Remove Core Audio sound implementation

master
Jens Ayton 2014-01-04 23:46:47 +01:00
parent 481b9a120b
commit ba8db00242
26 changed files with 7 additions and 4115 deletions

@ -1 +1 @@
Subproject commit 84aa2d70144a836c74832412fa445b703c2df187
Subproject commit 3df6ed027e4ef6955cb530e98b459870a68fc652

View File

@ -753,7 +753,6 @@
1A0519340C7CCAC900BA5CCA /* DebugBundle.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = DebugBundle.xcodeproj; path = "Mac-specific/DebugBundle/DebugBundle.xcodeproj"; sourceTree = "<group>"; };
1A062C8711B28D8A00727C1D /* NSObjectOOExtensions.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = NSObjectOOExtensions.h; sourceTree = "<group>"; };
1A062C8811B28D8A00727C1D /* NSObjectOOExtensions.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = NSObjectOOExtensions.m; sourceTree = "<group>"; };
1A06F2851196E5B100AFA5B4 /* OOCASoundDebugMonitor.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = OOCASoundDebugMonitor.h; sourceTree = "<group>"; };
1A06F3141196FB6F00AFA5B4 /* oolite-player-AI.plist */ = {isa = PBXFileReference; explicitFileType = text; fileEncoding = 4; path = "oolite-player-AI.plist"; sourceTree = "<group>"; };
1A0729D70EF56D1200B0F925 /* OOConvertSystemDescriptions.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = OOConvertSystemDescriptions.h; sourceTree = "<group>"; };
1A0729D80EF56D1200B0F925 /* OOConvertSystemDescriptions.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = OOConvertSystemDescriptions.m; sourceTree = "<group>"; };
@ -1272,8 +1271,6 @@
1A817DBE106D441200AA2F97 /* oolite-particle-flash.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = "oolite-particle-flash.png"; sourceTree = "<group>"; };
1A817DC1106D443B00AA2F97 /* OOFlashEffectEntity.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = OOFlashEffectEntity.h; sourceTree = "<group>"; };
1A817DC2106D443B00AA2F97 /* OOFlashEffectEntity.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = OOFlashEffectEntity.m; sourceTree = "<group>"; };
1A81F7070A7BAC4D006580AD /* OOCAMusic.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = OOCAMusic.m; sourceTree = "<group>"; };
1A81F7080A7BAC4D006580AD /* OOCAMusic.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = OOCAMusic.h; sourceTree = "<group>"; };
1A846BA90D79F9570081280D /* oolite-version.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = "oolite-version.xcconfig"; path = "src/Cocoa/oolite-version.xcconfig"; sourceTree = "<group>"; };
1A85AD0612EDCAC7000E1FCD /* OOJSPropID.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = OOJSPropID.h; sourceTree = "<group>"; };
1A85AE4D12EE0ED9000E1FCD /* OOViewID.tbl */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = OOViewID.tbl; sourceTree = "<group>"; };
@ -1603,25 +1600,6 @@
2512834409BA281500F43D55 /* CollisionRegion.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CollisionRegion.h; sourceTree = "<group>"; };
2512834509BA281500F43D55 /* CollisionRegion.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CollisionRegion.m; sourceTree = "<group>"; };
25160E2E0995362F0037C2E1 /* OOCocoa.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = OOCocoa.h; sourceTree = "<group>"; };
251610CA099544090037C2E1 /* OOCABufferedSound.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = OOCABufferedSound.h; sourceTree = "<group>"; };
251610CB099544090037C2E1 /* OOCASoundMixer.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = OOCASoundMixer.h; sourceTree = "<group>"; };
251610CD099544090037C2E1 /* OOCASoundChannel.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = OOCASoundChannel.h; sourceTree = "<group>"; };
251610CF099544090037C2E1 /* OOCASoundReferencePoint.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = OOCASoundReferencePoint.m; sourceTree = "<group>"; };
251610D0099544090037C2E1 /* OOCASound.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = OOCASound.h; sourceTree = "<group>"; };
251610D1099544090037C2E1 /* OOCASoundMixer.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = OOCASoundMixer.m; sourceTree = "<group>"; };
251610D2099544090037C2E1 /* OOCABufferedSound.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = OOCABufferedSound.m; sourceTree = "<group>"; };
251610D3099544090037C2E1 /* OOCAStreamingSound.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = OOCAStreamingSound.m; sourceTree = "<group>"; };
251610D4099544090037C2E1 /* OOCASoundDecoder.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = OOCASoundDecoder.h; sourceTree = "<group>"; };
251610D5099544090037C2E1 /* OOCASound.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = OOCASound.m; sourceTree = "<group>"; };
251610D6099544090037C2E1 /* OOCASoundChannel.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = OOCASoundChannel.m; sourceTree = "<group>"; };
251610D7099544090037C2E1 /* OOCAStreamingSound.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = OOCAStreamingSound.h; sourceTree = "<group>"; };
251610D8099544090037C2E1 /* OOErrorDescription.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = OOErrorDescription.h; sourceTree = "<group>"; };
251610D9099544090037C2E1 /* OOCASoundReferencePoint.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = OOCASoundReferencePoint.h; sourceTree = "<group>"; };
251610DA099544090037C2E1 /* OOCASoundInternal.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = OOCASoundInternal.h; sourceTree = "<group>"; };
251610DB099544090037C2E1 /* OOCASoundDecoder.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = OOCASoundDecoder.m; sourceTree = "<group>"; };
251610DC099544090037C2E1 /* OOErrorDescription.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = OOErrorDescription.m; sourceTree = "<group>"; };
251610F0099544190037C2E1 /* VirtualRingBuffer.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = VirtualRingBuffer.m; sourceTree = "<group>"; };
251610F1099544190037C2E1 /* VirtualRingBuffer.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = VirtualRingBuffer.h; sourceTree = "<group>"; };
25161101099544380037C2E1 /* AI.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; lineEnding = 0; path = AI.m; sourceTree = "<group>"; xcLanguageSpecificationIdentifier = xcode.lang.objc; };
25161102099544380037C2E1 /* OOXMLExtensions.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = OOXMLExtensions.m; sourceTree = "<group>"; };
25161106099544390037C2E1 /* AI.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; lineEnding = 0; path = AI.h; sourceTree = "<group>"; xcLanguageSpecificationIdentifier = xcode.lang.objcpp; };
@ -2389,7 +2367,6 @@
1ACBF0700D82DF9B00CC005F /* OOSoundSourcePool.m */,
1A7B967E0E620C9E00322821 /* OOSoundInternal.h */,
1AA085E81825788E007CCAEB /* OpenAL */,
1A8A3D8F0B9B058500AB7625 /* CoreAudio */,
);
name = Audio;
sourceTree = "<group>";
@ -2928,36 +2905,6 @@
name = Mathematics;
sourceTree = "<group>";
};
1A8A3D8F0B9B058500AB7625 /* CoreAudio */ = {
isa = PBXGroup;
children = (
251610D0099544090037C2E1 /* OOCASound.h */,
251610DA099544090037C2E1 /* OOCASoundInternal.h */,
251610D5099544090037C2E1 /* OOCASound.m */,
1A81F7080A7BAC4D006580AD /* OOCAMusic.h */,
1A81F7070A7BAC4D006580AD /* OOCAMusic.m */,
251610CA099544090037C2E1 /* OOCABufferedSound.h */,
251610D2099544090037C2E1 /* OOCABufferedSound.m */,
251610D7099544090037C2E1 /* OOCAStreamingSound.h */,
251610D3099544090037C2E1 /* OOCAStreamingSound.m */,
251610CB099544090037C2E1 /* OOCASoundMixer.h */,
251610D1099544090037C2E1 /* OOCASoundMixer.m */,
251610CD099544090037C2E1 /* OOCASoundChannel.h */,
251610D6099544090037C2E1 /* OOCASoundChannel.m */,
251610D9099544090037C2E1 /* OOCASoundReferencePoint.h */,
251610CF099544090037C2E1 /* OOCASoundReferencePoint.m */,
251610D4099544090037C2E1 /* OOCASoundDecoder.h */,
251610DB099544090037C2E1 /* OOCASoundDecoder.m */,
251610D8099544090037C2E1 /* OOErrorDescription.h */,
251610DC099544090037C2E1 /* OOErrorDescription.m */,
251610F1099544190037C2E1 /* VirtualRingBuffer.h */,
251610F0099544190037C2E1 /* VirtualRingBuffer.m */,
1A06F2851196E5B100AFA5B4 /* OOCASoundDebugMonitor.h */,
);
name = CoreAudio;
path = ../Cocoa;
sourceTree = "<group>";
};
1AA085E81825788E007CCAEB /* OpenAL */ = {
isa = PBXGroup;
children = (

View File

@ -1,52 +0,0 @@
/*
OOCABufferedSound.h
Subclass of OOSound playing from an in-memory buffer.
This class is an implementation detail. Do not use it directly; use OOSound.
OOCASound - Core Audio sound implementation for Oolite.
Copyright (C) 2005-2013 Jens Ayton
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#import <Cocoa/Cocoa.h>
#import "OOCASound.h"
@class OOCASoundDecoder;
@interface OOCABufferedSound: OOSound
{
@private
float *_bufferL,
*_bufferR;
size_t _size;
Float64 _sampleRate;
NSString *_name;
BOOL _stereo;
}
- (id)initWithDecoder:(OOCASoundDecoder *)inDecoder;
@end

View File

@ -1,196 +0,0 @@
/*
OOCABufferedSound.m
OOCASound - Core Audio sound implementation for Oolite.
Copyright (C) 2005-2013 Jens Ayton
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#import "OOCASoundInternal.h"
#import "OOCASoundDecoder.h"
@interface OOCABufferedSound (Private)
- (BOOL)bufferSound:(NSString *)inPath;
@end
@implementation OOCABufferedSound
#pragma mark NSObject
- (void)dealloc
{
free(_bufferL);
_bufferL = NULL;
if (_stereo) free(_bufferR);
_bufferR = NULL;
[super dealloc];
}
- (NSString *)description
{
return [NSString stringWithFormat:@"<%@ %p>{\"%@\", %s, %g Hz, %lu bytes}", [self className], self, [self name], _stereo ? "stereo" : "mono", _sampleRate, _size * sizeof (float) * (_stereo ? 2 : 1)];
}
#pragma mark OOSound
- (NSString *)name
{
return _name;
}
- (BOOL)getAudioStreamBasicDescription:(AudioStreamBasicDescription *)outFormat
{
assert(NULL != outFormat);
outFormat->mSampleRate = _sampleRate;
outFormat->mFormatID = kAudioFormatLinearPCM;
outFormat->mFormatFlags = kAudioFormatFlagsNativeFloatPacked | kLinearPCMFormatFlagIsNonInterleaved;
outFormat->mBytesPerPacket = sizeof (float);
outFormat->mFramesPerPacket = 1;
outFormat->mBytesPerFrame = sizeof (float);
outFormat->mChannelsPerFrame = 2;
outFormat->mBitsPerChannel = sizeof (float) * 8;
outFormat->mReserved = 0;
return YES;
}
// Context is (offset << 1) | loop. Offset is initially 0.
- (BOOL)prepareToPlayWithContext:(OOCASoundRenderContext *)outContext looped:(BOOL)inLoop
{
*outContext = inLoop ? 1 : 0;
return YES;
}
- (OSStatus)renderWithFlags:(AudioUnitRenderActionFlags *)ioFlags frames:(UInt32)inNumFrames context:(OOCASoundRenderContext *)ioContext data:(AudioBufferList *)ioData
{
size_t toCopy, remaining, underflow, offset;
BOOL loop, done = NO;
loop = (*ioContext) & 1;
offset = (*ioContext) >> 1;
assert (ioData->mNumberBuffers == 2);
if (offset < _size)
{
remaining = _size - offset;
if (remaining < inNumFrames)
{
toCopy = remaining;
underflow = inNumFrames - remaining;
}
else
{
toCopy = inNumFrames;
underflow = 0;
}
memcpy(ioData->mBuffers[0].mData, _bufferL + offset, toCopy * sizeof (float));
memcpy(ioData->mBuffers[1].mData, _bufferR + offset, toCopy * sizeof (float));
if (underflow && loop)
{
offset = toCopy;
toCopy = inNumFrames - toCopy;
if (_size < toCopy) toCopy = _size;
memcpy(((float *)ioData->mBuffers[0].mData) + offset, _bufferL, toCopy * sizeof (float));
memcpy(((float *)ioData->mBuffers[1].mData) + offset, _bufferR, toCopy * sizeof (float));
underflow -= toCopy;
offset = 0;
}
*ioContext = ((offset + toCopy) << 1) | loop;
}
else
{
toCopy = 0;
underflow = inNumFrames;
*ioFlags |= kAudioUnitRenderAction_OutputIsSilence;
done = YES;
}
if (underflow)
{
memset(ioData->mBuffers[0].mData + toCopy, 0, underflow * sizeof (float));
memset(ioData->mBuffers[1].mData + toCopy, 0, underflow * sizeof (float));
}
OOCASoundVerifyBuffers(ioData, inNumFrames, self);
return done ? endOfDataReached : noErr;
}
#pragma mark OOCABufferedSound
- (id)initWithDecoder:(OOCASoundDecoder *)inDecoder
{
BOOL OK = YES;
assert(gOOSoundSetUp);
if (gOOSoundBroken || nil == inDecoder) OK = NO;
if (OK)
{
self = [super init];
if (nil == self) OK = NO;
}
if (OK)
{
_name = [[inDecoder name] copy];
_sampleRate = [inDecoder sampleRate];
if ([inDecoder isStereo])
{
OK = [inDecoder readStereoCreatingLeftBuffer:&_bufferL rightBuffer:&_bufferR withFrameCount:&_size];
_stereo = YES;
}
else
{
OK = [inDecoder readMonoCreatingBuffer:&_bufferL withFrameCount:&_size];
_bufferR = _bufferL;
}
}
if (!OK)
{
[self release];
self = nil;
}
return self;
}
@end

View File

@ -1,46 +0,0 @@
/*
OOCAMusic.h
Subclass of OOSound with additional controls specific to music playback. Only
one instance of OOMusic may be playing at a time.
OOCASound - Core Audio sound implementation for Oolite.
Copyright (C) 2005-2013 Jens Ayton
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#import <Cocoa/Cocoa.h>
#import "OOCASound.h"
@interface OOMusic: OOSound
{
@private
OOSound *sound;
}
- (void) playLooped:(BOOL)looped;
- (void) stop;
- (BOOL) isPlaying;
@end

View File

@ -1,113 +0,0 @@
/*
OOCAMusic.m
OOCASound - Core Audio sound implementation for Oolite.
Copyright (C) 2005-2013 Jens Ayton
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#import "OOCASoundInternal.h"
static OOMusic *sPlayingMusic = nil;
static OOSoundSource *sMusicSource = nil;
@implementation OOMusic
#pragma mark NSObject
+ (id)allocWithZone:(NSZone *)inZone
{
return NSAllocateObject([OOMusic class], 0, inZone);
}
- (void)dealloc
{
if (sPlayingMusic == self) [self stop];
[sound release];
[super dealloc];
}
#pragma mark OOSound
- (id)initWithContentsOfFile:(NSString *)inPath
{
self = [super init];
if (nil != self)
{
sound = [[OOSound alloc] initWithContentsOfFile:inPath];
if (nil == sound)
{
[self release];
self = nil;
}
}
return self;
}
- (NSString *)name
{
return [sound name];
}
#pragma mark OOMusic
- (void)playLooped:(BOOL)inLoop
{
if (sPlayingMusic != self)
{
if (nil == sMusicSource)
{
sMusicSource = [[OOSoundSource alloc] init];
}
[sMusicSource stop];
[sMusicSource setLoop:inLoop];
[sMusicSource setSound:sound];
[sMusicSource play];
sPlayingMusic = self;
}
}
- (BOOL)isPlaying
{
return sPlayingMusic == self && [sMusicSource isPlaying];
}
- (void)stop
{
if (sPlayingMusic == self)
{
sPlayingMusic = nil;
[sMusicSource stop];
}
}
@end

View File

@ -1,50 +0,0 @@
/*
OOCASound.h
Abstract base class for sounds, and primary sound loading interface.
OOCASound - Core Audio sound implementation for Oolite.
Copyright (C) 2005-2013 Jens Ayton
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#import <Cocoa/Cocoa.h>
@interface OOSound: NSObject
{
@private
uint32_t _playingCount;
}
+ (void) setUp;
+ (void) update;
+ (void) setMasterVolume:(float) fraction;
+ (float) masterVolume;
- (id) initWithContentsOfFile:(NSString *)path;
- (NSString *)name;
@end

View File

@ -1,390 +0,0 @@
/*
OOCASound.m
OOCASound - Core Audio sound implementation for Oolite.
Copyright (C) 2005-2013 Jens Ayton
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
/* OOSound is a class cluster. A single OOSound object exists, which
represents a sound that has been alloced but not inited. The designated
initialiser returns a concrete subclass, either OOCABufferedSound or
OOCAStreamingSound, depending on the size of the sound data.
*/
#import "OOCASoundInternal.h"
#import "OOCASoundDecoder.h"
#import <CoreAudio/CoreAudio.h>
#import <AudioToolbox/AudioToolbox.h>
#import "NSThreadOOExtensions.h"
#import "OOCollectionExtractors.h"
#define KEY_VOLUME_CONTROL @"volume_control"
#define KEY_MAX_BUFFERED_SOUND @"max_buffered_sound"
NSString * const kOOLogDeprecatedMethodOOCASound = @"general.error.deprecatedMethod.oocasound";
NSString * const kOOLogSoundInitError = @"sound.initialization.error";
static NSString * const kOOLogSoundLoadingSuccess = @"sound.load.success";
static NSString * const kOOLogSoundLoadingError = @"sound.load.error";
static float sNominalVolume = 1.0f;
BOOL gOOSoundSetUp = NO;
BOOL gOOSoundBroken = NO;
NSRecursiveLock *gOOCASoundSyncLock = nil; // Used to ensure thread-safety of play and stop, specifically because stop may be called from the CoreAudio thread.
static OOSound *sSingletonOOSound = nil;
static int sMaxBufferedSoundSize = 1 << 20; // 1 MB
#ifndef NDEBUG
static struct
{
BOOL hasData;
float badVal;
OOSound *badSound;
} sSoundError;
#import <Foundation/NSDebug.h>
#endif
@implementation OOSound
#pragma mark NSObject
+ (id)allocWithZone:(NSZone *)inZone
{
if (self != [OOSound class]) return [super allocWithZone:inZone];
if (nil == sSingletonOOSound)
{
sSingletonOOSound = [super allocWithZone:inZone];
}
return sSingletonOOSound;
}
- (id)init
{
if ([self isMemberOfClass:[OOSound class]])
{
[self release];
return nil;
}
else
{
return [super init];
}
}
- (void)dealloc
{
if (self == sSingletonOOSound) sSingletonOOSound = nil;
[super dealloc];
}
- (NSString *)description
{
if ([self isMemberOfClass:[OOSound class]])
{
return [NSString stringWithFormat:@"<%@ %p>(singleton placeholder)", [self className], self];
}
else
{
return [NSString stringWithFormat:@"<%@ %p>{\"%@\"}", [self className], self, [self name]];
}
}
#pragma mark OOSound
/*
SLOW_CODE +setUp takes up about 5% of launch time (measured with a light
OXP load), mostly in setting up the AUGraph -- much more than the actual
sound preloading. Setup should be easyish to do asynchronously.
-- Ahruman 2012-09-14
*/
+ (void) setUp
{
NSUserDefaults *prefs = nil;
if (!gOOSoundSetUp)
{
gOOCASoundSyncLock = [[NSRecursiveLock alloc] init];
[gOOCASoundSyncLock setName:@"OOCASound synchronization lock"];
if (nil == gOOCASoundSyncLock)
{
OOLog(kOOLogSoundInitError, @"Failed to set up sound (lock allocation failed). No sound will be played.");
gOOSoundBroken = YES;
}
if (!gOOSoundBroken)
{
if (![OOSoundChannel setUp]) gOOSoundBroken = YES;
}
gOOSoundSetUp = YES; // Must be before [OOSoundMixer sharedMixer] below.
prefs = [NSUserDefaults standardUserDefaults];
if ([prefs objectForKey:KEY_VOLUME_CONTROL]) sNominalVolume = [prefs floatForKey:KEY_VOLUME_CONTROL];
else sNominalVolume = 0.75; // default setting at 75% system volume
[[OOSoundMixer sharedMixer] setMasterVolume:sNominalVolume];
int maxSize = [prefs oo_intForKey:KEY_MAX_BUFFERED_SOUND defaultValue:sMaxBufferedSoundSize];
if (0 <= maxSize) sMaxBufferedSoundSize = maxSize;
}
}
+ (void) update
{
[[OOSoundMixer sharedMixer] update];
#ifndef NDEBUG
if (sSoundError.hasData)
{
float badVal = sSoundError.badVal;
OOSound *badSound = sSoundError.badSound;
sSoundError.hasData = NO;
NSString *desc = nil;
if (NSIsFreedObject(badSound)) desc = [NSString stringWithFormat:@"released sound %p", badSound];
else desc = [badSound description];
OOLog(@"sound.renderingError", @"Sound rendering error detected for sound %@ (bad value: %f)", desc, badVal);
}
#endif
}
+ (void) setMasterVolume:(float)fraction
{
if (fraction != sNominalVolume)
{
[[OOSoundMixer sharedMixer] setMasterVolume:fraction];
sNominalVolume = fraction;
[[NSUserDefaults standardUserDefaults] setFloat:fraction forKey:KEY_VOLUME_CONTROL];
}
}
+ (float) masterVolume
{
return sNominalVolume;
}
/* Designated initialiser for OOSound.
Note: OOSound is a class cluster. This will always return a subclass of OOSound.
*/
- (id) initWithContentsOfFile:(NSString *)inPath
{
OOCASoundDecoder *decoder;
if (!gOOSoundSetUp) [OOSound setUp];
decoder = [[OOCASoundDecoder alloc] initWithPath:inPath];
if (nil == decoder) return nil;
if ([decoder sizeAsBuffer] <= (size_t)sMaxBufferedSoundSize)
{
self = [[OOCABufferedSound alloc] initWithDecoder:decoder];
}
else
{
self = [[OOCAStreamingSound alloc] initWithDecoder:decoder];
}
[decoder release];
if (nil != self)
{
#ifndef NDEBUG
OOLog(kOOLogSoundLoadingSuccess, @"Loaded sound %@", self);
#endif
}
else
{
OOLog(kOOLogSoundLoadingError, @"Failed to load sound \"%@\"", inPath);
}
return self;
}
- (id)initWithDecoder:(OOCASoundDecoder *)inDecoder
{
[self release];
return nil;
}
- (OSStatus)renderWithFlags:(AudioUnitRenderActionFlags *)ioFlags frames:(UInt32)inNumFrames context:(OOCASoundRenderContext *)ioContext data:(AudioBufferList *)ioData
{
OOLog(@"general.error.subclassResponsibility.OOCASound-renderWithFlags", @"%s shouldn't be called - subclass responsibility.", __PRETTY_FUNCTION__);
return unimpErr;
}
- (void)incrementPlayingCount
{
++_playingCount;
}
- (void)decrementPlayingCount
{
//assert(0 != _playingCount);
if (EXPECT(_playingCount != 0)) --_playingCount;
else OOLog(@"sound.playUnderflow", @"Playing count for %@ dropped below 0!", self);
}
- (BOOL) isPlaying
{
return 0 != _playingCount;
}
- (uint32_t)playingCount
{
return _playingCount;
}
- (BOOL)prepareToPlayWithContext:(OOCASoundRenderContext *)outContext looped:(BOOL)inLoop
{
return YES;
}
- (void)finishStoppingWithContext:(OOCASoundRenderContext)inContext
{
}
- (BOOL)doPlay
{
return YES;
}
- (BOOL)doStop
{
return YES;
}
- (NSString *)name
{
return nil;
}
- (BOOL)getAudioStreamBasicDescription:(AudioStreamBasicDescription *)outFormat
{
return NO;
}
@end
#ifndef NDEBUG
static BOOL VerifyOneBuffer(AudioBuffer *buffer, NSUInteger numFrames, float *badVal);
void OOCASoundVerifyBuffers(AudioBufferList *buffers, NSUInteger numFrames, OOSound *sound)
{
BOOL allOK = YES;
UInt32 i;
float badVal = 0.0;
for (i = 0; i < buffers->mNumberBuffers; i++)
{
if (!VerifyOneBuffer(&buffers->mBuffers[i], numFrames, &badVal))
{
allOK = NO;
}
}
if (!allOK && !sSoundError.hasData)
{
sSoundError.badSound = sound;
sSoundError.badVal = badVal;
sSoundError.hasData = YES; // Must be last!
}
}
static BOOL VerifyOneBuffer(AudioBuffer *buffer, NSUInteger numFrames, float *badVal)
{
if (buffer == NULL || buffer->mData == NULL || badVal == NULL) return NO;
*badVal = 0.0;
if (numFrames * sizeof(float) > buffer->mDataByteSize)
{
memset(buffer->mData, 0, buffer->mDataByteSize);
return NO;
}
// Assume data is float.
float *floatBuffer = (float *)buffer->mData;
NSUInteger i;
BOOL OK = YES;
BOOL worstAbnormal = NO;
for (i = 0; i < numFrames; i++)
{
float val = floatBuffer[i];
BOOL abnormal = isnan(val) || !isfinite(val);
if (abnormal || (fabs(val) > kOOAudioSlop))
{
if (abnormal || (!abnormal && !worstAbnormal && fabs(*badVal < fabs(val))))
{
worstAbnormal = abnormal;
*badVal = val;
}
OK = NO;
}
}
if (OK == NO)
{
memset(buffer->mData, 0, buffer->mDataByteSize);
}
return OK;
}
#endif

View File

@ -1,98 +0,0 @@
/*
OOCASoundChannel.h
A channel for audio playback.
This class is an implementation detail. Do not use it directly; use an
OOSoundSource to play an OOSound.
OOCASound - Core Audio sound implementation for Oolite.
Copyright (C) 2005-2013 Jens Ayton
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#import <Foundation/Foundation.h>
#import <AudioToolbox/AudioToolbox.h>
#import "OOCASoundDebugMonitor.h"
@class OOSound;
typedef uintptr_t OOCASoundRenderContext;
typedef OSStatus (*OOSoundChannel_RenderIMP)(id inSelf, SEL inSelector, AudioUnitRenderActionFlags *ioFlags, UInt32 inNumFrames, OOCASoundRenderContext *ioContext, AudioBufferList *ioData);
@interface OOSoundChannel: NSObject
{
@private
OOSoundChannel *_next;
id _delegate;
AUNode _subGraphNode;
AUGraph _subGraph;
AUNode _node;
AudioUnit _au;
OOSound *_sound;
OOCASoundRenderContext _context;
OOSoundChannel_RenderIMP Render;
uint8_t _state,
_id,
_stopReq;
OSStatus _error;
}
+ (BOOL)setUp;
+ (void)tearDown;
- (id)initWithID:(uint32_t)inID auGraph:(AUGraph)inGraph;
- (void)setDelegate:(id)inDelegate;
- (uint32_t)ID;
- (AUNode)auSubGraphNode;
// Unretained pointer used to maintain simple stack
- (OOSoundChannel *)next;
- (void)setNext:(OOSoundChannel *)inNext;
- (BOOL)playSound:(OOSound *)inSound looped:(BOOL)inLoop;
- (void)stop;
- (OOSound *)sound;
- (BOOL)isOK;
#ifndef NDEBUG
- (OOCASoundDebugMonitorChannelState) soundInspectorState;
#endif
@end
@interface NSObject(OOSoundChannelDelegate)
// Note: this will be called in a separate thread.
- (void)channel:(OOSoundChannel *)inChannel didFinishPlayingSound:(OOSound *)inSound;
@end

View File

@ -1,734 +0,0 @@
/*
OOCASoundChannel.m
OOCASound - Core Audio sound implementation for Oolite.
Copyright (C) 2005-2013 Jens Ayton
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#import "OOCASoundChannel.h"
#import "OOCASoundInternal.h"
#import <mach/mach.h>
#import <pthread.h>
#import "NSThreadOOExtensions.h"
static NSString * const kOOLogSoundNULLError = @"sound.render.undexpectedNull";
static NSString * const kOOLogSoundBadStateError = @"sound.render.badState";
static NSString * const kOOLogSoundPlaySuccess = @"sound.play.success";
static NSString * const kOOLogSoundBadReuse = @"sound.play.failed.badReuse";
static NSString * const kOOLogSoundSetupFailed = @"sound.play.failed.setupFailed";
static NSString * const kOOLogSoundPlayAUError = @"sound.play.failed.auError";
static NSString * const kOOLogSoundPlayUnknownError = @"sound.play.failed";
static NSString * const kOOLogSoundCleanUpSuccess = @"sound.channel.cleanup.success";
static NSString * const kOOLogSoundCleanUpBroken = @"sound.channel.cleanup.failed.broken";
static NSString * const kOOLogSoundCleanUpBadState = @"sound.channel.cleanup.failed.badState";
static NSString * const kOOLogSoundMachPortError = @"sound.channel.machPortError";
#ifndef NDEBUG
// Tracks a kind of error that isnt happening any more.
#define COUNT_NULLS 1
#endif
static mach_port_t sReapPort = MACH_PORT_NULL;
static mach_port_t sStatusPort = MACH_PORT_NULL;
static BOOL sReaperRunning = NO;
static OOSoundChannel_RenderIMP SoundChannelRender = NULL;
#if COUNT_NULLS
static int32_t sDebugUnexpectedNullCount = 0;
#endif
/*
When a channel finishes playing, it is put in theplay thread dead list.At the end of each
sound callback, if the play thread dead list is not empty and the reap queue mutex can be
acquired, the play thread dead list is copied to the reap queue under the mutex. This allows us
to use a mutex-protected list to communicate with the reap queue without having to wait on the
mutex in the real-time thread.
*/
static OOSoundChannel *sPlayThreadDeadList = NULL;
static OOSoundChannel *sReapQueue = NULL;
static pthread_mutex_t sReapQueueMutex = { 0 };
typedef enum
{
kState_Stopped,
kState_Playing,
kState_Ended,
kState_Reap,
kState_Broken
} States;
#define kAURenderSelector @selector(renderWithFlags:frames:context:data:)
@interface OOSoundChannel(Private)
+ (void)reaperThread:junk;
- (void)reap;
- (void)cleanUp;
- (OSStatus)renderWithFlags:(AudioUnitRenderActionFlags *)ioFlags frames:(UInt32)inNumFrames context:(OOCASoundRenderContext *)ioContext data:(AudioBufferList *)ioData;
@end
enum
{
// Port messages
kMsgThreadUp = 1UL,
kMsgDie,
kMsgThreadDied,
kMsgWakeUp
};
typedef struct
{
uintptr_t tag;
void *value;
} PortMessage;
typedef struct
{
mach_msg_header_t header;
mach_msg_size_t descCount;
mach_msg_descriptor_t descriptor;
PortMessage message;
} PortSendMsgBody;
typedef struct
{
mach_msg_header_t header;
mach_msg_size_t descCount;
mach_msg_descriptor_t descriptor;
PortMessage message;
mach_msg_trailer_t trailer;
} PortWaitMsgBody;
static OSStatus ChannelRenderProc(void *inRefCon, AudioUnitRenderActionFlags *ioFlags, const AudioTimeStamp *inTimeStamp, UInt32 inBusNumber, UInt32 inNumFrames, AudioBufferList *ioData);
static mach_port_t CreatePort(void);
static void PortSend(mach_port_t inPort, PortMessage inMessage);
static BOOL PortWait(mach_port_t inPort, PortMessage *outMessage);
@implementation OOSoundChannel
+ (BOOL)setUp
{
BOOL OK = YES;
PortMessage message;
if (sReaperRunning) return YES;
SoundChannelRender = (OOSoundChannel_RenderIMP)[OOSoundChannel instanceMethodForSelector:kAURenderSelector];
if (NULL == SoundChannelRender) OK = NO;
if (OK)
{
sReapPort = CreatePort();
if (MACH_PORT_NULL == sReapPort) OK = NO;
}
if (OK)
{
sStatusPort = CreatePort();
if (MACH_PORT_NULL == sStatusPort) OK = NO;
}
if (OK)
{
if (0 != pthread_mutex_init(&sReapQueueMutex, NULL)) OK = NO;
}
if (OK)
{
[NSThread detachNewThreadSelector:@selector(reaperThread:) toTarget:self withObject:nil];
OK = PortWait(sStatusPort, &message);
if (OK)
{
if (kMsgThreadUp != message.tag) OK = NO;
}
}
if (!OK)
{
OOLog(kOOLogSoundInitError, @"Failed to set up sound (channel queue allocation failed). No sound will be played.");
}
return OK;
}
+ (void)tearDown
{
ipc_space_t task;
PortMessage message = { kMsgDie, NULL };
if (sReaperRunning)
{
PortSend(sReapPort, message);
PortWait(sStatusPort, &message);
}
task = mach_task_self();
if (MACH_PORT_NULL != sReapPort) mach_port_destroy(task, sReapPort);
if (MACH_PORT_NULL != sStatusPort) mach_port_destroy(task, sStatusPort);
}
+ (void)reaperThread:junk
{
PortMessage message = { kMsgThreadUp, NULL };
OOSoundChannel *chan;
NSAutoreleasePool *pool = nil;
[NSThread ooSetCurrentThreadName:@"OOSoundChannel reaper thread"];
sReaperRunning = YES;
PortSend(sStatusPort, message);
[NSThread setThreadPriority:0.5];
for (;;)
{
if (PortWait(sReapPort, &message))
{
pool = [[NSAutoreleasePool alloc] init];
if (kMsgWakeUp == message.tag)
{
assert (!pthread_mutex_lock(&sReapQueueMutex));
while (sReapQueue)
{
chan = sReapQueue;
sReapQueue = chan->_next;
if (kState_Reap == chan->_state) [chan reap];
[chan cleanUp];
}
pthread_mutex_unlock(&sReapQueueMutex);
}
else if (kMsgDie == message.tag)
{
[pool release];
break;
}
[pool release];
}
}
message.tag = kMsgThreadDied;
message.value = NULL;
sReaperRunning = NO;
PortSend(sStatusPort, message);
}
- (id)init
{
[self release];
return nil;
}
- (id)initWithID:(uint32_t)inID auGraph:(AUGraph)inGraph
{
OSStatus err = noErr;
AudioComponentDescription desc;
AURenderCallbackStruct input;
assert(sReaperRunning);
self = [super init];
if (nil != self)
{
_id = inID;
// Create a subgraph (since we cant have multiple output units otherwise)
err = AUGraphNewNodeSubGraph(inGraph, &_subGraphNode);
if (!err) err = AUGraphGetNodeInfoSubGraph(inGraph, _subGraphNode, &_subGraph);
// Create an output unit
desc.componentType = kAudioUnitType_Output;
desc.componentSubType = kAudioUnitSubType_GenericOutput;
desc.componentManufacturer = kAudioUnitManufacturer_Apple;
desc.componentFlags = 0;
desc.componentFlagsMask = 0;
if (!err) err = AUGraphAddNode(_subGraph, &desc, &_node);
if (!err) err = AUGraphNodeInfo(_subGraph, _node, NULL, &_au);
// Set render callback
input.inputProc = ChannelRenderProc;
input.inputProcRefCon = self;
if (!err) err = AudioUnitSetProperty(_au, kAudioUnitProperty_SetRenderCallback,
kAudioUnitScope_Input, 0, &input, sizeof input);
// Init & check errors
if (!err) err = AudioUnitInitialize(_au);
if (err)
{
OOLog(kOOLogSoundInitError, @"AudioUnit setup error %@ preparing channel ID %u.", AudioErrorNSString(err), inID);
[self release];
self = nil;
}
}
return self;
}
- (void)dealloc
{
[self stop];
if (NULL != _au) CloseComponent(_au);
[super dealloc];
}
- (void)setDelegate:(id)inDelegate
{
_delegate = inDelegate;
}
- (uint32_t)ID
{
return _id;
}
- (AUNode)auSubGraphNode
{
return _subGraphNode;
}
- (OOSoundChannel *)next
{
return _next;
}
- (void)setNext:(OOSoundChannel *)inNext
{
_next = inNext;
}
- (OOSound *)sound
{
return _sound;
}
- (BOOL)playSound:(OOSound *)inSound looped:(BOOL)inLooped
{
BOOL OK = YES;
OSStatus err = noErr;
AudioStreamBasicDescription format;
OOSound *temp;
#if COUNT_NULLS
SInt32 unexpectedNulls;
unexpectedNulls = sDebugUnexpectedNullCount;
if (0 != unexpectedNulls)
{
OSAtomicAdd32(-unexpectedNulls, &sDebugUnexpectedNullCount);
OOLog(kOOLogSoundNULLError, @"%u NULL Render() or nil _sound errors have occured.", (unsigned int)unexpectedNulls);
}
#endif
if (nil != inSound)
{
[gOOCASoundSyncLock lock];
if (kState_Stopped != _state)
{
OOLog(kOOLogSoundBadReuse, @"Channel %@ reused while playing.", self);
[[OOSoundMixer sharedMixer] disconnectChannel:self];
if (_sound)
{
Render = NULL;
temp = _sound;
_sound = nil;
[temp finishStoppingWithContext:_context];
_context = 0;
[temp release];
}
_stopReq = NO;
_state = kState_Stopped;
}
Render = (OOSoundChannel_RenderIMP)[inSound methodForSelector:kAURenderSelector];
OK = (NULL != Render);
if (OK) OK = [inSound getAudioStreamBasicDescription:&format];
if (OK) OK = [inSound prepareToPlayWithContext:&_context looped:inLooped];
if (!OK)
{
OOLog(kOOLogSoundSetupFailed, @"Failed to play sound %@ - set-up failed.", inSound);
}
if (OK)
{
_sound = inSound;
err = AudioUnitSetProperty(_au, kAudioUnitProperty_StreamFormat,
kAudioUnitScope_Input, 0, &format, sizeof format);
if (err) OOLog(kOOLogSoundPlayAUError, @"Failed to play %@ (error %@)", inSound, AudioErrorNSString(err));
OK = !err;
}
if (OK) OK = [[OOSoundMixer sharedMixer] connectChannel:self];
if (OK)
{
[_sound retain];
_state = kState_Playing;
OOLog(kOOLogSoundPlaySuccess, @"Playing sound %@", _sound);
}
else
{
_sound = nil;
if (!err) OOLog(kOOLogSoundPlayUnknownError, @"Failed to play %@", inSound);
}
[gOOCASoundSyncLock unlock];
}
return OK;
}
- (void)stop
{
if (kState_Playing == _state)
{
_stopReq = YES;
}
if (kState_Ended == _state) [self cleanUp];
}
- (void)reap
{
OSStatus err;
err = [[OOSoundMixer sharedMixer] disconnectChannel:self];
if (noErr == err)
{
_state = kState_Ended;
}
else
{
_state = kState_Broken;
_error = err;
}
}
- (void)cleanUp
{
OOSound *sound;
[gOOCASoundSyncLock lock];
if (kState_Broken == _state)
{
OOLog(kOOLogSoundCleanUpBroken, @"Sound channel %@ broke with error %@.", self, AudioErrorNSString(_error));
}
if (kState_Ended == _state || kState_Broken == _state)
{
Render = NULL;
sound = _sound;
_sound = nil;
[sound finishStoppingWithContext:_context];
_context = 0;
_state = kState_Stopped;
_stopReq = NO;
if (nil != _delegate && [_delegate respondsToSelector:@selector(channel:didFinishPlayingSound:)])
{
[_delegate channel:self didFinishPlayingSound:sound];
}
[sound release];
OOLog(kOOLogSoundCleanUpSuccess, @"Sound channel id %u cleaned up successfully.", _id);
}
else
{
OOLog(kOOLogSoundCleanUpBadState, @"Sound channel %@ cleaned up in invalid state %u.", self, _state);
}
[gOOCASoundSyncLock unlock];
}
- (BOOL)isOK
{
return kState_Broken != _state;
}
#ifndef NDEBUG
- (OOCASoundDebugMonitorChannelState) soundInspectorState
{
switch ((States)_state)
{
case kState_Stopped:
return kOOCADebugStateIdle;
case kState_Playing:
return kOOCADebugStatePlaying;
case kState_Ended:
case kState_Reap:
case kState_Broken:
return kOOCADebugStateOther;
}
return kOOCADebugStateOther;
}
#endif
- (NSString *)description
{
NSString *result, *stateString = nil;
[gOOCASoundSyncLock lock];
switch ((States)_state)
{
case kState_Stopped:
stateString = @"stopped";
break;
case kState_Playing:
stateString = @"playing";
break;
case kState_Ended:
stateString = @"ended";
break;
case kState_Reap:
stateString = @"waiting to be reaped";
break;
case kState_Broken:
stateString = [NSString stringWithFormat:@"broken (%@)", AudioErrorShortNSString(_error)];
break;
}
if (stateString == nil)
{
stateString = [NSString stringWithFormat:@"unknown (%u)", _state];
}
result = [NSString stringWithFormat:@"<%@ %p>{ID=%u, state=%@, sound=%@}", [self className], self, _id, stateString, _sound];
[gOOCASoundSyncLock unlock];
return result;
}
- (OSStatus)renderWithFlags:(AudioUnitRenderActionFlags *)ioFlags frames:(UInt32)inNumFrames context:(OOCASoundRenderContext *)ioContext data:(AudioBufferList *)ioData
{
OSStatus err = noErr;
PortMessage message;
BOOL renderSilence = NO;
if (EXPECT_NOT(_stopReq)) err = endOfDataReached;
else if (EXPECT(kState_Playing == _state))
{
if (NULL != Render && nil != _sound)
{
err = Render(_sound, kAURenderSelector, ioFlags, inNumFrames, &_context, ioData);
}
else
{
err = endOfDataReached;
renderSilence = YES;
#if COUNT_NULLS
// Logging in real-time thread _baaaaaad_.
if (NULL == Render || nil == _sound)
{
OSAtomicAdd32(1, &sDebugUnexpectedNullCount);
}
#endif
}
}
else
{
renderSilence = YES;
}
if (EXPECT_NOT(renderSilence))
{
unsigned i, count = ioData->mNumberBuffers;
for (i = 0; i != count; i++)
{
memset(ioData->mBuffers[i].mData, 0, ioData->mBuffers[i].mDataByteSize);
}
*ioFlags |= kAudioUnitRenderAction_OutputIsSilence;
}
if (EXPECT_NOT(endOfDataReached == err))
{
err = noErr;
if (EXPECT(kState_Playing == _state))
{
_state = kState_Reap;
_next = sPlayThreadDeadList;
sPlayThreadDeadList = self;
}
}
if (EXPECT_NOT(nil != sPlayThreadDeadList && !pthread_mutex_trylock(&sReapQueueMutex)))
{
// Put sPlayThreadDeadList at front of sReapQueue
OOSoundChannel *curr;
curr = sPlayThreadDeadList;
while (nil != curr->_next) curr = curr->_next;
curr->_next = sReapQueue;
sReapQueue = sPlayThreadDeadList;
sPlayThreadDeadList = nil;
pthread_mutex_unlock(&sReapQueueMutex);
// Wake up reaper thread
message.tag = kMsgWakeUp;
message.value = NULL;
PortSend(sReapPort, message);
}
return err;
}
@end
static OSStatus ChannelRenderProc(void *inRefCon, AudioUnitRenderActionFlags *ioFlags, const AudioTimeStamp *inTimeStamp, UInt32 inBusNumber, UInt32 inNumFrames, AudioBufferList *ioData)
{
return SoundChannelRender((id)inRefCon, kAURenderSelector, ioFlags, inNumFrames, 0, ioData);
}
static mach_port_t CreatePort(void)
{
kern_return_t err;
mach_port_t result;
ipc_space_t task;
mach_msg_type_name_t type;
mach_port_t sendRight;
task = mach_task_self();
err = mach_port_allocate(task, MACH_PORT_RIGHT_RECEIVE, &result);
if (KERN_SUCCESS == err) err = mach_port_insert_right(task, result, result, MACH_MSG_TYPE_MAKE_SEND);
if (KERN_SUCCESS == err) err = mach_port_extract_right(task, result, MACH_MSG_TYPE_MAKE_SEND, &sendRight, &type);
if (KERN_SUCCESS != err)
{
OOLog(kOOLogSoundInitError, @"Mach port creation failure: %@", KernelResultNSString(err));
result = MACH_PORT_NULL;
}
return result;
}
static void PortSend(mach_port_t inPort, PortMessage inMessage)
{
PortSendMsgBody message;
mach_msg_return_t result;
memset(&message, 0, sizeof message);
message.header.msgh_bits = MACH_MSGH_BITS_REMOTE(MACH_MSG_TYPE_MAKE_SEND);
message.header.msgh_size = sizeof message;
message.header.msgh_remote_port = inPort;
message.header.msgh_local_port = MACH_PORT_NULL;
message.descCount = 1;
message.message = inMessage;
result = mach_msg(&message.header, MACH_SEND_MSG | MACH_SEND_TIMEOUT, sizeof message, 0, MACH_PORT_NULL, 0, MACH_PORT_NULL);
if (MACH_MSG_SUCCESS != result)
{
OOLog(kOOLogSoundMachPortError, @"Mach port transient send failure: %@", KernelResultNSString(result));
result = mach_msg(&message.header, MACH_SEND_MSG, sizeof message, 0, MACH_PORT_NULL, 0, MACH_PORT_NULL);
if (MACH_MSG_SUCCESS != result)
{
OOLog(kOOLogSoundMachPortError, @"Mach port send failure: %@", KernelResultNSString(result));
}
}
}
static BOOL PortWait(mach_port_t inPort, PortMessage *outMessage)
{
PortWaitMsgBody message;
mach_msg_return_t result;
memset(&message, 0, sizeof message);
message.header.msgh_bits = MACH_MSGH_BITS_LOCAL(MACH_MSG_TYPE_COPY_RECEIVE);
message.header.msgh_size = sizeof message;
message.header.msgh_local_port = inPort;
result = mach_msg_receive(&message.header);
if (MACH_MSG_SUCCESS == result)
{
if (NULL != outMessage) *outMessage = message.message;
}
else
{
if (MACH_RCV_TIMED_OUT != result) OOLog(kOOLogSoundMachPortError, @"Mach port receive failure: %@", KernelResultNSString(result));
}
return MACH_MSG_SUCCESS == result;
}

View File

@ -1,56 +0,0 @@
/*
OOCASoundDebugMonitor.h
Protocol for debugging information for sound system.
OOCASound - Core Audio sound implementation for Oolite.
Copyright (C) 2005-2013 Jens Ayton
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#import "OOSound.h"
#ifndef NDEBUG
typedef enum
{
kOOCADebugStateIdle,
kOOCADebugStatePlaying,
kOOCADebugStateOther // Cleanup phase or broken.
} OOCASoundDebugMonitorChannelState;
@protocol OOCASoundDebugMonitor
- (void) soundDebugMonitorNoteChannelMaxCount:(NSUInteger)maxChannels;
- (void) soundDebugMonitorNoteActiveChannelCount:(NSUInteger)usedChannels;
- (void) soundDebugMonitorNoteState:(OOCASoundDebugMonitorChannelState)state ofChannel:(NSUInteger)channel;
- (void) soundDebugMonitorNoteAUGraphLoad:(float)load;
@end
extern void OOSoundRegisterDebugMonitor(id <OOCASoundDebugMonitor> monitor);
#endif

View File

@ -1,62 +0,0 @@
/*
OOCASoundDecoder.h
Class responsible for converting a sound to a PCM buffer for playback. This
class is an implementation detail. Do not use it directly; use OOSound to
load sounds.
OOCASound - Core Audio sound implementation for Oolite.
Copyright (C) 2005-2013 Jens Ayton
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#import <Cocoa/Cocoa.h>
@interface OOCASoundDecoder: NSObject
- (id)initWithPath:(NSString *)inPath;
+ (OOCASoundDecoder *)codecWithPath:(NSString *)inPath;
// Full-buffer reading.
- (BOOL)readMonoCreatingBuffer:(float **)outBuffer withFrameCount:(size_t *)outSize;
- (BOOL)readStereoCreatingLeftBuffer:(float **)outLeftBuffer rightBuffer:(float **)outRightBuffer withFrameCount:(size_t *)outSize;
// Stream reading. This will always provide two channels (as non-interleaved PCM), discarding extra channels or doubling mono as necessary.
- (size_t)streamStereoToBufferL:(float *)ioBufferL bufferR:(float *)ioBufferR maxFrames:(size_t)inMax;
// Returns the size of the data -readMonoCreatingBuffer:withFrameCount: will create.
- (size_t)sizeAsBuffer;
- (BOOL)isStereo;
- (Float64)sampleRate;
// For streaming
- (BOOL)atEnd;
- (BOOL)scanToOffset:(uint64_t)inOffset;
- (void)rewindToBeginning;
- (NSString *)name;
@end

View File

@ -1,489 +0,0 @@
/*
OOCASoundDecoder.m
OOCASound - Core Audio sound implementation for Oolite.
Copyright (C) 2005-2013 Jens Ayton
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#define OV_EXCLUDE_STATIC_CALLBACKS
#import "OOCASoundDecoder.h"
#import <stdio.h>
#import <vorbis/vorbisfile.h>
#import "OOLogging.h"
enum
{
kMaxDecodeSize = 1 << 20 // 2^20 frames = 4 MB
};
static void MixDown(float *inChan1, float *inChan2, float *outMix, size_t inCount);
@interface OOCASoundVorbisCodec: OOCASoundDecoder
{
OggVorbis_File _vf;
NSString *_name;
BOOL _atEnd;
}
- (NSDictionary *)comments;
@end
@implementation OOCASoundDecoder
- (id)initWithPath:(NSString *)inPath
{
[self release];
self = nil;
if ([[inPath pathExtension] isEqual:@"ogg"])
{
self = [[OOCASoundVorbisCodec alloc] initWithPath:inPath];
}
return self;
}
+ (OOCASoundDecoder *)codecWithPath:(NSString *)inPath
{
if ([[inPath pathExtension] isEqual:@"ogg"])
{
return [[[OOCASoundVorbisCodec alloc] initWithPath:inPath] autorelease];
}
return nil;
}
- (size_t)streamStereoToBufferL:(float *)ioBufferL bufferR:(float *)ioBufferR maxFrames:(size_t)inMax
{
return 0;
}
- (BOOL)readMonoCreatingBuffer:(float **)outBuffer withFrameCount:(size_t *)outSize
{
if (NULL != outBuffer) *outBuffer = NULL;
if (NULL != outSize) *outSize = 0;
return NO;
}
- (BOOL)readStereoCreatingLeftBuffer:(float **)outLeftBuffer rightBuffer:(float **)outRightBuffer withFrameCount:(size_t *)outSize
{
if (NULL != outLeftBuffer) *outLeftBuffer = NULL;
if (NULL != outRightBuffer) *outRightBuffer = NULL;
if (NULL != outSize) *outSize = 0;
return NO;
}
- (size_t)sizeAsBuffer
{
return 0;
}
- (BOOL)isStereo
{
return NO;
}
- (double)sampleRate
{
return 0;
}
- (BOOL)atEnd
{
return YES;
}
- (void)rewindToBeginning
{
}
- (BOOL)scanToOffset:(uint64_t)inOffset
{
return NO;
}
- (NSString *)name
{
return @"";
}
@end
@implementation OOCASoundVorbisCodec
- (id)initWithPath:(NSString *)inPath
{
BOOL OK = NO;
int err;
FILE *file;
if ((self = [super init]))
{
_name = [[inPath lastPathComponent] retain];
if (nil != inPath)
{
file = fopen([inPath UTF8String], "rb");
if (NULL != file)
{
err = ov_open(file, &_vf, NULL, 0);
if (0 == err)
{
OK = YES;
}
}
}
if (!OK)
{
[self release];
self = nil;
}
}
return self;
}
- (void)dealloc
{
[_name release];
ov_clear(&_vf);
[super dealloc];
}
- (NSDictionary *)comments
{
vorbis_comment *comments;
unsigned i, count;
NSMutableDictionary *result = nil;
NSString *comment, *key, *value;
NSRange range;
comments = ov_comment(&_vf, -1);
if (NULL != comments)
{
count = comments->comments;
if (0 != count)
{
result = [NSMutableDictionary dictionaryWithCapacity:count];
for (i = 0; i != count; ++i)
{
comment = [[NSString alloc] initWithBytesNoCopy:comments->user_comments[i] length:comments->comment_lengths[i] encoding:NSUTF8StringEncoding freeWhenDone:NO];
range = [comment rangeOfString:@"="];
if (0 != range.length)
{
key = [comment substringToIndex:range.location];
value = [comment substringFromIndex:range.location + 1];
}
else
{
key = comment;
value = @"";
}
[result setObject:value forKey:key];
[comment release];
}
}
}
return result;
}
- (BOOL)readMonoCreatingBuffer:(float **)outBuffer withFrameCount:(size_t *)outSize
{
float *buffer = NULL, *dst, **src;
size_t sizeInFrames = 0;
int remaining;
unsigned chanCount;
long framesRead;
ogg_int64_t totalSizeInFrames;
BOOL OK = YES;
if (NULL != outBuffer) *outBuffer = NULL;
if (NULL != outSize) *outSize = 0;
if (NULL == outBuffer || NULL == outSize) OK = NO;
if (OK)
{
totalSizeInFrames = ov_pcm_total(&_vf, -1);
assert ((uint64_t)totalSizeInFrames < (uint64_t)SIZE_MAX); // Should have been checked by caller
sizeInFrames = (size_t)totalSizeInFrames;
}
if (OK)
{
buffer = malloc(sizeof (float) * sizeInFrames);
if (!buffer) OK = NO;
}
if (OK && sizeInFrames)
{
remaining = (int)MIN(sizeInFrames, (size_t)INT_MAX);
dst = buffer;
do
{
chanCount = ov_info(&_vf, -1)->channels;
framesRead = ov_read_float(&_vf, &src, remaining, NULL);
if (framesRead <= 0)
{
if (OV_HOLE == framesRead) continue;
//else:
break;
}
if (1 == chanCount) memcpy(dst, src[0], sizeof (float) * framesRead);
else MixDown(src[0], src[1], dst, framesRead);
remaining -= framesRead;
dst += framesRead;
} while (0 != remaining);
sizeInFrames -= remaining; // In case we stopped at an error
}
if (OK)
{
*outBuffer = buffer;
*outSize = sizeInFrames;
}
else
{
if (buffer) free(buffer);
}
return OK;
}
- (BOOL)readStereoCreatingLeftBuffer:(float **)outLeftBuffer rightBuffer:(float **)outRightBuffer withFrameCount:(size_t *)outSize
{
float *bufferL = NULL, *bufferR = NULL, *dstL, *dstR, **src;
size_t sizeInFrames = 0;
int remaining;
unsigned chanCount;
long framesRead;
ogg_int64_t totalSizeInFrames;
BOOL OK = YES;
if (NULL != outLeftBuffer) *outLeftBuffer = NULL;
if (NULL != outRightBuffer) *outRightBuffer = NULL;
if (NULL != outSize) *outSize = 0;
if (NULL == outLeftBuffer || NULL == outRightBuffer || NULL == outSize) OK = NO;
if (OK)
{
totalSizeInFrames = ov_pcm_total(&_vf, -1);
assert ((uint64_t)totalSizeInFrames < (uint64_t)SIZE_MAX); // Should have been checked by caller
sizeInFrames = (size_t)totalSizeInFrames;
}
if (OK)
{
bufferL = malloc(sizeof (float) * sizeInFrames);
if (!bufferL) OK = NO;
}
if (OK)
{
bufferR = malloc(sizeof (float) * sizeInFrames);
if (!bufferR) OK = NO;
}
if (OK && sizeInFrames)
{
remaining = (int)MIN(sizeInFrames, (size_t)INT_MAX);
dstL = bufferL;
dstR = bufferR;
do
{
chanCount = ov_info(&_vf, -1)->channels;
framesRead = ov_read_float(&_vf, &src, remaining, NULL);
if (framesRead <= 0)
{
if (OV_HOLE == framesRead) continue;
//else:
break;
}
unsigned rightChan = (chanCount == 1) ? 0 : 1;
memcpy(dstL, src[0], sizeof (float) * framesRead);
memcpy(dstR, src[rightChan], sizeof (float) * framesRead);
remaining -= framesRead;
dstL += framesRead;
dstR += framesRead;
} while (0 != remaining);
sizeInFrames -= remaining; // In case we stopped at an error
}
if (OK)
{
*outLeftBuffer = bufferL;
*outRightBuffer = bufferR;
*outSize = sizeInFrames;
}
else
{
if (bufferL) free(bufferL);
if (bufferR) free(bufferR);
}
return OK;
}
- (size_t)streamStereoToBufferL:(float *)ioBufferL bufferR:(float *)ioBufferR maxFrames:(size_t)inMax
{
float **src;
unsigned chanCount;
long framesRead;
size_t size;
int remaining;
// Note: for our purposes, a frame is a set of one sample for each channel.
if (NULL == ioBufferL || NULL == ioBufferR || 0 == inMax) return 0;
if (_atEnd) return inMax;
remaining = (int)MIN(inMax, (size_t)INT_MAX);
do
{
chanCount = ov_info(&_vf, -1)->channels;
framesRead = ov_read_float(&_vf, &src, remaining, NULL);
if (framesRead <= 0)
{
if (OV_HOLE == framesRead) continue;
//else:
_atEnd = YES;
break;
}
size = sizeof (float) * framesRead;
unsigned rightChan = (chanCount == 1) ? 0 : 1;
memcpy(ioBufferL, src[0], size);
memcpy(ioBufferR, src[rightChan], size);
remaining -= framesRead;
ioBufferL += framesRead;
ioBufferR += framesRead;
} while (0 != remaining);
return inMax - remaining;
}
- (size_t)sizeAsBuffer
{
ogg_int64_t size;
size = ov_pcm_total(&_vf, -1);
size *= sizeof(float) * ([self isStereo] ? 2 : 1);
if ((uint64_t)SIZE_MAX < (uint64_t)size) size = (ogg_int64_t)SIZE_MAX;
return (size_t)size;
}
- (BOOL)isStereo
{
return 1 < ov_info(&_vf, -1)->channels;
}
- (NSString *)description
{
return [NSString stringWithFormat:@"<%@ %p>{\"%@\", comments=%@}", [self className], self, _name, [self comments]];
}
- (Float64)sampleRate
{
return ov_info(&_vf, -1)->rate;
}
- (BOOL)atEnd
{
return _atEnd;
}
- (void)rewindToBeginning
{
if (!ov_pcm_seek(&_vf, 0)) _atEnd = NO;
}
- (BOOL)scanToOffset:(uint64_t)inOffset
{
if (!ov_pcm_seek(&_vf, inOffset))
{
_atEnd = NO;
return YES;
}
else return NO;
}
- (NSString *)name
{
return [[_name retain] autorelease];
}
@end
// TODO: optimise, vectorise
static void MixDown(float *inChan1, float *inChan2, float *outMix, size_t inCount)
{
while (inCount--)
{
*outMix++ = (*inChan1++ + *inChan2++) * 0.5f;
}
}

View File

@ -1,89 +0,0 @@
/*
OOCASoundInternal.h
Declarations used within OOCASound. This file should not be used by client
code.
OOCASound - Core Audio sound implementation for Oolite.
Copyright (C) 2005-2013 Jens Ayton
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#import "OOSoundInternal.h"
#import "OOCASoundChannel.h"
#import "OOCABufferedSound.h"
#import "OOCAStreamingSound.h"
#import <CoreAudio/CoreAudio.h>
#import <AudioToolbox/AudioToolbox.h>
#import "OOErrorDescription.h"
#import "OOLogging.h"
#import "OOMaths.h"
@interface OOSound (Internal)
- (OSStatus)renderWithFlags:(AudioUnitRenderActionFlags *)ioFlags frames:(UInt32)inNumFrames context:(OOCASoundRenderContext *)ioContext data:(AudioBufferList *)ioData;
// Called by -play and -stop only if in appropriate state
- (BOOL)prepareToPlayWithContext:(OOCASoundRenderContext *)outContext looped:(BOOL)inLoop;
- (void)finishStoppingWithContext:(OOCASoundRenderContext)inContext;
- (BOOL)getAudioStreamBasicDescription:(AudioStreamBasicDescription *)outFormat;
- (void)incrementPlayingCount;
- (void)decrementPlayingCount;
- (BOOL) isPlaying;
@end
@interface OOSoundMixer (Internal)
- (BOOL)connectChannel:(OOSoundChannel *)inChannel;
- (OSStatus)disconnectChannel:(OOSoundChannel *)inChannel;
@end
extern BOOL gOOSoundSetUp, gOOSoundBroken;
extern NSString * const kOOLogDeprecatedMethodOOCASound;
extern NSString * const kOOLogSoundInitError;
#define kOOLogUnconvertedNSLog @"unclassified.OOCASound"
#ifndef NDEBUG
void OOCASoundVerifyBuffers(AudioBufferList *buffers, NSUInteger numFrames, OOSound *sound);
#else
#define OOCASoundVerifyBuffers(buffers, numFrames, sound) do {} while (0)
#endif
/* The Vorbis floating-point decoder gives us out-of-range values for certain
built-in sounds. To compensate, we reduce overall volume slightly to avoid
clipping. (The worst observed value is -1.341681f in bigbang.ogg.)
*/
#define kOOAudioSlop 1.341682f

View File

@ -1,74 +0,0 @@
/*
OOCASoundMixer.h
Class responsible for managing and mixing sound channels. This class is an
implementation detail. Do not use it directly; use an OOSoundSource to play an
OOSound.
OOCASound - Core Audio sound implementation for Oolite.
Copyright (C) 2005-2013 Jens Ayton
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#import <Foundation/Foundation.h>
#import <mach/port.h>
#import <AudioToolbox/AudioToolbox.h>
@class OOMusic, OOSoundChannel, OOSoundSource;
enum
{
kMixerGeneralChannels = 32
};
@interface OOSoundMixer: NSObject
{
@private
OOSoundChannel *_channels[kMixerGeneralChannels];
OOSoundChannel *_freeList;
NSLock *_listLock;
AUGraph _graph;
AUNode _mixerNode;
AUNode _outputNode;
AudioUnit _mixerUnit;
uint32_t _activeChannels;
#ifndef NDEBUG
uint32_t _playMask;
#endif
}
// Singleton accessor
+ (OOSoundMixer *) sharedMixer;
- (void) update;
- (void) setMasterVolume:(float)inVolume;
- (OOSoundChannel *) popChannel;
- (void) pushChannel:(OOSoundChannel *) OO_NS_CONSUMED inChannel;
@end

View File

@ -1,382 +0,0 @@
/*
OOCASoundMixer.m
OOCASound - Core Audio sound implementation for Oolite.
Copyright (C) 2005-2013 Jens Ayton
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#import "OOCASoundInternal.h"
#import "OOCASoundChannel.h"
#import "NSThreadOOExtensions.h"
#import "OOCASoundDebugMonitor.h"
#import "OOErrorDescription.h"
static NSString * const kOOLogSoundInspetorNotLoaded = @"sound.mixer.inspector.loadFailed";
static NSString * const kOOLogSoundMixerOutOfChannels = @"sound.mixer.outOfChannels";
static NSString * const kOOLogSoundMixerReplacingBrokenChannel = @"sound.mixer.replacingBrokenChannel";
static NSString * const kOOLogSoundMixerFailedToConnectChannel = @"sound.mixer.failedToConnectChannel";
@interface OOSoundMixer (Private)
- (void)pushChannel:(OOSoundChannel *)inChannel;
- (OOSoundChannel *)popChannel;
@end
static OOSoundMixer *sSingleton = nil;
#ifndef NDEBUG
static id <OOCASoundDebugMonitor> gOOCASoundDebugMonitor = nil;
void OOSoundRegisterDebugMonitor(id <OOCASoundDebugMonitor> monitor)
{
if (monitor != gOOCASoundDebugMonitor)
{
gOOCASoundDebugMonitor = monitor;
[monitor soundDebugMonitorNoteChannelMaxCount:kMixerGeneralChannels];
}
}
#endif
@implementation OOSoundMixer
+ (OOSoundMixer *) sharedMixer
{
if (nil == sSingleton)
{
sSingleton = [[self alloc] init];
}
return sSingleton;
}
- (id)init
{
OSStatus err = noErr;
BOOL OK;
uint32_t idx = 0, count = kMixerGeneralChannels;
OOSoundChannel *temp;
AudioComponentDescription desc;
if (!gOOSoundSetUp) [OOSound setUp];
self = [super init];
if (nil != self)
{
_listLock = [[NSLock alloc] init];
[_listLock setName:@"OOSoundMixer list lock"];
OK = nil != _listLock;
if (OK)
{
// Create audio graph
err = NewAUGraph(&_graph);
// Add output node
desc.componentType = kAudioUnitType_Output;
desc.componentSubType = kAudioUnitSubType_DefaultOutput;
desc.componentManufacturer = kAudioUnitManufacturer_Apple;
desc.componentFlags = 0;
desc.componentFlagsMask = 0;
if (!err) err = AUGraphAddNode(_graph, &desc, &_outputNode);
// Add mixer node
desc.componentType = kAudioUnitType_Mixer;
desc.componentSubType = kAudioUnitSubType_StereoMixer;
desc.componentManufacturer = kAudioUnitManufacturer_Apple;
desc.componentFlags = 0;
desc.componentFlagsMask = 0;
if (!err) err = AUGraphAddNode(_graph, &desc, &_mixerNode);
// Connect mixer to output
if (!err) err = AUGraphConnectNodeInput(_graph, _mixerNode, 0, _outputNode, 0);
// Open the graph (turn it into concrete AUs) and extract mixer AU
if (!err) err = AUGraphOpen(_graph);
if (!err) err = AUGraphNodeInfo(_graph, _mixerNode, NULL, &_mixerUnit);
if (!err) [self setMasterVolume:1.0];
if (err) OK = NO;
}
if (OK)
{
// Allocate channels
do
{
temp = [[OOSoundChannel alloc] initWithID:count auGraph:_graph];
if (nil != temp)
{
_channels[idx++] = temp;
[temp setNext:_freeList];
_freeList = temp;
}
} while (--count);
if (noErr != AUGraphInitialize(_graph)) OK = NO;
}
if (OK)
{
// Force CA to do any lazy setup.
AUGraphStart(_graph);
AUGraphStop(_graph);
}
if (!OK)
{
static bool onlyOnce;
if (!onlyOnce)
{
onlyOnce = YES;
OOLog(@"sound.mixer.init.failed", @"Failed to initialize sound mixer - error %@", AudioErrorNSString(err));
}
[super release];
self = nil;
}
}
sSingleton = self;
return sSingleton;
}
- (void)dealloc
{
uint32_t idx;
if (NULL != _graph)
{
AUGraphStop(_graph);
AUGraphUninitialize(_graph);
AUGraphClose(_graph);
DisposeAUGraph(_graph);
}
for (idx = 0; idx != kMixerGeneralChannels; ++idx)
{
[_channels[idx] release];
}
[super dealloc];
}
- (void)channel:(OOSoundChannel *)inChannel didFinishPlayingSound:(OOSound *)inSound
{
uint32_t ID;
[inSound decrementPlayingCount];
if (![inChannel isOK])
{
OOLog(kOOLogSoundMixerReplacingBrokenChannel, @"Sound mixer: replacing broken channel %@.", inChannel);
ID = [inChannel ID];
[inChannel release];
inChannel = [[OOSoundChannel alloc] initWithID:ID auGraph:_graph];
}
[self pushChannel:inChannel];
}
#ifndef NDEBUG
#define GET_PLAYMASK(n) ((_playMask & (1 << ((n) - 1))) != 0)
#define SET_PLAYMASK(n) do { _playMask |= (1 << ((n) - 1)); } while (0)
#define CLEAR_PLAYMASK(n) do { _playMask &= ~(1 << ((n) - 1)); } while (0)
#endif
- (void)update
{
#ifndef NDEBUG
if (gOOCASoundDebugMonitor != nil)
{
[gOOCASoundDebugMonitor soundDebugMonitorNoteActiveChannelCount:_activeChannels];
unsigned i;
for (i = 0; i != kMixerGeneralChannels; ++i)
{
uint32_t ID = [_channels[i] ID];
BOOL playMaskValue = GET_PLAYMASK(ID);
OOCASoundDebugMonitorChannelState state = [_channels[i] soundInspectorState];
// Because of asynchrony, channel may be in stopped state but not reenqueued.
if (playMaskValue && state == kOOCADebugStateIdle) state = kOOCADebugStateOther;
[gOOCASoundDebugMonitor soundDebugMonitorNoteState:state ofChannel:ID - 1];
}
Float32 load;
if (!AUGraphGetCPULoad(_graph, &load))
{
[gOOCASoundDebugMonitor soundDebugMonitorNoteAUGraphLoad:load];
}
}
#endif
}
- (void)setMasterVolume:(float)inVolume
{
AudioUnitSetParameter(_mixerUnit, kStereoMixerParam_Volume, kAudioUnitScope_Output, 0, inVolume / kOOAudioSlop, 0);
}
- (OOSoundChannel *)popChannel
{
OOSoundChannel *result;
[_listLock lock];
result = _freeList;
_freeList = [result next];
if (nil != result)
{
if (0 == _activeChannels++)
{
AUGraphStart(_graph);
}
#ifndef NDEBUG
SET_PLAYMASK([result ID]);
#endif
}
[_listLock unlock];
return result;
}
- (void)pushChannel:(OOSoundChannel *) OO_NS_CONSUMED inChannel
{
assert(nil != inChannel);
[_listLock lock];
[inChannel setNext:_freeList];
_freeList = inChannel;
if (0 == --_activeChannels)
{
AUGraphStop(_graph);
}
#ifndef NDEBUG
CLEAR_PLAYMASK([inChannel ID]);
#endif
[_listLock unlock];
}
- (BOOL)connectChannel:(OOSoundChannel *)inChannel
{
AUNode node;
OSStatus err;
assert(nil != inChannel);
node = [inChannel auSubGraphNode];
err = AUGraphConnectNodeInput(_graph, node, 0, _mixerNode, [inChannel ID]);
if (!err) err = AUGraphUpdate(_graph, NULL);
if (err)
{
OOLog(kOOLogSoundMixerFailedToConnectChannel, @"Sound mixer: failed to connect channel %@, error = %@.", inChannel, AudioErrorNSString(err));
#if OO_DEBUG
CAShow(_graph);
#endif
}
return !err;
}
- (OSStatus)disconnectChannel:(OOSoundChannel *)inChannel
{
OSStatus err;
assert(nil != inChannel);
err = AUGraphDisconnectNodeInput(_graph, _mixerNode, [inChannel ID]);
if (noErr == err) AUGraphUpdate(_graph, NULL);
return err;
}
@end
@implementation OOSoundMixer (Singleton)
/* Canonical singleton boilerplate.
See Cocoa Fundamentals Guide: Creating a Singleton Instance.
See also +sharedMixer above.
NOTE: assumes single-threaded access.
*/
+ (id)allocWithZone:(NSZone *)inZone
{
if (sSingleton == nil)
{
sSingleton = [super allocWithZone:inZone];
return sSingleton;
}
return nil;
}
- (id)copyWithZone:(NSZone *)inZone
{
return self;
}
- (id)retain
{
return self;
}
- (NSUInteger)retainCount
{
return UINT_MAX;
}
- (void)release
{}
- (id)autorelease
{
return self;
}
@end

View File

@ -1,44 +0,0 @@
/*
OOCASoundReferencePoint.h
A reference point for positional audio. The position of an OOSoundSource is
specified relative to an OOSoundReferencePoint. Since positional audio is
currently unimplemented, this class does nothing.
OOCASound - Core Audio sound implementation for Oolite.
Copyright (C) 2005-2013 Jens Ayton
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#import <Foundation/Foundation.h>
#import "OOMaths.h"
@interface OOSoundReferencePoint: NSObject
// Positional audio attributes are ignored in this implementation
- (void)setPosition:(Vector)inPosition;
- (void)setVelocity:(Vector)inVelocity;
- (void)setOrientation:(Vector)inOrientation;
@end

View File

@ -1,51 +0,0 @@
/*
OOCASoundReferencePoint.m
OOCASound - Core Audio sound implementation for Oolite.
Copyright (C) 2005-2013 Jens Ayton
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#import "OOCASoundReferencePoint.h"
@implementation OOSoundReferencePoint
- (void)setPosition:(Vector)inPosition
{
}
- (void)setVelocity:(Vector)inVelocity
{
}
- (void)setOrientation:(Vector)inOrientation
{
}
@end

View File

@ -1,48 +0,0 @@
/*
OOCAStreamingSound.h
Subclass of OOSound which streams audio from disk.
This class is an implementation detail. Do not use it directly; use OOSound.
OOCASound - Core Audio sound implementation for Oolite.
Copyright (C) 2005-2013 Jens Ayton
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#import <Cocoa/Cocoa.h>
#import "OOSound.h"
@class OOCASoundDecoder;
@class VirtualRingBuffer;
@interface OOCAStreamingSound: OOSound
{
@private
OOCASoundDecoder *_decoder;
}
- (id) initWithDecoder:(OOCASoundDecoder *)inDecoder;
@end

View File

@ -1,382 +0,0 @@
/*
OOCAStreamingSound.m
This class is an implementation detail. Do not use it directly; use OOSound.
OOCASound - Core Audio sound implementation for Oolite.
Copyright (C) 2005-2013 Jens Ayton
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#import "OOCASoundInternal.h"
#import "OOCASoundDecoder.h"
#import "VirtualRingBuffer.h"
#import "NSThreadOOExtensions.h"
static NSString * const kOOLogSoundStreamingRefill = @"sound.streaming.refill";
static NSString * const kOOLogSoundStreamingLoop = @"sound.streaming.loop";
static NSString * const kOOLogSoundStreamingUnderflow = @"sound.streaming.underflow";
static BOOL sFeederThreadActive = NO;
static MPQueueID sFeederQueue = kInvalidID;
// For IMP caching of VirtualRingBuffer methods
typedef UInt32 (*VRB_lengthAvailableToReadReturningPointerIMP)(id inSelf, SEL inSel, void ** outReturnedReadPointer);
typedef void (*VRB_didReadLengthIMP)(id inSelf, SEL inSel, UInt32 inLength);
#define kSEL_VRB_lengthAvailableToReadReturningPointer @selector(lengthAvailableToReadReturningPointer:)
#define kSEL_VRB_didReadLength @selector(didReadLength:)
static VRB_lengthAvailableToReadReturningPointerIMP VRB_lengthAvailableToReadReturningPointer = NULL;
static VRB_didReadLengthIMP VRB_didReadLength = NULL;
typedef struct
{
uint64_t readOffset;
VirtualRingBuffer *bufferL,
*bufferR;
int32_t pendingCount;
BOOL atEnd,
loop,
empty,
stopped;
} *OOCAStreamingSoundRenderContext;
@interface OOCAStreamingSound (Internal)
+ (void)feederThread:ignored;
- (BOOL)setUpAudioUnit;
- (void)fillBuffersWithContext:(OOCAStreamingSoundRenderContext)inContext;
- (void)releaseContext:(OOCAStreamingSoundRenderContext)inContext;
@end
enum
{
// Port messages
kMsgFillBuffers = 1UL
};
enum
{
kStreamBufferCount = 400000, // Number of frames in buffer
kStreamBufferRefillThreshold = kStreamBufferCount / 3, // When to request refill
kMinRebufferFrames = kStreamBufferCount / 10, // When to ignore fill request (may get multiple requests before filler thread is scheduled)
kStreamBufferSize = kStreamBufferCount * sizeof (float)
};
@implementation OOCAStreamingSound
- (id)initWithDecoder:(OOCASoundDecoder *)inDecoder
{
BOOL OK = YES;
assert(gOOSoundSetUp);
if (gOOSoundBroken || nil == inDecoder) OK = NO;
if (OK && VRB_lengthAvailableToReadReturningPointer == NULL)
{
VRB_lengthAvailableToReadReturningPointer = (VRB_lengthAvailableToReadReturningPointerIMP)[VirtualRingBuffer instanceMethodForSelector:@selector(lengthAvailableToReadReturningPointer:)];
VRB_didReadLength = (VRB_didReadLengthIMP)[VirtualRingBuffer instanceMethodForSelector:@selector(didReadLength:)];
if (VRB_lengthAvailableToReadReturningPointer == NULL || VRB_didReadLength == NULL) OK = NO;
}
if (OK)
{
self = [super init];
if (nil == self) OK = NO;
}
if (OK)
{
_decoder = [inDecoder retain];
}
if (!OK)
{
[self release];
self = nil;
}
return self;
}
- (void)dealloc
{
assert(![self isPlaying]);
[_decoder release];
[super dealloc];
}
- (BOOL)prepareToPlayWithContext:(OOCASoundRenderContext *)outContext looped:(BOOL)inLoop
{
BOOL OK = YES;
OOCAStreamingSoundRenderContext context = NULL;
assert(outContext != NULL);
if (OK)
{
context = calloc(1, sizeof *context);
if (context != NULL)
{
*outContext = (OOCASoundRenderContext)context;
context->loop = inLoop;
context->empty = YES;
}
else
{
OK = NO;
}
}
if (OK)
{
context->bufferL = [[VirtualRingBuffer alloc] initWithLength:kStreamBufferSize];
context->bufferR = [[VirtualRingBuffer alloc] initWithLength:kStreamBufferSize];
if (!context->bufferL || !context->bufferR)
{
OK = NO;
}
}
if (OK && sFeederQueue == kInvalidID)
{
OK = (noErr == MPCreateQueue(&sFeederQueue)) && (sFeederQueue != kInvalidID);
}
if (OK)
{
if (!sFeederThreadActive) [NSThread detachNewThreadSelector:@selector(feederThread:) toTarget:[OOCAStreamingSound class] withObject:nil];
[self retain]; // Will be released by fillBuffers... when stopped is true and pendingCount is 0.
++context->pendingCount;
[self fillBuffersWithContext:context];
}
return OK;
}
- (void)finishStoppingWithContext:(OOCASoundRenderContext)inContext
{
OOCAStreamingSoundRenderContext context;
context = (OOCAStreamingSoundRenderContext) inContext;
[gOOCASoundSyncLock lock];
context->stopped = YES;
if (0 == context->pendingCount)
{
OOLog(@"sound.streaming.releaseContext.immediate", @"Streaming sound %@ stopped with 0 pendingCount, releasing context.", self);
[self releaseContext:context];
}
else
{
OOLog(@"sound.streaming.releaseContext.deferring", @"Streaming sound %@ stopped with %i pendingCount, deferring release.", self, context->pendingCount);
}
[gOOCASoundSyncLock unlock];
}
+ (void)feederThread:(id)ignored
{
uintptr_t msgID;
void *param1, *param2;
OOCAStreamingSound *sound;
OOCAStreamingSoundRenderContext context = 0;
NSAutoreleasePool *pool = nil;
assert(sFeederQueue != kInvalidID);
[NSThread ooSetCurrentThreadName:@"OOCAStreamingSound feeder thread"];
sFeederThreadActive = YES;
for (;;)
{
if (noErr != MPWaitOnQueue(sFeederQueue, (void **)&msgID, &param1, &param2, kDurationForever)) continue;
pool = [[NSAutoreleasePool alloc] init];
switch (msgID)
{
case kMsgFillBuffers:
sound = param1;
context = param2;
[sound fillBuffersWithContext:context];
}
[pool release];
}
}
- (void)fillBuffersWithContext:(OOCAStreamingSoundRenderContext)inContext
{
size_t spaceL, spaceR;
void *ptrL, *ptrR;
size_t frames;
[gOOCASoundSyncLock lock];
spaceL = [inContext->bufferL lengthAvailableToWriteReturningPointer:&ptrL];
spaceR = [inContext->bufferR lengthAvailableToWriteReturningPointer:&ptrR];
// These ought to be the same
frames = MIN(spaceL, spaceR) / sizeof (float);
if (kMinRebufferFrames < frames)
{
if (![_decoder scanToOffset:inContext->readOffset])
{
inContext->atEnd = YES;
}
else
{
if (kStreamBufferCount < frames)
{
if (!inContext->empty) OOLog(kOOLogSoundStreamingUnderflow, @"Buffer underflow for sound %@.", self);
inContext->empty = NO;
}
OOLog(kOOLogSoundStreamingRefill, @"Buffering %zu frames for sound %@.", frames, self);
frames = [_decoder streamStereoToBufferL:(float *)ptrL bufferR:(float *)ptrR maxFrames:frames];
inContext->readOffset += frames;
[inContext->bufferL didWriteLength:frames * sizeof (float)];
[inContext->bufferR didWriteLength:frames * sizeof (float)];
if ([_decoder atEnd])
{
if (inContext->loop)
{
OOLog(kOOLogSoundStreamingLoop, @"Resetting streaming sound %@ for looping.", self);
inContext->readOffset = 0;
}
else inContext->atEnd = YES;
}
}
}
OSAtomicAdd32(-1, &inContext->pendingCount);
if (inContext->pendingCount == 0 && inContext->stopped)
{
OOLog(@"sound.streaming.releaseContext.deferred", @"Stopped streaming sound %@ reached 0 pendingCount, releasing context.", self);
[self releaseContext:inContext];
}
[gOOCASoundSyncLock unlock];
}
- (void)releaseContext:(OOCAStreamingSoundRenderContext)inContext
{
[inContext->bufferL release];
[inContext->bufferR release];
free(inContext);
[self autorelease];
}
- (BOOL)getAudioStreamBasicDescription:(AudioStreamBasicDescription *)outFormat
{
assert(NULL != outFormat);
outFormat->mSampleRate = [_decoder sampleRate];
outFormat->mFormatID = kAudioFormatLinearPCM;
outFormat->mFormatFlags = kAudioFormatFlagsNativeFloatPacked | kLinearPCMFormatFlagIsNonInterleaved;
outFormat->mBytesPerPacket = sizeof (float);
outFormat->mFramesPerPacket = 1;
outFormat->mBytesPerFrame = sizeof (float);
outFormat->mChannelsPerFrame = 2;
outFormat->mBitsPerChannel = sizeof (float) * 8;
outFormat->mReserved = 0;
return YES;
}
- (OSStatus)renderWithFlags:(AudioUnitRenderActionFlags *)ioFlags frames:(UInt32)inNumFrames context:(OOCASoundRenderContext *)ioContext data:(AudioBufferList *)ioData
{
uint32_t available, availL, availR, remaining, underflow;
uint32_t numBytes;
void *ptrL, *ptrR;
OOCAStreamingSoundRenderContext context;
context = (OOCAStreamingSoundRenderContext)*ioContext;
assert(2 == ioData->mNumberBuffers);
availL = VRB_lengthAvailableToReadReturningPointer(context->bufferL, kSEL_VRB_lengthAvailableToReadReturningPointer, &ptrL);
availR = VRB_lengthAvailableToReadReturningPointer(context->bufferR, kSEL_VRB_lengthAvailableToReadReturningPointer, &ptrR);
numBytes = inNumFrames * sizeof (float);
available = MIN(availL, availR);
remaining = available;
if (numBytes < available) available = numBytes;
memcpy(ioData->mBuffers[0].mData, ptrL, available);
memcpy(ioData->mBuffers[1].mData, ptrR, available);
VRB_didReadLength(context->bufferL, kSEL_VRB_didReadLength, available);
VRB_didReadLength(context->bufferR, kSEL_VRB_didReadLength, available);
if (available < numBytes)
{
// Buffer underflow! Fill with silence.
underflow = numBytes - available;
if (0 == available) *ioFlags |= kAudioUnitRenderAction_OutputIsSilence;
memset(ioData->mBuffers[0].mData + available, 0, underflow);
memset(ioData->mBuffers[1].mData + available, 0, underflow);
}
OOCASoundVerifyBuffers(ioData, inNumFrames, self);
remaining -= available;
if (!context->atEnd && remaining < kStreamBufferRefillThreshold * sizeof (float) && sFeederQueue != kInvalidID)
{
OSAtomicAdd32(1, &context->pendingCount);
MPNotifyQueue(sFeederQueue, (void *)kMsgFillBuffers, self, context);
}
return (context->atEnd && remaining == 0) ? endOfDataReached : noErr;
}
- (NSString *)name
{
return [_decoder name];
}
@end

View File

@ -1,23 +0,0 @@
/*
OOErrorDescription.h
A set of functions for mapping various types of Mac OS error codes to names,
primarily for debugging purposes.
For OOCASound - Core Audio sound implementation for Oolite.
By Jens Ayton, 2005
This file is hereby placed in the public domain.
*/
#import <Foundation/Foundation.h>
// Provide descriptions of various Mac-specific error codes
NSString *OSStatusErrorNSString(OSStatus inCode);
NSString *AudioErrorNSString(ComponentResult inCode);
NSString *KernelResultNSString(kern_return_t inCode);
NSString *FourCharCodeToNSString(FourCharCode inCode);
NSString *AudioErrorShortNSString(OSStatus inCode);

View File

@ -1,259 +0,0 @@
/*
OOErrorDescription.m
A set of functions for mapping various types of Mac OS error codes to names,
primarily for debugging purposes.
For OOCASound - Core Audio sound implementation for Oolite.
By Jens Ayton, 2005
This file is hereby placed in the public domain.
*/
#import "OOErrorDescription.h"
#import <CoreAudio/CoreAudio.h>
#import <AudioToolbox/AudioToolbox.h>
#import <Carbon/Carbon.h>
#ifndef NDEBUG
#define CASE(foo) case foo: return @#foo
#endif
#ifndef NDEBUG
static NSString *GetGenericOSStatusString(OSStatus inCode);
#endif
NSString *OSStatusErrorNSString(OSStatus inCode)
{
NSString *result = nil;
#ifndef NDEBUG
result = GetGenericOSStatusString(inCode);
#else
if (noErr == inCode) result = @"no error";
#endif
if (nil == result) result = [NSString stringWithFormat:@"%i", (int)inCode];
return result;
}
NSString *AudioErrorNSString(ComponentResult inCode)
{
#ifndef NDEBUG
switch (inCode)
{
CASE(kAudioConverterErr_FormatNotSupported);
CASE(kAudioConverterErr_OperationNotSupported);
CASE(kAudioConverterErr_PropertyNotSupported);
CASE(kAudioConverterErr_InvalidInputSize);
CASE(kAudioConverterErr_InvalidOutputSize);
CASE(kAudioConverterErr_UnspecifiedError);
CASE(kAudioConverterErr_BadPropertySizeError);
CASE(kAudioConverterErr_RequiresPacketDescriptionsError);
CASE(kAudioConverterErr_InputSampleRateOutOfRange);
CASE(kAudioConverterErr_OutputSampleRateOutOfRange);
CASE(kAudioCodecUnknownPropertyError);
CASE(kAudioCodecIllegalOperationError);
CASE(kAudioCodecUnsupportedFormatError);
CASE(kAudioCodecStateError);
CASE(kAudioCodecNotEnoughBufferSpaceError);
CASE(kAudioUnitErr_InvalidProperty);
CASE(kAudioUnitErr_InvalidParameter);
CASE(kAudioUnitErr_InvalidElement);
CASE(kAudioUnitErr_NoConnection);
CASE(kAudioUnitErr_FailedInitialization);
CASE(kAudioUnitErr_TooManyFramesToProcess);
CASE(kAudioUnitErr_IllegalInstrument);
CASE(kAudioUnitErr_InstrumentTypeNotFound);
CASE(kAudioUnitErr_InvalidFile);
CASE(kAudioUnitErr_UnknownFileType);
CASE(kAudioUnitErr_FileNotSpecified);
CASE(kAudioUnitErr_FormatNotSupported);
CASE(kAudioUnitErr_Uninitialized);
CASE(kAudioUnitErr_InvalidScope);
CASE(kAudioUnitErr_PropertyNotWritable);
CASE(kAudioUnitErr_CannotDoInCurrentContext);
CASE(kAudioUnitErr_InvalidPropertyValue);
CASE(kAudioUnitErr_PropertyNotInUse);
CASE(kAudioUnitErr_Initialized);
CASE(kAudioUnitErr_InvalidOfflineRender);
CASE(kAudioUnitErr_Unauthorized);
CASE(kAUGraphErr_NodeNotFound);
CASE(kAUGraphErr_InvalidConnection);
CASE(kAUGraphErr_OutputNodeErr);
CASE(kAUGraphErr_InvalidAudioUnit);
default:
{
NSString *result = GetGenericOSStatusString(inCode);
if (nil != result) return result;
}
}
#else
if (noErr == inCode) return @"no error";
#endif
return AudioErrorShortNSString(inCode);
}
NSString *AudioErrorShortNSString(OSStatus inCode)
{
#define PRINTABLE(x) (!((x) < ' ') && !((x) == 0x7F))
if (!(inCode & 0x80000000) &&
PRINTABLE(inCode >> 24) &&
PRINTABLE((inCode >> 16) & 0xFF) &&
PRINTABLE((inCode >> 8) & 0xFF) &&
PRINTABLE(inCode & 0xFF))
{
// Assume a four-char code
return [NSString stringWithFormat:@"\'%@\'", FourCharCodeToNSString(inCode)];
}
else
{
return [NSString stringWithFormat:@"%i", (int)inCode];
}
}
NSString *KernelResultNSString(kern_return_t inCode)
{
#ifndef NDEBUG
switch (inCode)
{
CASE(KERN_INVALID_ADDRESS);
CASE(KERN_PROTECTION_FAILURE);
CASE(KERN_NO_SPACE);
CASE(KERN_INVALID_ARGUMENT);
CASE(KERN_FAILURE);
CASE(KERN_RESOURCE_SHORTAGE);
CASE(KERN_NOT_RECEIVER);
CASE(KERN_NO_ACCESS);
CASE(KERN_MEMORY_FAILURE);
CASE(KERN_MEMORY_ERROR);
CASE(KERN_ALREADY_IN_SET);
CASE(KERN_NOT_IN_SET);
CASE(KERN_NAME_EXISTS);
CASE(KERN_ABORTED);
CASE(KERN_INVALID_NAME);
CASE(KERN_INVALID_TASK);
CASE(KERN_INVALID_RIGHT);
CASE(KERN_INVALID_VALUE);
CASE(KERN_UREFS_OVERFLOW);
CASE(KERN_INVALID_CAPABILITY);
CASE(KERN_RIGHT_EXISTS);
CASE(KERN_INVALID_HOST);
CASE(KERN_MEMORY_PRESENT);
CASE(KERN_MEMORY_DATA_MOVED);
CASE(KERN_MEMORY_RESTART_COPY);
CASE(KERN_INVALID_PROCESSOR_SET);
CASE(KERN_POLICY_LIMIT);
CASE(KERN_INVALID_POLICY);
CASE(KERN_INVALID_OBJECT);
CASE(KERN_ALREADY_WAITING);
CASE(KERN_DEFAULT_SET);
CASE(KERN_EXCEPTION_PROTECTED);
CASE(KERN_INVALID_LEDGER);
CASE(KERN_INVALID_MEMORY_CONTROL);
CASE(KERN_INVALID_SECURITY);
CASE(KERN_NOT_DEPRESSED);
CASE(KERN_TERMINATED);
CASE(KERN_LOCK_SET_DESTROYED);
CASE(KERN_LOCK_UNSTABLE);
CASE(KERN_LOCK_OWNED);
CASE(KERN_LOCK_OWNED_SELF);
CASE(KERN_SEMAPHORE_DESTROYED);
CASE(KERN_RPC_SERVER_TERMINATED);
CASE(KERN_RPC_TERMINATE_ORPHAN);
CASE(KERN_RPC_CONTINUE_ORPHAN);
CASE(KERN_NOT_SUPPORTED);
CASE(KERN_NODE_DOWN);
CASE(KERN_NOT_WAITING);
CASE(KERN_OPERATION_TIMED_OUT);
CASE(MACH_MSG_IPC_SPACE);
CASE(MACH_MSG_VM_SPACE);
CASE(MACH_MSG_IPC_KERNEL);
CASE(MACH_MSG_VM_KERNEL);
CASE(MACH_SEND_IN_PROGRESS);
CASE(MACH_SEND_INVALID_DATA);
CASE(MACH_SEND_INVALID_DEST);
CASE(MACH_SEND_TIMED_OUT);
CASE(MACH_SEND_INTERRUPTED);
CASE(MACH_SEND_MSG_TOO_SMALL);
CASE(MACH_SEND_INVALID_REPLY);
CASE(MACH_SEND_INVALID_RIGHT);
CASE(MACH_SEND_INVALID_NOTIFY);
CASE(MACH_SEND_INVALID_MEMORY);
CASE(MACH_SEND_NO_BUFFER);
CASE(MACH_SEND_TOO_LARGE);
CASE(MACH_SEND_INVALID_TYPE);
CASE(MACH_SEND_INVALID_HEADER);
CASE(MACH_SEND_INVALID_TRAILER);
CASE(MACH_SEND_INVALID_RT_OOL_SIZE);
CASE(MACH_RCV_IN_PROGRESS);
CASE(MACH_RCV_INVALID_NAME);
CASE(MACH_RCV_TIMED_OUT);
CASE(MACH_RCV_TOO_LARGE);
CASE(MACH_RCV_INTERRUPTED);
CASE(MACH_RCV_PORT_CHANGED);
CASE(MACH_RCV_INVALID_NOTIFY);
CASE(MACH_RCV_INVALID_DATA);
CASE(MACH_RCV_PORT_DIED);
CASE(MACH_RCV_IN_SET);
CASE(MACH_RCV_HEADER_ERROR);
CASE(MACH_RCV_BODY_ERROR);
CASE(MACH_RCV_INVALID_TYPE);
CASE(MACH_RCV_SCATTER_SMALL);
CASE(MACH_RCV_INVALID_TRAILER);
CASE(MACH_RCV_IN_PROGRESS_TIMED);
case 0: return @"no error";
}
#else
if (0 == inCode) return @"no error";
#endif
return [NSString stringWithFormat:@"0x%.8X", (unsigned)inCode];
}
NSString *FourCharCodeToNSString(FourCharCode inCode)
{
NSString *result;
result = (NSString *)UTCreateStringForOSType(inCode);
return [result autorelease];
}
#ifndef NDEBUG
static NSString *GetGenericOSStatusString(OSStatus inCode)
{
switch (inCode)
{
case noErr: return @"no error";
CASE(paramErr);
CASE(memFullErr);
CASE(unimpErr);
CASE(userCanceledErr);
CASE(dskFulErr);
CASE(fnfErr);
CASE(errFSBadFSRef);
CASE(gestaltUnknownErr);
}
return nil;
}
#endif

View File

@ -1,88 +0,0 @@
//
// 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 "OOCocoa.h"
#import <Foundation/Foundation.h>
@interface VirtualRingBuffer : NSObject
{
@private
void *buffer;
void *bufferEnd;
NSUInteger 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:(NSUInteger)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;
// Read operations:
// The reading thread must call this method first.
- (NSUInteger)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:(NSUInteger)length;
// Write operations:
// The writing thread must call this method first.
- (NSUInteger)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:(NSUInteger)length;
@end

View File

@ -1,309 +0,0 @@
//
// 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"
#import "OOLogging.h"
#include <mach/mach.h>
#include <mach/mach_error.h>
#if DEBUG
#define kOOLogUnconvertedNSLog @"unclassified.VirtualRingBuffer"
#endif
@implementation VirtualRingBuffer
static void *allocateVirtualBuffer(NSUInteger bufferLength);
static void deallocateVirtualBuffer(void *buffer, NSUInteger bufferLength);
- (id)initWithLength:(NSUInteger)length
{
if (!(self = [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);
}
//
// 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
//
- (NSUInteger)lengthAvailableToReadReturningPointer:(void **)returnedReadPointer
{
// Assumptions:
// returnedReadPointer != NULL
NSUInteger 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:(NSUInteger)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
//
- (NSUInteger)lengthAvailableToWriteReturningPointer:(void **)returnedWritePointer
{
// Assumptions:
// returnedWritePointer != NULL
NSUInteger 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:(NSUInteger)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(NSUInteger bufferLength)
{
kern_return_t error;
vm_address_t originalAddress = 0;
vm_address_t realAddress = 0;
mach_port_t memoryEntry;
vm_size_t memoryEntryLength;
vm_address_t virtualAddress = 0;
// 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
NSLog(@"allocateVirtualBuffer: vm_allocate 2nd time didn't return same address (%p vs %p)", (void *)originalAddress, (void *)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, 0);
if (error) {
#if DEBUG
mach_error("mach_make_memory_entry", error);
#endif
goto errorReturn;
}
if (!memoryEntry) {
#if DEBUG
NSLog(@"mach_make_memory_entry: returned memoryEntry of NULL");
#endif
goto errorReturn;
}
if (memoryEntryLength != bufferLength) {
#if DEBUG
NSLog(@"mach_make_memory_entry: size changed (from %0lx to %0lx)", 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 = 0;
goto errorReturn;
}
if (virtualAddress != realAddress + bufferLength) {
#if DEBUG
NSLog(@"vm_map: didn't return correct address (%p vs %p)", (void *)(realAddress + bufferLength), (void *)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, NSUInteger 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

@ -22,7 +22,7 @@ There are four public sound classes:
Oolite
Copyright (C) 2004-2013 Giles C Williams and contributors
Copyright (C) 2004-2014 Giles C Williams and contributors
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
@ -50,15 +50,9 @@ MA 02110-1301, USA.
#import "OOALMusic.h"
#import "OOBasicSoundReferencePoint.h"
#else
#if OOLITE_SDL
#import "OOSDLSound.h"
#import "SDLMusic.h"
#import "OOBasicSoundReferencePoint.h"
#else
#import "OOCASound.h"
#import "OOCAMusic.h"
#import "OOCASoundReferencePoint.h"
#endif
#warning No sound implementation selected. Currently, the only option is OOLITE_OPENAL. There are SDL and Mac CoreAudio implementations in the revision history.
#endif
#import "OOSoundSource.h"

View File

@ -8,22 +8,8 @@
#define OOSoundAcquireLock() do {} while(0)
#define OOSoundReleaseLock() do {} while(0)
#elif OOLITE_SDL
#else
#import "OOSDLSoundMixer.h"
#import "OOSDLSoundChannel.h"
#define OOSoundAcquireLock() do {} while(0)
#define OOSoundReleaseLock() do {} while(0)
#elif OOLITE_MAC_OS_X
#import "OOCASoundMixer.h"
#import "OOCASoundChannel.h"
extern NSRecursiveLock *gOOCASoundSyncLock;
#define OOSoundAcquireLock() [gOOCASoundSyncLock lock]
#define OOSoundReleaseLock() [gOOCASoundSyncLock unlock]
#warning No sound implementation selected. Currently, the only option is OOLITE_OPENAL. There are SDL and Mac CoreAudio implementations in the revision history.
#endif