diff --git a/src/CoreAudio/CoreAudioComponent/AUPublic b/src/CoreAudio/CoreAudioComponent/AUPublic new file mode 120000 index 000000000..6f6e2053f --- /dev/null +++ b/src/CoreAudio/CoreAudioComponent/AUPublic @@ -0,0 +1 @@ +../CoreAudioUtilityClasses/CoreAudio/AudioUnits/AUPublic \ No newline at end of file diff --git a/src/CoreAudio/CoreAudioComponent/AUPublic/AUBase/AUBase.cpp b/src/CoreAudio/CoreAudioComponent/AUPublic/AUBase/AUBase.cpp deleted file mode 100644 index 612bc4d30..000000000 --- a/src/CoreAudio/CoreAudioComponent/AUPublic/AUBase/AUBase.cpp +++ /dev/null @@ -1,2393 +0,0 @@ -/* - File: AUBase.cpp - Abstract: AUBase.h - Version: 1.1 - - Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple - Inc. ("Apple") in consideration of your agreement to the following - terms, and your use, installation, modification or redistribution of - this Apple software constitutes acceptance of these terms. If you do - not agree with these terms, please do not use, install, modify or - redistribute this Apple software. - - In consideration of your agreement to abide by the following terms, and - subject to these terms, Apple grants you a personal, non-exclusive - license, under Apple's copyrights in this original Apple software (the - "Apple Software"), to use, reproduce, modify and redistribute the Apple - Software, with or without modifications, in source and/or binary forms; - provided that if you redistribute the Apple Software in its entirety and - without modifications, you must retain this notice and the following - text and disclaimers in all such redistributions of the Apple Software. - Neither the name, trademarks, service marks or logos of Apple Inc. may - be used to endorse or promote products derived from the Apple Software - without specific prior written permission from Apple. Except as - expressly stated in this notice, no other rights or licenses, express or - implied, are granted by Apple herein, including but not limited to any - patent rights that may be infringed by your derivative works or by other - works in which the Apple Software may be incorporated. - - The Apple Software is provided by Apple on an "AS IS" basis. APPLE - MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION - THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS - FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND - OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS. - - IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL - OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, - MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED - AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), - STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE - POSSIBILITY OF SUCH DAMAGE. - - Copyright (C) 2014 Apple Inc. All Rights Reserved. - -*/ -#include "AUBase.h" -#include "AUDispatch.h" -#include "AUInputElement.h" -#include "AUOutputElement.h" -#include -#include -#include "CAAudioChannelLayout.h" -#include "CAHostTimeBase.h" -#include "CAVectorUnit.h" -#include "CAXException.h" - - - -#if TARGET_OS_MAC && (TARGET_CPU_X86 || TARGET_CPU_X86_64) - // our compiler does ALL floating point with SSE - inline int GETCSR () { int _result; asm volatile ("stmxcsr %0" : "=m" (*&_result) ); return _result; } - inline void SETCSR (int a) { int _temp = a; asm volatile( "ldmxcsr %0" : : "m" (*&_temp ) ); } - - #define DISABLE_DENORMALS int _savemxcsr = GETCSR(); SETCSR(_savemxcsr | 0x8040); - #define RESTORE_DENORMALS SETCSR(_savemxcsr); -#else - #define DISABLE_DENORMALS - #define RESTORE_DENORMALS -#endif - -static bool sAUBaseCFStringsInitialized = false; -// this is used for the presets -static CFStringRef kUntitledString = NULL; -//these are the current keys for the class info document -static CFStringRef kVersionString = NULL; -static CFStringRef kTypeString = NULL; -static CFStringRef kSubtypeString = NULL; -static CFStringRef kManufacturerString = NULL; -static CFStringRef kDataString = NULL; -static CFStringRef kNameString = NULL; -static CFStringRef kRenderQualityString = NULL; -static CFStringRef kCPULoadString = NULL; -static CFStringRef kElementNameString = NULL; -static CFStringRef kPartString = NULL; - -SInt32 AUBase::sVectorUnitType = kVecUninitialized; - -//_____________________________________________________________________________ -// -AUBase::AUBase( AudioComponentInstance inInstance, - UInt32 numInputElements, - UInt32 numOutputElements, - UInt32 numGroupElements) : - ComponentBase(inInstance), - mElementsCreated(false), - mInitialized(false), - mHasBegunInitializing(false), - mInitNumInputEls(numInputElements), mInitNumOutputEls(numOutputElements), -#if !CA_BASIC_AU_FEATURES - mInitNumGroupEls(numGroupElements), -#endif - mRenderCallbacksTouched(false), - mRenderThreadID (NULL), - mWantsRenderThreadID (false), - mLastRenderError(0), - mUsesFixedBlockSize(false), - mBuffersAllocated(false), - mLogString (NULL), - mNickName (NULL), - mAUMutex(NULL) - #if !CA_NO_AU_UI_FEATURES - , - mContextName(NULL) - #endif -{ - ResetRenderTime (); - - if(!sAUBaseCFStringsInitialized) - { - kUntitledString = CFSTR("Untitled"); - kVersionString = CFSTR(kAUPresetVersionKey); - kTypeString = CFSTR(kAUPresetTypeKey); - kSubtypeString = CFSTR(kAUPresetSubtypeKey); - kManufacturerString = CFSTR(kAUPresetManufacturerKey); - kDataString = CFSTR(kAUPresetDataKey); - kNameString = CFSTR(kAUPresetNameKey); - kRenderQualityString = CFSTR(kAUPresetRenderQualityKey); - kCPULoadString = CFSTR(kAUPresetCPULoadKey); - kElementNameString = CFSTR(kAUPresetElementNameKey); - kPartString = CFSTR(kAUPresetPartKey); - sAUBaseCFStringsInitialized = true; - } - - if (sVectorUnitType == kVecUninitialized) { - sVectorUnitType = CAVectorUnit::GetVectorUnitType() ; - } - - mAudioUnitAPIVersion = 2; - - SetMaxFramesPerSlice(kAUDefaultMaxFramesPerSlice); - - GlobalScope().Initialize(this, kAudioUnitScope_Global, 1); - -#if !CA_NO_AU_UI_FEATURES - memset (&mHostCallbackInfo, 0, sizeof (mHostCallbackInfo)); -#endif - - - mCurrentPreset.presetNumber = -1; - mCurrentPreset.presetName = kUntitledString; - CFRetain (mCurrentPreset.presetName); -} - -//_____________________________________________________________________________ -// -AUBase::~AUBase() -{ - if (mCurrentPreset.presetName) CFRelease (mCurrentPreset.presetName); -#if !CA_NO_AU_UI_FEATURES - if (mContextName) CFRelease (mContextName); -#endif - if (mLogString) delete [] mLogString; - if (mNickName) CFRelease(mNickName); -} - -//_____________________________________________________________________________ -// -void AUBase::CreateElements() -{ - if (!mElementsCreated) { - Inputs().Initialize(this, kAudioUnitScope_Input, mInitNumInputEls); - Outputs().Initialize(this, kAudioUnitScope_Output, mInitNumOutputEls); -#if !CA_BASIC_AU_FEATURES - Groups().Initialize(this, kAudioUnitScope_Group, mInitNumGroupEls); -#endif - CreateExtendedElements(); - - mElementsCreated = true; - } -} - -//_____________________________________________________________________________ -// -void AUBase::SetMaxFramesPerSlice(UInt32 nFrames) -{ - mMaxFramesPerSlice = nFrames; - if (mBuffersAllocated) - ReallocateBuffers(); - PropertyChanged(kAudioUnitProperty_MaximumFramesPerSlice, kAudioUnitScope_Global, 0); -} - -//_____________________________________________________________________________ -// -OSStatus AUBase::CanSetMaxFrames() const -{ - return IsInitialized() ? kAudioUnitErr_Initialized : OSStatus(noErr); -} - -//_____________________________________________________________________________ -// -void AUBase::ReallocateBuffers() -{ - CreateElements(); - - UInt32 nOutputs = Outputs().GetNumberOfElements(); - for (UInt32 i = 0; i < nOutputs; ++i) { - AUOutputElement *output = GetOutput(i); - output->AllocateBuffer(); // does no work if already allocated - } - UInt32 nInputs = Inputs().GetNumberOfElements(); - for (UInt32 i = 0; i < nInputs; ++i) { - AUInputElement *input = GetInput(i); - input->AllocateBuffer(); // does no work if already allocated - } - mBuffersAllocated = true; -} - -//_____________________________________________________________________________ -// -void AUBase::DeallocateIOBuffers() -{ - if (!mBuffersAllocated) - return; - - UInt32 nOutputs = Outputs().GetNumberOfElements(); - for (UInt32 i = 0; i < nOutputs; ++i) { - AUOutputElement *output = GetOutput(i); - output->DeallocateBuffer(); - } - UInt32 nInputs = Inputs().GetNumberOfElements(); - for (UInt32 i = 0; i < nInputs; ++i) { - AUInputElement *input = GetInput(i); - input->DeallocateBuffer(); - } - mBuffersAllocated = false; -} - -//_____________________________________________________________________________ -// -OSStatus AUBase::DoInitialize() -{ - OSStatus result = noErr; - - if (!mInitialized) { - result = Initialize(); - if (result == noErr) { - if (CanScheduleParameters()) - mParamList.reserve(24); - mHasBegunInitializing = true; - ReallocateBuffers(); // calls CreateElements() - mInitialized = true; // signal that it's okay to render - CAMemoryBarrier(); - } - } - - return result; -} - -//_____________________________________________________________________________ -// -OSStatus AUBase::Initialize() -{ - return noErr; -} - -//_____________________________________________________________________________ -// -void AUBase::PreDestructor() -{ - // this is called from the ComponentBase dispatcher, which doesn't know anything about our (optional) lock - CAMutex::Locker lock(mAUMutex); - DoCleanup(); -} - -//_____________________________________________________________________________ -// -void AUBase::DoCleanup() -{ - if (mInitialized) - Cleanup(); - - DeallocateIOBuffers(); - ResetRenderTime (); - - mInitialized = false; - mHasBegunInitializing = false; -} - -//_____________________________________________________________________________ -// -void AUBase::Cleanup() -{ -} - -//_____________________________________________________________________________ -// -OSStatus AUBase::Reset( AudioUnitScope inScope, - AudioUnitElement inElement) -{ - ResetRenderTime (); - return noErr; -} - -//_____________________________________________________________________________ -// -OSStatus AUBase::DispatchGetPropertyInfo(AudioUnitPropertyID inID, - AudioUnitScope inScope, - AudioUnitElement inElement, - UInt32 & outDataSize, - Boolean & outWritable) -{ - OSStatus result = noErr; - bool validateElement = true; - - switch (inID) { - case kAudioUnitProperty_MakeConnection: - ca_require(inScope == kAudioUnitScope_Input || inScope == kAudioUnitScope_Global, InvalidScope); - outDataSize = sizeof(AudioUnitConnection); - outWritable = true; - break; - - - case kAudioUnitProperty_SetRenderCallback: - ca_require(AudioUnitAPIVersion() > 1, InvalidProperty); - ca_require(inScope == kAudioUnitScope_Input || inScope == kAudioUnitScope_Global, InvalidScope); - outDataSize = sizeof(AURenderCallbackStruct); - outWritable = true; - break; - - case kAudioUnitProperty_StreamFormat: - outDataSize = sizeof(CAStreamBasicDescription); - outWritable = IsStreamFormatWritable(inScope, inElement); - break; - - case kAudioUnitProperty_SampleRate: - outDataSize = sizeof(Float64); - outWritable = IsStreamFormatWritable(inScope, inElement); - break; - - case kAudioUnitProperty_ClassInfo: - ca_require(inScope == kAudioUnitScope_Global, InvalidScope); - outDataSize = sizeof(CFPropertyListRef); - outWritable = true; - break; - - case kAudioUnitProperty_FactoryPresets: - ca_require(inScope == kAudioUnitScope_Global, InvalidScope); - result = GetPresets(NULL); - if (!result) { - outDataSize = sizeof(CFArrayRef); - outWritable = false; - } - break; - - case kAudioUnitProperty_PresentPreset: -#if !CA_USE_AUDIO_PLUGIN_ONLY -#ifndef __LP64__ - case kAudioUnitProperty_CurrentPreset: -#endif -#endif - ca_require(inScope == kAudioUnitScope_Global, InvalidScope); - outDataSize = sizeof(AUPreset); - outWritable = true; - break; - - case kAudioUnitProperty_ElementName: - outDataSize = sizeof (CFStringRef); - outWritable = true; - break; - - case kAudioUnitProperty_ParameterList: - { - UInt32 nparams = 0; - result = GetParameterList(inScope, NULL, nparams); - - outDataSize = sizeof(AudioUnitParameterID) * nparams; - outWritable = false; - validateElement = false; - } - break; - - case kAudioUnitProperty_ParameterInfo: - outDataSize = sizeof(AudioUnitParameterInfo); - outWritable = false; - validateElement = false; - break; - - case kAudioUnitProperty_ParameterHistoryInfo: - outDataSize = sizeof(AudioUnitParameterHistoryInfo); - outWritable = false; - validateElement = false; - break; - - case kAudioUnitProperty_ElementCount: - outDataSize = sizeof(UInt32); - outWritable = BusCountWritable(inScope); - validateElement = false; - break; - - case kAudioUnitProperty_Latency: - ca_require(inScope == kAudioUnitScope_Global, InvalidScope); - outDataSize = sizeof(Float64); - outWritable = false; - break; - - case kAudioUnitProperty_TailTime: - ca_require(inScope == kAudioUnitScope_Global, InvalidScope); - if (SupportsTail()) { - outDataSize = sizeof(Float64); - outWritable = false; - } else - goto InvalidProperty; - break; - - case kAudioUnitProperty_MaximumFramesPerSlice: - ca_require(inScope == kAudioUnitScope_Global, InvalidScope); - outDataSize = sizeof(UInt32); - outWritable = true; - break; - - case kAudioUnitProperty_LastRenderError: - ca_require(inScope == kAudioUnitScope_Global, InvalidScope); - outDataSize = sizeof(OSStatus); - outWritable = false; - break; - - case kAudioUnitProperty_SupportedNumChannels: - { - ca_require(inScope == kAudioUnitScope_Global, InvalidScope); - UInt32 num = SupportedNumChannels (NULL); - if (num) { - outDataSize = sizeof (AUChannelInfo) * num; - result = noErr; - } else - goto InvalidProperty; - outWritable = false; - break; - } - - case kAudioUnitProperty_SupportedChannelLayoutTags: - { - UInt32 numLayouts = GetChannelLayoutTags(inScope, inElement, NULL); - if (numLayouts) { - outDataSize = numLayouts * sizeof(AudioChannelLayoutTag); - result = noErr; - } else - goto InvalidProperty; - outWritable = false; - validateElement = false; //already done it - break; - } - - case kAudioUnitProperty_AudioChannelLayout: - { - outWritable = false; - outDataSize = GetAudioChannelLayout(inScope, inElement, NULL, outWritable); - if (outDataSize) { - result = noErr; - } else { - if (GetChannelLayoutTags(inScope, inElement, NULL) == 0) - goto InvalidProperty; - else - result = kAudioUnitErr_InvalidPropertyValue; - } - validateElement = false; //already done it - break; - } - -#if (MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5) || TARGET_OS_IPHONE - case kAudioUnitProperty_ShouldAllocateBuffer: - ca_require((inScope == kAudioUnitScope_Input || inScope == kAudioUnitScope_Output), InvalidScope); - outWritable = true; - outDataSize = sizeof(UInt32); - break; -#endif - -#if !CA_USE_AUDIO_PLUGIN_ONLY - case kAudioUnitProperty_FastDispatch: - ca_require(inScope == kAudioUnitScope_Global, InvalidScope); - if (!IsCMgrObject()) goto InvalidProperty; - outDataSize = sizeof(void *); - outWritable = false; - validateElement = false; - break; - - case kAudioUnitProperty_GetUIComponentList: - ca_require(inScope == kAudioUnitScope_Global, InvalidScope); - outDataSize = GetNumCustomUIComponents(); - if (outDataSize == 0) - goto InvalidProperty; - outDataSize *= sizeof (AudioComponentDescription); - - outWritable = false; - break; -#endif - - case kAudioUnitProperty_ParameterValueStrings: - result = GetParameterValueStrings(inScope, inElement, NULL); - if (result == noErr) { - outDataSize = sizeof(CFArrayRef); - outWritable = false; - validateElement = false; - } - break; - -#if !CA_NO_AU_HOST_CALLBACKS - case kAudioUnitProperty_HostCallbacks: - ca_require(inScope == kAudioUnitScope_Global, InvalidScope); - outDataSize = sizeof(mHostCallbackInfo); - outWritable = true; - break; -#endif -#if !CA_NO_AU_UI_FEATURES - case kAudioUnitProperty_ContextName: - ca_require(inScope == kAudioUnitScope_Global, InvalidScope); - outDataSize = sizeof(CFStringRef); - outWritable = true; - break; - - case kAudioUnitProperty_IconLocation: - ca_require(inScope == kAudioUnitScope_Global, InvalidScope); - outWritable = false; - if (!HasIcon()) - goto InvalidProperty; - outDataSize = sizeof(CFURLRef); - break; - - case kAudioUnitProperty_ParameterClumpName: - outDataSize = sizeof(AudioUnitParameterNameInfo ); - outWritable = false; - break; - -#endif // !CA_NO_AU_UI_FEATURES - - case 'lrst' : // kAudioUnitProperty_LastRenderedSampleTime - outDataSize = sizeof(Float64); - outWritable = false; - break; - - case kAudioUnitProperty_NickName: - ca_require(inScope == kAudioUnitScope_Global, InvalidScope); - outDataSize = sizeof(CFStringRef); - outWritable = true; - break; - - default: - result = GetPropertyInfo(inID, inScope, inElement, outDataSize, outWritable); - validateElement = false; - break; - } - - if (result == noErr && validateElement) { - ca_require(GetElement(inScope, inElement) != NULL, InvalidElement); - } - - return result; -InvalidProperty: - return kAudioUnitErr_InvalidProperty; -InvalidScope: - return kAudioUnitErr_InvalidScope; -InvalidElement: - return kAudioUnitErr_InvalidElement; -} - -//_____________________________________________________________________________ -// -OSStatus AUBase::DispatchGetProperty( AudioUnitPropertyID inID, - AudioUnitScope inScope, - AudioUnitElement inElement, - void * outData) -{ - // NOTE: We're currently only called from AUBase::ComponentEntryDispatch, which - // calls DispatchGetPropertyInfo first, which performs validation of the scope/element, - // and ensures that the outData buffer is non-null and large enough. - OSStatus result = noErr; - - switch (inID) { - case kAudioUnitProperty_StreamFormat: - *(CAStreamBasicDescription *)outData = GetStreamFormat(inScope, inElement); - break; - - case kAudioUnitProperty_SampleRate: - *(Float64 *)outData = GetStreamFormat(inScope, inElement).mSampleRate; - break; - - case kAudioUnitProperty_ParameterList: - { - UInt32 nparams = 0; - result = GetParameterList(inScope, (AudioUnitParameterID *)outData, nparams); - } - break; - - case kAudioUnitProperty_ParameterInfo: - result = GetParameterInfo(inScope, inElement, *(AudioUnitParameterInfo *)outData); - break; - - case kAudioUnitProperty_ParameterHistoryInfo: - { - AudioUnitParameterHistoryInfo* info = (AudioUnitParameterHistoryInfo*)outData; - result = GetParameterHistoryInfo(inScope, inElement, info->updatesPerSecond, info->historyDurationInSeconds); - } - break; - - case kAudioUnitProperty_ClassInfo: - { - *(CFPropertyListRef *)outData = NULL; - result = SaveState((CFPropertyListRef *)outData); - } - break; - - case kAudioUnitProperty_FactoryPresets: - { - *(CFArrayRef *)outData = NULL; - result = GetPresets ((CFArrayRef *)outData); - } - break; - - case kAudioUnitProperty_PresentPreset: -#if !CA_USE_AUDIO_PLUGIN_ONLY -#ifndef __LP64__ - case kAudioUnitProperty_CurrentPreset: -#endif -#endif - { - *(AUPreset *)outData = mCurrentPreset; - - // retain current string (as client owns a reference to it and will release it) - if (inID == kAudioUnitProperty_PresentPreset && mCurrentPreset.presetName) - CFRetain (mCurrentPreset.presetName); - - result = noErr; - } - break; - - case kAudioUnitProperty_ElementName: - { - AUElement * element = GetElement(inScope, inElement); - if (element->HasName()) { - *(CFStringRef *)outData = element->GetName(); - CFRetain (element->GetName()); - result = noErr; - } else - result = kAudioUnitErr_InvalidPropertyValue; - } - break; - - case kAudioUnitProperty_ElementCount: - *(UInt32 *)outData = GetScope(inScope).GetNumberOfElements(); - break; - - case kAudioUnitProperty_Latency: - *(Float64 *)outData = GetLatency(); - break; - - case kAudioUnitProperty_TailTime: - if (SupportsTail()) - *(Float64 *)outData = GetTailTime(); - else - result = kAudioUnitErr_InvalidProperty; - break; - - case kAudioUnitProperty_MaximumFramesPerSlice: - *(UInt32 *)outData = mMaxFramesPerSlice; - break; - - case kAudioUnitProperty_LastRenderError: - *(OSStatus *)outData = mLastRenderError; - mLastRenderError = 0; - break; - - case kAudioUnitProperty_SupportedNumChannels: - { - const AUChannelInfo* infoPtr = NULL; - UInt32 num = SupportedNumChannels (&infoPtr); - if(num != 0 && infoPtr != NULL) - memcpy (outData, infoPtr, num * sizeof (AUChannelInfo)); - } - break; - - case kAudioUnitProperty_SupportedChannelLayoutTags: - { - AudioChannelLayoutTag* ptr = outData ? static_cast(outData) : NULL; - UInt32 numLayouts = GetChannelLayoutTags (inScope, inElement, ptr); - if (numLayouts == 0) - result = kAudioUnitErr_InvalidProperty; - } - break; - - case kAudioUnitProperty_AudioChannelLayout: - { - AudioChannelLayout* ptr = outData ? static_cast(outData) : NULL; - Boolean writable; - UInt32 dataSize = GetAudioChannelLayout(inScope, inElement, ptr, writable); - if (!dataSize) { - result = kAudioUnitErr_InvalidProperty; - } - break; - } - -#if (MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5) || TARGET_OS_IPHONE - case kAudioUnitProperty_ShouldAllocateBuffer: - { - AUIOElement * element = GetIOElement(inScope, inElement); - *(UInt32*)outData = element->WillAllocateBuffer(); - break; - } -#endif - - case kAudioUnitProperty_ParameterValueStrings: - result = GetParameterValueStrings(inScope, inElement, (CFArrayRef *)outData); - break; - -#if !CA_USE_AUDIO_PLUGIN_ONLY - case kAudioUnitProperty_FastDispatch: - if (!IsCMgrObject()) result = kAudioUnitErr_InvalidProperty; - else { - switch (inElement) { - case kAudioUnitGetParameterSelect: - *(AudioUnitGetParameterProc *)outData = (AudioUnitGetParameterProc)CMgr_AudioUnitBaseGetParameter; - break; - case kAudioUnitSetParameterSelect: - *(AudioUnitSetParameterProc *)outData = (AudioUnitSetParameterProc)CMgr_AudioUnitBaseSetParameter; - break; - case kAudioUnitRenderSelect: - if (AudioUnitAPIVersion() > 1) - *(AudioUnitRenderProc *)outData = (AudioUnitRenderProc)CMgr_AudioUnitBaseRender; - else result = kAudioUnitErr_InvalidElement; - break; - default: - result = GetProperty(inID, inScope, inElement, outData); - break; - } - } - break; - - case kAudioUnitProperty_GetUIComponentList: - GetUIComponentDescs ((ComponentDescription*)outData); - break; -#endif - -#if !CA_NO_AU_HOST_CALLBACKS - case kAudioUnitProperty_HostCallbacks: - memcpy(outData, &mHostCallbackInfo, sizeof(mHostCallbackInfo)); - break; -#endif -#if !CA_NO_AU_UI_FEATURES - case kAudioUnitProperty_IconLocation: - { - CFURLRef iconLocation = CopyIconLocation(); - if (iconLocation) { - *(CFURLRef*)outData = iconLocation; - } else - result = kAudioUnitErr_InvalidProperty; - } - break; - - case kAudioUnitProperty_ContextName: - *(CFStringRef *)outData = mContextName; - if (mContextName) { - CFRetain(mContextName); - // retain CFString (if exists) since client will be responsible for its release - result = noErr; - } else { - result = kAudioUnitErr_InvalidPropertyValue; - } - break; - - case kAudioUnitProperty_ParameterClumpName: - { - AudioUnitParameterNameInfo * ioClumpInfo = (AudioUnitParameterNameInfo*) outData; - if (ioClumpInfo->inID == kAudioUnitClumpID_System) // this ID value is reserved - result = kAudioUnitErr_InvalidPropertyValue; - else - { - result = CopyClumpName(inScope, ioClumpInfo->inID, ioClumpInfo->inDesiredLength, &ioClumpInfo->outName); - - // this is provided for compatbility with existing implementations that don't know - // about this new mechanism - if (result == kAudioUnitErr_InvalidProperty) - result = GetProperty (inID, inScope, inElement, outData); - } - } - break; - -#endif // !CA_NO_AU_UI_FEATURES - - case 'lrst' : // kAudioUnitProperty_LastRenderedSampleTime - *(Float64*)outData = mCurrentRenderTime.mSampleTime; - break; - - case kAudioUnitProperty_NickName: - // Ownership follows Core Foundation's 'Copy Rule' - if (mNickName) CFRetain(mNickName); - *(CFStringRef*)outData = mNickName; - break; - - default: - result = GetProperty(inID, inScope, inElement, outData); - break; - } - return result; -} - - -//_____________________________________________________________________________ -// -OSStatus AUBase::DispatchSetProperty( AudioUnitPropertyID inID, - AudioUnitScope inScope, - AudioUnitElement inElement, - const void * inData, - UInt32 inDataSize) -{ - OSStatus result = noErr; - - switch (inID) { - case kAudioUnitProperty_MakeConnection: - ca_require(inDataSize >= sizeof(AudioUnitConnection), InvalidPropertyValue); - { - AudioUnitConnection &connection = *(AudioUnitConnection *)inData; - result = SetConnection(connection); - } - break; - - - case kAudioUnitProperty_SetRenderCallback: - { - ca_require(inDataSize >= sizeof(AURenderCallbackStruct), InvalidPropertyValue); - ca_require(AudioUnitAPIVersion() > 1, InvalidProperty); - AURenderCallbackStruct &callback = *(AURenderCallbackStruct*)inData; - result = SetInputCallback(kAudioUnitProperty_SetRenderCallback, inElement, callback.inputProc, callback.inputProcRefCon); - } - break; - - case kAudioUnitProperty_ElementCount: - ca_require(inDataSize == sizeof(UInt32), InvalidPropertyValue); - ca_require(BusCountWritable(inScope), NotWritable); - result = SetBusCount(inScope, *(UInt32*)inData); - if (result == noErr) { - PropertyChanged(inID, inScope, inElement); - } - break; - - case kAudioUnitProperty_MaximumFramesPerSlice: - ca_require(inDataSize == sizeof(UInt32), InvalidPropertyValue); - result = CanSetMaxFrames(); - if (result) return result; - SetMaxFramesPerSlice(*(UInt32 *)inData); - break; - - case kAudioUnitProperty_StreamFormat: - { - if (inDataSize < 36) goto InvalidPropertyValue; - ca_require(GetElement(inScope, inElement) != NULL, InvalidElement); - - CAStreamBasicDescription newDesc; - // now we're going to be ultra conservative! because of discrepancies between - // sizes of this struct based on aligment padding inconsistencies - memset (&newDesc, 0, sizeof(newDesc)); - memcpy (&newDesc, inData, 36); - - ca_require(ValidFormat(inScope, inElement, newDesc), InvalidFormat); - - const CAStreamBasicDescription curDesc = GetStreamFormat(inScope, inElement); - - if ( !curDesc.IsEqual(newDesc, false) ) { - ca_require(IsStreamFormatWritable(inScope, inElement), NotWritable); - result = ChangeStreamFormat(inScope, inElement, curDesc, newDesc); - } - } - break; - - case kAudioUnitProperty_SampleRate: - { - ca_require(inDataSize == sizeof(Float64), InvalidPropertyValue); - ca_require(GetElement(inScope, inElement) != NULL, InvalidElement); - - const CAStreamBasicDescription curDesc = GetStreamFormat(inScope, inElement); - CAStreamBasicDescription newDesc = curDesc; - newDesc.mSampleRate = *(Float64 *)inData; - - ca_require(ValidFormat(inScope, inElement, newDesc), InvalidFormat); - - if ( !curDesc.IsEqual(newDesc, false) ) { - ca_require(IsStreamFormatWritable(inScope, inElement), NotWritable); - result = ChangeStreamFormat(inScope, inElement, curDesc, newDesc); - } - } - break; - - case kAudioUnitProperty_AudioChannelLayout: - { - const AudioChannelLayout *layout = static_cast(inData); - size_t headerSize = sizeof(AudioChannelLayout) - sizeof(AudioChannelDescription); - - ca_require(inDataSize >= headerSize + layout->mNumberChannelDescriptions * sizeof(AudioChannelDescription), InvalidPropertyValue); - result = SetAudioChannelLayout(inScope, inElement, layout); - if (result == noErr) - PropertyChanged(inID, inScope, inElement); - break; - } - - case kAudioUnitProperty_ClassInfo: - ca_require(inDataSize == sizeof(CFPropertyListRef *), InvalidPropertyValue); - ca_require(inScope == kAudioUnitScope_Global, InvalidScope); - result = RestoreState(*(CFPropertyListRef *)inData); - break; - - case kAudioUnitProperty_PresentPreset: -#if !CA_USE_AUDIO_PLUGIN_ONLY -#ifndef __LP64__ - case kAudioUnitProperty_CurrentPreset: -#endif -#endif - { - ca_require(inDataSize == sizeof(AUPreset), InvalidPropertyValue); - ca_require(inScope == kAudioUnitScope_Global, InvalidScope); - AUPreset & newPreset = *(AUPreset *)inData; - - if (newPreset.presetNumber >= 0) - { - result = NewFactoryPresetSet(newPreset); - // NewFactoryPresetSet SHOULD call SetAFactoryPreset if the preset is valid - // from its own list of preset number->name - if (!result) - PropertyChanged(inID, inScope, inElement); - } - else if (newPreset.presetName) - { - result = NewCustomPresetSet(newPreset); - if (!result) - PropertyChanged(inID, inScope, inElement); - } - else - result = kAudioUnitErr_InvalidPropertyValue; - } - break; - - case kAudioUnitProperty_ElementName: - { - ca_require(GetElement(inScope, inElement) != NULL, InvalidElement); - ca_require(inDataSize == sizeof(CFStringRef), InvalidPropertyValue); - AUElement * element = GetScope(inScope).GetElement (inElement); - element->SetName (*(CFStringRef *)inData); - PropertyChanged(inID, inScope, inElement); - } - break; - -#if (MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5) || TARGET_OS_IPHONE - case kAudioUnitProperty_ShouldAllocateBuffer: - { - ca_require((inScope == kAudioUnitScope_Input || inScope == kAudioUnitScope_Output), InvalidScope); - ca_require(GetElement(inScope, inElement) != NULL, InvalidElement); - ca_require(inDataSize == sizeof(UInt32), InvalidPropertyValue); - ca_require(!IsInitialized(), Initialized); - - AUIOElement * element = GetIOElement(inScope, inElement); - element->SetWillAllocateBuffer(*(UInt32 *)inData != 0); - } - break; -#endif - -#if !CA_NO_AU_HOST_CALLBACKS - case kAudioUnitProperty_HostCallbacks: - { - ca_require(inScope == kAudioUnitScope_Global, InvalidScope); - UInt32 availSize = std::min(inDataSize, (UInt32)sizeof(HostCallbackInfo)); - bool hasChanged = !memcmp (&mHostCallbackInfo, inData, availSize); - memset (&mHostCallbackInfo, 0, sizeof (mHostCallbackInfo)); - memcpy (&mHostCallbackInfo, inData, availSize); - if (hasChanged) - PropertyChanged(inID, inScope, inElement); - break; - } -#endif -#if !CA_NO_AU_UI_FEATURES - case kAudioUnitProperty_SetExternalBuffer: - ca_require(inDataSize >= sizeof(AudioUnitExternalBuffer), InvalidPropertyValue); - ca_require(IsInitialized(), Uninitialized); - { - AudioUnitExternalBuffer &buf = *(AudioUnitExternalBuffer*)inData; - if (intptr_t(buf.buffer) & 0x0F) result = kAudio_ParamError; - else if (inScope == kAudioUnitScope_Input) { - AUInputElement *input = GetInput(inElement); - input->UseExternalBuffer(buf); - } else { - AUOutputElement *output = GetOutput(inElement); - output->UseExternalBuffer(buf); - } - } - break; - - case kAudioUnitProperty_ContextName: - { - ca_require(inDataSize == sizeof(CFStringRef), InvalidPropertyValue); - ca_require(inScope == kAudioUnitScope_Global, InvalidScope); - CFStringRef inStr = *(CFStringRef *)inData; - if (mContextName) CFRelease(mContextName); - if (inStr) CFRetain(inStr); - mContextName = inStr; - PropertyChanged(inID, inScope, inElement); - } - break; - -#endif // !CA_NO_AU_UI_FEATURES - - case kAudioUnitProperty_NickName: - { - ca_require(inScope == kAudioUnitScope_Global, InvalidScope); - ca_require(inDataSize == sizeof(CFStringRef), InvalidPropertyValue); - CFStringRef inStr = *(CFStringRef *)inData; - if (mNickName) CFRelease(mNickName); - if (inStr) CFRetain(inStr); - mNickName = inStr; - PropertyChanged(inID, inScope, inElement); - break; - } - - default: - result = SetProperty(inID, inScope, inElement, inData, inDataSize); - if (result == noErr) - PropertyChanged(inID, inScope, inElement); - - break; - } - return result; -NotWritable: - return kAudioUnitErr_PropertyNotWritable; -InvalidFormat: - return kAudioUnitErr_FormatNotSupported; -#if !CA_NO_AU_UI_FEATURES -Uninitialized: - return kAudioUnitErr_Uninitialized; -#endif -#if (MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5) || CA_USE_AUDIO_PLUGIN_ONLY -Initialized: - return kAudioUnitErr_Initialized; -#endif -InvalidScope: - return kAudioUnitErr_InvalidScope; -InvalidProperty: - return kAudioUnitErr_InvalidProperty; -InvalidPropertyValue: - return kAudioUnitErr_InvalidPropertyValue; -InvalidElement: - return kAudioUnitErr_InvalidElement; -} - -//_____________________________________________________________________________ -// -OSStatus AUBase::DispatchRemovePropertyValue (AudioUnitPropertyID inID, - AudioUnitScope inScope, - AudioUnitElement inElement) -{ - OSStatus result = noErr; - switch (inID) - { - case kAudioUnitProperty_AudioChannelLayout: - { - result = RemoveAudioChannelLayout(inScope, inElement); - if (result == noErr) - PropertyChanged(inID, inScope, inElement); - break; - } - -#if !CA_NO_AU_HOST_CALLBACKS - case kAudioUnitProperty_HostCallbacks: - { - ca_require(inScope == kAudioUnitScope_Global, InvalidScope); - bool hasValue = false; - void* ptr = &mHostCallbackInfo; - for (unsigned int i = 0; i < sizeof (HostCallbackInfo); ++i) { - if (static_cast(ptr)[i]) { - hasValue = true; - break; - } - } - if (hasValue) { - memset (&mHostCallbackInfo, 0, sizeof (HostCallbackInfo)); - PropertyChanged(inID, inScope, inElement); - } - break; - } -#endif -#if !CA_NO_AU_UI_FEATURES - case kAudioUnitProperty_ContextName: - if (mContextName) CFRelease(mContextName); - mContextName = NULL; - result = noErr; - break; - -#endif // !CA_NO_AU_UI_FEATURES - - case kAudioUnitProperty_NickName: - { - if(inScope == kAudioUnitScope_Global) { - if (mNickName) CFRelease(mNickName); - mNickName = NULL; - PropertyChanged(inID, inScope, inElement); - } else { - result = kAudioUnitErr_InvalidScope; - } - break; - } - - default: - result = RemovePropertyValue (inID, inScope, inElement); - break; - } - - return result; -#if !CA_NO_AU_UI_FEATURES || !CA_NO_AU_HOST_CALLBACKS -InvalidScope: - return kAudioUnitErr_InvalidScope; -#endif -} - -//_____________________________________________________________________________ -// -OSStatus AUBase::GetPropertyInfo( AudioUnitPropertyID inID, - AudioUnitScope inScope, - AudioUnitElement inElement, - UInt32 & outDataSize, - Boolean & outWritable) -{ - return kAudioUnitErr_InvalidProperty; -} - - -//_____________________________________________________________________________ -// -OSStatus AUBase::GetProperty( AudioUnitPropertyID inID, - AudioUnitScope inScope, - AudioUnitElement inElement, - void * outData) -{ - return kAudioUnitErr_InvalidProperty; -} - - -//_____________________________________________________________________________ -// -OSStatus AUBase::SetProperty( AudioUnitPropertyID inID, - AudioUnitScope inScope, - AudioUnitElement inElement, - const void * inData, - UInt32 inDataSize) -{ - return kAudioUnitErr_InvalidProperty; -} - -//_____________________________________________________________________________ -// -OSStatus AUBase::RemovePropertyValue ( AudioUnitPropertyID inID, - AudioUnitScope inScope, - AudioUnitElement inElement) -{ - return kAudioUnitErr_InvalidPropertyValue; -} - -//_____________________________________________________________________________ -// -OSStatus AUBase::AddPropertyListener( AudioUnitPropertyID inID, - AudioUnitPropertyListenerProc inProc, - void * inProcRefCon) -{ - PropertyListener pl; - - pl.propertyID = inID; - pl.listenerProc = inProc; - pl.listenerRefCon = inProcRefCon; - - if (mPropertyListeners.empty()) - mPropertyListeners.reserve(32); - mPropertyListeners.push_back(pl); - - return noErr; -} - -//_____________________________________________________________________________ -// -OSStatus AUBase::RemovePropertyListener( AudioUnitPropertyID inID, - AudioUnitPropertyListenerProc inProc, - void * inProcRefCon, - bool refConSpecified) -{ - // iterate in reverse so that it's safe to erase in the middle of the vector - for (int i = (int)mPropertyListeners.size(); --i >=0; ) { - PropertyListeners::iterator it = mPropertyListeners.begin() + i; - if ((*it).propertyID == inID && (*it).listenerProc == inProc && (!refConSpecified || (*it).listenerRefCon == inProcRefCon)) - mPropertyListeners.erase(it); - } - return noErr; -} - -//_____________________________________________________________________________ -// -void AUBase::PropertyChanged( AudioUnitPropertyID inID, - AudioUnitScope inScope, - AudioUnitElement inElement) -{ - for (PropertyListeners::iterator it = mPropertyListeners.begin(); it != mPropertyListeners.end(); ++it) - if ((*it).propertyID == inID) - ((*it).listenerProc)((*it).listenerRefCon, mComponentInstance, inID, inScope, inElement); -} - -//_____________________________________________________________________________ -// -OSStatus AUBase::SetRenderNotification( AURenderCallback inProc, - void * inRefCon) -{ - if (inProc == NULL) - return kAudio_ParamError; - - mRenderCallbacksTouched = true; - mRenderCallbacks.deferred_add(RenderCallback(inProc, inRefCon)); - // this will do nothing if it's already in the list - return noErr; -} - -//_____________________________________________________________________________ -// -OSStatus AUBase::RemoveRenderNotification( AURenderCallback inProc, - void * inRefCon) -{ - mRenderCallbacks.deferred_remove(RenderCallback(inProc, inRefCon)); - return noErr; // error? -} - -//_____________________________________________________________________________ -// -OSStatus AUBase::GetParameter( AudioUnitParameterID inID, - AudioUnitScope inScope, - AudioUnitElement inElement, - AudioUnitParameterValue & outValue) -{ - AUElement *elem = SafeGetElement(inScope, inElement); - outValue = elem->GetParameter(inID); - return noErr; -} - - -//_____________________________________________________________________________ -// -OSStatus AUBase::SetParameter( AudioUnitParameterID inID, - AudioUnitScope inScope, - AudioUnitElement inElement, - AudioUnitParameterValue inValue, - UInt32 inBufferOffsetInFrames) -{ - AUElement *elem = SafeGetElement(inScope, inElement); - elem->SetParameter(inID, inValue); - return noErr; -} - -//_____________________________________________________________________________ -// -OSStatus AUBase::ScheduleParameter ( const AudioUnitParameterEvent *inParameterEvent, - UInt32 inNumEvents) -{ - bool canScheduleParameters = CanScheduleParameters(); - - for (UInt32 i = 0; i < inNumEvents; ++i) - { - if (inParameterEvent[i].eventType == kParameterEvent_Immediate) - { - SetParameter (inParameterEvent[i].parameter, - inParameterEvent[i].scope, - inParameterEvent[i].element, - inParameterEvent[i].eventValues.immediate.value, - inParameterEvent[i].eventValues.immediate.bufferOffset); - } - if (canScheduleParameters) { - mParamList.push_back (inParameterEvent[i]); - } - } - - return noErr; -} - -// ____________________________________________________________________________ -// -static bool SortParameterEventList(const AudioUnitParameterEvent &ev1, const AudioUnitParameterEvent &ev2 ) -{ - int offset1 = ev1.eventType == kParameterEvent_Immediate ? ev1.eventValues.immediate.bufferOffset : ev1.eventValues.ramp.startBufferOffset; - int offset2 = ev2.eventType == kParameterEvent_Immediate ? ev2.eventValues.immediate.bufferOffset : ev2.eventValues.ramp.startBufferOffset; - - if(offset1 < offset2) return true; - return false; -} - - -// ____________________________________________________________________________ -// -OSStatus AUBase::ProcessForScheduledParams( ParameterEventList &inParamList, - UInt32 inFramesToProcess, - void *inUserData ) -{ - OSStatus result = noErr; - - int totalFramesToProcess = inFramesToProcess; - - int framesRemaining = totalFramesToProcess; - - unsigned int currentStartFrame = 0; // start of the whole buffer - - - - // sort the ParameterEventList by startBufferOffset - std::sort(inParamList.begin(), inParamList.end(), SortParameterEventList); - - ParameterEventList::iterator iter = inParamList.begin(); - - - while(framesRemaining > 0 ) - { - // first of all, go through the ramped automation events and find out where the next - // division of our whole buffer will be - - int currentEndFrame = totalFramesToProcess; // start out assuming we'll process all the way to - // the end of the buffer - - iter = inParamList.begin(); - - // find the next break point - while(iter != inParamList.end() ) - { - AudioUnitParameterEvent &event = *iter; - - int offset = event.eventType == kParameterEvent_Immediate ? event.eventValues.immediate.bufferOffset : event.eventValues.ramp.startBufferOffset; - - if(offset > (int)currentStartFrame && offset < currentEndFrame ) - { - currentEndFrame = offset; - break; - } - - // consider ramp end to be a possible choice (there may be gaps in the supplied ramp events) - if(event.eventType == kParameterEvent_Ramped ) - { - offset = event.eventValues.ramp.startBufferOffset + event.eventValues.ramp.durationInFrames; - - if(offset > (int)currentStartFrame && offset < currentEndFrame ) - { - currentEndFrame = offset; - } - } - - iter++; - } - - int framesThisTime = currentEndFrame - currentStartFrame; - - // next, setup the parameter maps to be current for the ramp parameters active during - // this time segment... - - for(ParameterEventList::iterator iter2 = inParamList.begin(); iter2 != inParamList.end(); iter2++ ) - { - AudioUnitParameterEvent &event = *iter2; - - bool eventFallsInSlice; - - - if(event.eventType == kParameterEvent_Ramped) - eventFallsInSlice = event.eventValues.ramp.startBufferOffset < currentEndFrame - && event.eventValues.ramp.startBufferOffset + event.eventValues.ramp.durationInFrames > currentStartFrame; - else /* kParameterEvent_Immediate */ - // actually, for the same parameter, there may be future immediate events which override this one, - // but it's OK since the event list is sorted in time order, we're guaranteed to end up with the current one - eventFallsInSlice = event.eventValues.immediate.bufferOffset <= currentStartFrame; - - if(eventFallsInSlice) - { - AUElement *element = GetElement(event.scope, event.element ); - - if(element) element->SetScheduledEvent( event.parameter, - event, - currentStartFrame, - currentEndFrame - currentStartFrame ); - } - } - - - - // Finally, actually do the processing for this slice..... - - result = ProcessScheduledSlice( inUserData, - currentStartFrame, - framesThisTime, - inFramesToProcess ); - - if(result != noErr) break; - - framesRemaining -= framesThisTime; - currentStartFrame = currentEndFrame; // now start from where we left off last time - } - - return result; -} - -//_____________________________________________________________________________ -// -void AUBase::SetWantsRenderThreadID (bool inFlag) -{ - if (inFlag == mWantsRenderThreadID) - return; - - mWantsRenderThreadID = inFlag; - if (!mWantsRenderThreadID) - mRenderThreadID = NULL; -} - -//_____________________________________________________________________________ -// - -//_____________________________________________________________________________ -// -OSStatus AUBase::DoRender( AudioUnitRenderActionFlags & ioActionFlags, - const AudioTimeStamp & inTimeStamp, - UInt32 inBusNumber, - UInt32 inFramesToProcess, - AudioBufferList & ioData) -{ - OSStatus theError; - RenderCallbackList::iterator rcit; - - AUTRACE(kCATrace_AUBaseRenderStart, mComponentInstance, (uintptr_t)this, inBusNumber, inFramesToProcess, (uintptr_t)ioData.mBuffers[0].mData); - DISABLE_DENORMALS - - try { - ca_require(IsInitialized(), Uninitialized); - ca_require(mAudioUnitAPIVersion >= 2, ParamErr); - if (inFramesToProcess > mMaxFramesPerSlice) { - static time_t lastTimeMessagePrinted = 0; - time_t now = time(NULL); - if (now != lastTimeMessagePrinted) { - lastTimeMessagePrinted = now; - syslog(LOG_ERR, "kAudioUnitErr_TooManyFramesToProcess : inFramesToProcess=%u, mMaxFramesPerSlice=%u", (unsigned)inFramesToProcess, (unsigned)mMaxFramesPerSlice); - DebugMessageN4("%s:%d inFramesToProcess=%u, mMaxFramesPerSlice=%u; TooManyFrames", __FILE__, __LINE__, (unsigned)inFramesToProcess, (unsigned)mMaxFramesPerSlice); - } - goto TooManyFrames; - } - ca_require (!UsesFixedBlockSize() || inFramesToProcess == GetMaxFramesPerSlice(), ParamErr); - - AUOutputElement *output = GetOutput(inBusNumber); // will throw if non-existant - if (output->GetStreamFormat().NumberChannelStreams() != ioData.mNumberBuffers) { - DebugMessageN4("%s:%d ioData.mNumberBuffers=%u, output->GetStreamFormat().NumberChannelStreams()=%u; kAudio_ParamError", - __FILE__, __LINE__, (unsigned)ioData.mNumberBuffers, (unsigned)output->GetStreamFormat().NumberChannelStreams()); - goto ParamErr; - } - - unsigned expectedBufferByteSize = inFramesToProcess * output->GetStreamFormat().mBytesPerFrame; - for (unsigned ibuf = 0; ibuf < ioData.mNumberBuffers; ++ibuf) { - AudioBuffer &buf = ioData.mBuffers[ibuf]; - if (buf.mData != NULL) { - // only care about the size if the buffer is non-null - if (buf.mDataByteSize < expectedBufferByteSize) { - // if the buffer is too small, we cannot render safely. kAudio_ParamError. - DebugMessageN7("%s:%d %u frames, %u bytes/frame, expected %u-byte buffer; ioData.mBuffers[%u].mDataByteSize=%u; kAudio_ParamError", - __FILE__, __LINE__, (unsigned)inFramesToProcess, (unsigned)output->GetStreamFormat().mBytesPerFrame, expectedBufferByteSize, ibuf, (unsigned)buf.mDataByteSize); - goto ParamErr; - } - // Some clients incorrectly pass bigger buffers than expectedBufferByteSize. - // We will generally set the buffer size at the end of rendering, before we return. - // However we should ensure that no one, DURING rendering, READS a - // potentially incorrect size. This can lead to doing too much work, or - // reading past the end of an input buffer into unmapped memory. - buf.mDataByteSize = expectedBufferByteSize; - } - } - - if (WantsRenderThreadID()) - { - #if TARGET_OS_MAC - mRenderThreadID = pthread_self(); - #elif TARGET_OS_WIN32 - mRenderThreadID = GetCurrentThreadId(); - #endif - } - - AudioUnitRenderActionFlags flags; - if (mRenderCallbacksTouched) { - mRenderCallbacks.update(); - flags = ioActionFlags | kAudioUnitRenderAction_PreRender; - for (rcit = mRenderCallbacks.begin(); rcit != mRenderCallbacks.end(); ++rcit) { - RenderCallback &rc = *rcit; - AUTRACE(kCATrace_AUBaseRenderCallbackStart, mComponentInstance, (intptr_t)this, (intptr_t)rc.mRenderNotify, 1, 0); - (*(AURenderCallback)rc.mRenderNotify)(rc.mRenderNotifyRefCon, - &flags, - &inTimeStamp, inBusNumber, inFramesToProcess, &ioData); - AUTRACE(kCATrace_AUBaseRenderCallbackEnd, mComponentInstance, (intptr_t)this, (intptr_t)rc.mRenderNotify, 1, 0); - } - } - - theError = DoRenderBus(ioActionFlags, inTimeStamp, inBusNumber, output, inFramesToProcess, ioData); - - if (mRenderCallbacksTouched) { - flags = ioActionFlags | kAudioUnitRenderAction_PostRender; - - if (SetRenderError (theError)) { - flags |= kAudioUnitRenderAction_PostRenderError; - } - - for (rcit = mRenderCallbacks.begin(); rcit != mRenderCallbacks.end(); ++rcit) { - RenderCallback &rc = *rcit; - AUTRACE(kCATrace_AUBaseRenderCallbackStart, mComponentInstance, (intptr_t)this, (intptr_t)rc.mRenderNotify, 2, 0); - (*(AURenderCallback)rc.mRenderNotify)(rc.mRenderNotifyRefCon, - &flags, - &inTimeStamp, inBusNumber, inFramesToProcess, &ioData); - AUTRACE(kCATrace_AUBaseRenderCallbackEnd, mComponentInstance, (intptr_t)this, (intptr_t)rc.mRenderNotify, 2, 0); - } - } - - // The vector's being emptied - // because these events should only apply to this Render cycle, so anything - // left over is from a preceding cycle and should be dumped. New scheduled - // parameters must be scheduled from the next pre-render callback. - if (!mParamList.empty()) - mParamList.clear(); - - } - catch (OSStatus err) { - theError = err; - goto errexit; - } - catch (...) { - theError = -1; - goto errexit; - } -done: - RESTORE_DENORMALS - AUTRACE(kCATrace_AUBaseRenderEnd, mComponentInstance, (intptr_t)this, theError, ioActionFlags, CATrace::ablData(ioData)); - - return theError; - -Uninitialized: theError = kAudioUnitErr_Uninitialized; goto errexit; -ParamErr: theError = kAudio_ParamError; goto errexit; -TooManyFrames: theError = kAudioUnitErr_TooManyFramesToProcess; goto errexit; -errexit: - DebugMessageN2 (" from %s, render err: %d", GetLoggingString(), (int)theError); - SetRenderError(theError); - goto done; -} - -//_____________________________________________________________________________ -// -OSStatus AUBase::DoProcess ( AudioUnitRenderActionFlags & ioActionFlags, - const AudioTimeStamp & inTimeStamp, - UInt32 inFramesToProcess, - AudioBufferList & ioData) -{ - OSStatus theError; - AUTRACE(kCATrace_AUBaseRenderStart, mComponentInstance, (intptr_t)this, -1, inFramesToProcess, 0); - DISABLE_DENORMALS - - try { - - if (!(ioActionFlags & (1 << 9)/*kAudioUnitRenderAction_DoNotCheckRenderArgs*/)) { - ca_require(IsInitialized(), Uninitialized); - ca_require(inFramesToProcess <= mMaxFramesPerSlice, TooManyFrames); - ca_require(!UsesFixedBlockSize() || inFramesToProcess == GetMaxFramesPerSlice(), ParamErr); - - AUInputElement *input = GetInput(0); // will throw if non-existant - if (input->GetStreamFormat().NumberChannelStreams() != ioData.mNumberBuffers) { - DebugMessageN4("%s:%d ioData.mNumberBuffers=%u, input->GetStreamFormat().NumberChannelStreams()=%u; kAudio_ParamError", - __FILE__, __LINE__, (unsigned)ioData.mNumberBuffers, (unsigned)input->GetStreamFormat().NumberChannelStreams()); - goto ParamErr; - } - - unsigned expectedBufferByteSize = inFramesToProcess * input->GetStreamFormat().mBytesPerFrame; - for (unsigned ibuf = 0; ibuf < ioData.mNumberBuffers; ++ibuf) { - AudioBuffer &buf = ioData.mBuffers[ibuf]; - if (buf.mData != NULL) { - // only care about the size if the buffer is non-null - if (buf.mDataByteSize < expectedBufferByteSize) { - // if the buffer is too small, we cannot render safely. kAudio_ParamError. - DebugMessageN7("%s:%d %u frames, %u bytes/frame, expected %u-byte buffer; ioData.mBuffers[%u].mDataByteSize=%u; kAudio_ParamError", - __FILE__, __LINE__, (unsigned)inFramesToProcess, (unsigned)input->GetStreamFormat().mBytesPerFrame, expectedBufferByteSize, ibuf, (unsigned)buf.mDataByteSize); - goto ParamErr; - } - // Some clients incorrectly pass bigger buffers than expectedBufferByteSize. - // We will generally set the buffer size at the end of rendering, before we return. - // However we should ensure that no one, DURING rendering, READS a - // potentially incorrect size. This can lead to doing too much work, or - // reading past the end of an input buffer into unmapped memory. - buf.mDataByteSize = expectedBufferByteSize; - } - } - } - - if (WantsRenderThreadID()) - { - #if TARGET_OS_MAC - mRenderThreadID = pthread_self(); - #elif TARGET_OS_WIN32 - mRenderThreadID = GetCurrentThreadId(); - #endif - } - - if (NeedsToRender (inTimeStamp)) { - theError = ProcessBufferLists (ioActionFlags, ioData, ioData, inFramesToProcess); - } else - theError = noErr; - - } - catch (OSStatus err) { - theError = err; - goto errexit; - } - catch (...) { - theError = -1; - goto errexit; - } -done: - RESTORE_DENORMALS - AUTRACE(kCATrace_AUBaseRenderEnd, mComponentInstance, (intptr_t)this, theError, ioActionFlags, CATrace::ablData(ioData)); - - return theError; - -Uninitialized: theError = kAudioUnitErr_Uninitialized; goto errexit; -ParamErr: theError = kAudio_ParamError; goto errexit; -TooManyFrames: theError = kAudioUnitErr_TooManyFramesToProcess; goto errexit; -errexit: - DebugMessageN2 (" from %s, process err: %d", GetLoggingString(), (int)theError); - SetRenderError(theError); - goto done; -} - -OSStatus AUBase::DoProcessMultiple ( AudioUnitRenderActionFlags & ioActionFlags, - const AudioTimeStamp & inTimeStamp, - UInt32 inFramesToProcess, - UInt32 inNumberInputBufferLists, - const AudioBufferList ** inInputBufferLists, - UInt32 inNumberOutputBufferLists, - AudioBufferList ** ioOutputBufferLists) -{ - OSStatus theError; - DISABLE_DENORMALS - - try { - - if (!(ioActionFlags & (1 << 9)/*kAudioUnitRenderAction_DoNotCheckRenderArgs*/)) { - ca_require(IsInitialized(), Uninitialized); - ca_require(inFramesToProcess <= mMaxFramesPerSlice, TooManyFrames); - ca_require (!UsesFixedBlockSize() || inFramesToProcess == GetMaxFramesPerSlice(), ParamErr); - - for (unsigned ibl = 0; ibl < inNumberInputBufferLists; ++ibl) { - if (inInputBufferLists[ibl] != NULL) { - AUInputElement *input = GetInput(ibl); // will throw if non-existant - unsigned expectedBufferByteSize = inFramesToProcess * input->GetStreamFormat().mBytesPerFrame; - - if (input->GetStreamFormat().NumberChannelStreams() != inInputBufferLists[ibl]->mNumberBuffers) { - DebugMessageN5("%s:%d inInputBufferLists[%u]->mNumberBuffers=%u, input->GetStreamFormat().NumberChannelStreams()=%u; kAudio_ParamError", - __FILE__, __LINE__, ibl, (unsigned)inInputBufferLists[ibl]->mNumberBuffers, (unsigned)input->GetStreamFormat().NumberChannelStreams()); - goto ParamErr; - } - - for (unsigned ibuf = 0; ibuf < inInputBufferLists[ibl]->mNumberBuffers; ++ibuf) { - const AudioBuffer &buf = inInputBufferLists[ibl]->mBuffers[ibuf]; - if (buf.mData != NULL) { - if (buf.mDataByteSize < expectedBufferByteSize) { - // the buffer is too small - DebugMessageN8("%s:%d %u frames, %u bytes/frame, expected %u-byte buffer; inInputBufferLists[%u].mBuffers[%u].mDataByteSize=%u; kAudio_ParamError", - __FILE__, __LINE__, (unsigned)inFramesToProcess, (unsigned)input->GetStreamFormat().mBytesPerFrame, expectedBufferByteSize, ibl, ibuf, (unsigned)buf.mDataByteSize); - goto ParamErr; - } - } else { - // the buffer must exist - goto ParamErr; - } - } - } else { - // skip NULL input audio buffer list - } - } - - for (unsigned obl = 0; obl < inNumberOutputBufferLists; ++obl) { - if (ioOutputBufferLists[obl] != NULL) { - AUOutputElement *output = GetOutput(obl); // will throw if non-existant - unsigned expectedBufferByteSize = inFramesToProcess * output->GetStreamFormat().mBytesPerFrame; - - if (output->GetStreamFormat().NumberChannelStreams() != ioOutputBufferLists[obl]->mNumberBuffers) { - DebugMessageN5("%s:%d ioOutputBufferLists[%u]->mNumberBuffers=%u, output->GetStreamFormat().NumberChannelStreams()=%u; kAudio_ParamError", - __FILE__, __LINE__, obl, (unsigned)ioOutputBufferLists[obl]->mNumberBuffers, (unsigned)output->GetStreamFormat().NumberChannelStreams()); - goto ParamErr; - } - - for (unsigned obuf = 0; obuf < ioOutputBufferLists[obl]->mNumberBuffers; ++obuf) { - AudioBuffer &buf = ioOutputBufferLists[obl]->mBuffers[obuf]; - if (buf.mData != NULL) { - // only care about the size if the buffer is non-null - if (buf.mDataByteSize < expectedBufferByteSize) { - // if the buffer is too small, we cannot render safely. kAudio_ParamError. - DebugMessageN8("%s:%d %u frames, %u bytes/frame, expected %u-byte buffer; ioOutputBufferLists[%u]->mBuffers[%u].mDataByteSize=%u; kAudio_ParamError", - __FILE__, __LINE__, (unsigned)inFramesToProcess, (unsigned)output->GetStreamFormat().mBytesPerFrame, expectedBufferByteSize, obl, obuf, (unsigned)buf.mDataByteSize); - goto ParamErr; - } - // Some clients incorrectly pass bigger buffers than expectedBufferByteSize. - // We will generally set the buffer size at the end of rendering, before we return. - // However we should ensure that no one, DURING rendering, READS a - // potentially incorrect size. This can lead to doing too much work, or - // reading past the end of an input buffer into unmapped memory. - buf.mDataByteSize = expectedBufferByteSize; - } - } - } else { - // skip NULL output audio buffer list - } - } - } - - if (WantsRenderThreadID()) - { -#if TARGET_OS_MAC - mRenderThreadID = pthread_self(); -#elif TARGET_OS_WIN32 - mRenderThreadID = GetCurrentThreadId(); -#endif - } - - if (NeedsToRender (inTimeStamp)) { - theError = ProcessMultipleBufferLists (ioActionFlags, inFramesToProcess, inNumberInputBufferLists, inInputBufferLists, inNumberOutputBufferLists, ioOutputBufferLists); - } else - theError = noErr; - } - catch (OSStatus err) { - theError = err; - goto errexit; - } - catch (...) { - theError = -1; - goto errexit; - } -done: - RESTORE_DENORMALS - - return theError; - -Uninitialized: theError = kAudioUnitErr_Uninitialized; goto errexit; -ParamErr: theError = kAudio_ParamError; goto errexit; -TooManyFrames: theError = kAudioUnitErr_TooManyFramesToProcess; goto errexit; -errexit: - DebugMessageN2 (" from %s, processmultiple err: %d", GetLoggingString(), (int)theError); - SetRenderError(theError); - goto done; -} - -//_____________________________________________________________________________ -// -OSStatus AUBase::SetInputCallback( UInt32 inPropertyID, - AudioUnitElement inElement, - AURenderCallback inProc, - void * inRefCon) -{ - AUInputElement *input = GetInput(inElement); // may throw - - input->SetInputCallback(inProc, inRefCon); - PropertyChanged(inPropertyID, kAudioUnitScope_Input, inElement); - - return noErr; -} - -//_____________________________________________________________________________ -// -OSStatus AUBase::SetConnection( const AudioUnitConnection & inConnection) -{ - - OSStatus err; - AUInputElement *input = GetInput(inConnection.destInputNumber); // may throw - - if (inConnection.sourceAudioUnit) { - // connecting, not disconnecting - CAStreamBasicDescription sourceDesc; - UInt32 size = sizeof(CAStreamBasicDescription); - ca_require_noerr(err = AudioUnitGetProperty( - inConnection.sourceAudioUnit, - kAudioUnitProperty_StreamFormat, - kAudioUnitScope_Output, - inConnection.sourceOutputNumber, - &sourceDesc, - &size), errexit); - ca_require_noerr(err = DispatchSetProperty (kAudioUnitProperty_StreamFormat, - kAudioUnitScope_Input, inConnection.destInputNumber, - &sourceDesc, sizeof(CAStreamBasicDescription)), errexit); - } - input->SetConnection(inConnection); - - PropertyChanged(kAudioUnitProperty_MakeConnection, kAudioUnitScope_Input, inConnection.destInputNumber); - return noErr; - -errexit: - return err; -} - -//_____________________________________________________________________________ -// -UInt32 AUBase::SupportedNumChannels ( const AUChannelInfo** outInfo) -{ - return 0; -} - -//_____________________________________________________________________________ -// -bool AUBase::ValidFormat( AudioUnitScope inScope, - AudioUnitElement inElement, - const CAStreamBasicDescription & inNewFormat) -{ - return FormatIsCanonical(inNewFormat); -} - -//_____________________________________________________________________________ -// -bool AUBase::IsStreamFormatWritable( AudioUnitScope scope, - AudioUnitElement element) -{ - switch (scope) { - case kAudioUnitScope_Input: - { - AUInputElement *input = GetInput(element); - if (input->HasConnection()) return false; // can't write format when input comes from connection - } - // ... fall ... - case kAudioUnitScope_Output: - return StreamFormatWritable(scope, element); - -//#warning "aliasing of global scope format should be pushed to subclasses" - case kAudioUnitScope_Global: - return StreamFormatWritable(kAudioUnitScope_Output, 0); - } - return false; -} - -//_____________________________________________________________________________ -// -const CAStreamBasicDescription & - AUBase::GetStreamFormat( AudioUnitScope inScope, - AudioUnitElement inElement) -{ -//#warning "aliasing of global scope format should be pushed to subclasses" - AUIOElement *element; - - switch (inScope) { - case kAudioUnitScope_Input: - element = Inputs().GetIOElement(inElement); - break; - case kAudioUnitScope_Output: - element = Outputs().GetIOElement(inElement); - break; - case kAudioUnitScope_Global: // global stream description is an alias for that of output 0 - element = Outputs().GetIOElement(0); - break; - default: - COMPONENT_THROW(kAudioUnitErr_InvalidScope); - } - return element->GetStreamFormat(); -} - -OSStatus AUBase::SetBusCount( AudioUnitScope inScope, - UInt32 inCount) -{ - if (IsInitialized()) - return kAudioUnitErr_Initialized; - - GetScope(inScope).SetNumberOfElements(inCount); - return noErr; -} - -//_____________________________________________________________________________ -// -OSStatus AUBase::ChangeStreamFormat( AudioUnitScope inScope, - AudioUnitElement inElement, - const CAStreamBasicDescription & inPrevFormat, - const CAStreamBasicDescription & inNewFormat) -{ -//#warning "aliasing of global scope format should be pushed to subclasses" - AUIOElement *element; - - switch (inScope) { - case kAudioUnitScope_Input: - element = Inputs().GetIOElement(inElement); - break; - case kAudioUnitScope_Output: - element = Outputs().GetIOElement(inElement); - break; - case kAudioUnitScope_Global: - element = Outputs().GetIOElement(0); - break; - default: - COMPONENT_THROW(kAudioUnitErr_InvalidScope); - } - element->SetStreamFormat(inNewFormat); - PropertyChanged(kAudioUnitProperty_StreamFormat, inScope, inElement); - return noErr; -} - -UInt32 AUBase::GetChannelLayoutTags( AudioUnitScope inScope, - AudioUnitElement inElement, - AudioChannelLayoutTag * outLayoutTags) -{ - return GetIOElement(inScope, inElement)->GetChannelLayoutTags(outLayoutTags); -} - -UInt32 AUBase::GetAudioChannelLayout( AudioUnitScope scope, - AudioUnitElement element, - AudioChannelLayout * outLayoutPtr, - Boolean & outWritable) -{ - AUIOElement * el = GetIOElement(scope, element); - return el->GetAudioChannelLayout(outLayoutPtr, outWritable); -} - -OSStatus AUBase::RemoveAudioChannelLayout( AudioUnitScope inScope, - AudioUnitElement inElement) -{ - OSStatus result = noErr; - AUIOElement * el = GetIOElement(inScope, inElement); - Boolean writable; - if (el->GetAudioChannelLayout(NULL, writable)) { - result = el->RemoveAudioChannelLayout(); - } - return result; -} - -OSStatus AUBase::SetAudioChannelLayout( AudioUnitScope inScope, - AudioUnitElement inElement, - const AudioChannelLayout * inLayout) -{ - AUIOElement* ioEl = GetIOElement (inScope, inElement); - - // the num channels of the layout HAS TO MATCH the current channels of the Element's stream format - UInt32 currentChannels = ioEl->GetStreamFormat().NumberChannels(); - UInt32 numChannelsInLayout = CAAudioChannelLayout::NumberChannels(*inLayout); - if (currentChannels != numChannelsInLayout) - return kAudioUnitErr_InvalidPropertyValue; - - UInt32 numLayouts = GetChannelLayoutTags (inScope, inElement, NULL); - if (numLayouts == 0) - return kAudioUnitErr_InvalidProperty; - AudioChannelLayoutTag *tags = (AudioChannelLayoutTag *)CA_malloc (numLayouts * sizeof (AudioChannelLayoutTag)); - GetChannelLayoutTags (inScope, inElement, tags); - bool foundTag = false; - for (unsigned int i = 0; i < numLayouts; ++i) { - if (tags[i] == inLayout->mChannelLayoutTag || tags[i] == kAudioChannelLayoutTag_UseChannelDescriptions) { - foundTag = true; - break; - } - } - free(tags); - - if (foundTag == false) - return kAudioUnitErr_InvalidPropertyValue; - - return ioEl->SetAudioChannelLayout(*inLayout); -} - -static void AddNumToDictionary (CFMutableDictionaryRef dict, CFStringRef key, SInt32 value) -{ - CFNumberRef num = CFNumberCreate (NULL, kCFNumberSInt32Type, &value); - CFDictionarySetValue (dict, key, num); - CFRelease (num); -} - -#define kCurrentSavedStateVersion 0 - -OSStatus AUBase::SaveState( CFPropertyListRef * outData) -{ - AudioComponentDescription desc = GetComponentDescription(); - - CFMutableDictionaryRef dict = CFDictionaryCreateMutable (NULL, 0, - &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); - -// first step -> save the version to the data ref - SInt32 value = kCurrentSavedStateVersion; - AddNumToDictionary (dict, kVersionString, value); - -// second step -> save the component type, subtype, manu to the data ref - value = desc.componentType; - AddNumToDictionary (dict, kTypeString, value); - - value = desc.componentSubType; - AddNumToDictionary (dict, kSubtypeString, value); - - value = desc.componentManufacturer; - AddNumToDictionary (dict, kManufacturerString, value); - -// fourth step -> save the state of all parameters on all scopes and elements - CFMutableDataRef data = CFDataCreateMutable(NULL, 0); - for (AudioUnitScope iscope = 0; iscope < 3; ++iscope) { - AUScope &scope = GetScope(iscope); - scope.SaveState (data); - } - - SaveExtendedScopes(data); - -// save all this in the data section of the dictionary - CFDictionarySetValue(dict, kDataString, data); - CFRelease (data); - -//OK - now we're going to do some properties -//save the preset name... - CFDictionarySetValue (dict, kNameString, mCurrentPreset.presetName); - -// Does the unit support the RenderQuality property - if so, save it... - value = 0; - OSStatus result = DispatchGetProperty (kAudioUnitProperty_RenderQuality, - kAudioUnitScope_Global, - 0, - &value); - - if (result == noErr) { - AddNumToDictionary (dict, kRenderQualityString, value); - } - -// Does the unit support the CPULoad Quality property - if so, save it... - Float32 cpuLoad; - result = DispatchGetProperty (6/*kAudioUnitProperty_CPULoad*/, - kAudioUnitScope_Global, - 0, - &cpuLoad); - - if (result == noErr) { - CFNumberRef num = CFNumberCreate (NULL, kCFNumberFloatType, &cpuLoad); - CFDictionarySetValue (dict, kCPULoadString, num); - CFRelease (num); - } - -// Do we have any element names for any of our scopes? - // first check to see if we have any names... - bool foundName = false; - for (AudioUnitScope i = 0; i < kNumScopes; ++i) { - foundName = GetScope (i).HasElementWithName(); - if (foundName) - break; - } - // OK - we found a name away we go... - if (foundName) { - CFMutableDictionaryRef nameDict = CFDictionaryCreateMutable (NULL, 0, - &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); - for (AudioUnitScope i = 0; i < kNumScopes; ++i) { - GetScope (i).AddElementNamesToDict (nameDict); - } - - CFDictionarySetValue (dict, kElementNameString, nameDict); - CFRelease (nameDict); - } - -// we're done!!! - *outData = dict; - - return noErr; -} - -//_____________________________________________________________________________ -// -OSStatus AUBase::RestoreState( CFPropertyListRef plist) -{ - if (CFGetTypeID(plist) != CFDictionaryGetTypeID()) return kAudioUnitErr_InvalidPropertyValue; - - AudioComponentDescription desc = GetComponentDescription(); - - CFDictionaryRef dict = static_cast(plist); - -// zeroeth step - make sure the Part key is NOT present, as this method is used -// to restore the GLOBAL state of the dictionary - if (CFDictionaryContainsKey (dict, kPartString)) - return kAudioUnitErr_InvalidPropertyValue; - -// first step -> check the saved version in the data ref -// at this point we're only dealing with version==0 - CFNumberRef cfnum = reinterpret_cast(CFDictionaryGetValue (dict, kVersionString)); - if (cfnum == NULL) return kAudioUnitErr_InvalidPropertyValue; - SInt32 value; - CFNumberGetValue (cfnum, kCFNumberSInt32Type, &value); - if (value != kCurrentSavedStateVersion) return kAudioUnitErr_InvalidPropertyValue; - -// second step -> check that this data belongs to this kind of audio unit -// by checking the component subtype and manuID -// We're not checking the type, since there may be different versions (effect, format-converter, offline) -// of essentially the same AU - cfnum = reinterpret_cast(CFDictionaryGetValue (dict, kSubtypeString)); - if (cfnum == NULL) return kAudioUnitErr_InvalidPropertyValue; - CFNumberGetValue (cfnum, kCFNumberSInt32Type, &value); - if (UInt32(value) != desc.componentSubType) return kAudioUnitErr_InvalidPropertyValue; - - cfnum = reinterpret_cast(CFDictionaryGetValue (dict, kManufacturerString)); - if (cfnum == NULL) return kAudioUnitErr_InvalidPropertyValue; - CFNumberGetValue (cfnum, kCFNumberSInt32Type, &value); - if (UInt32(value) != desc.componentManufacturer) return kAudioUnitErr_InvalidPropertyValue; - -// fourth step -> restore the state of all of the parameters for each scope and element - CFDataRef data = reinterpret_cast(CFDictionaryGetValue (dict, kDataString)); - if (data != NULL) - { - const UInt8 *p, *pend; - - p = CFDataGetBytePtr(data); - pend = p + CFDataGetLength(data); - - // we have a zero length data, which may just mean there were no parameters to save! - // if (p >= pend) return noErr; - - while (p < pend) { - UInt32 scopeIdx = CFSwapInt32BigToHost(*(UInt32 *)p); - p += sizeof(UInt32); - - AUScope &scope = GetScope(scopeIdx); - p = scope.RestoreState(p); - } - } - -//OK - now we're going to do some properties -//restore the preset name... - CFStringRef name = reinterpret_cast(CFDictionaryGetValue (dict, kNameString)); - if (mCurrentPreset.presetName) CFRelease (mCurrentPreset.presetName); - if (name) - { - mCurrentPreset.presetName = name; - mCurrentPreset.presetNumber = -1; - } - else { // no name entry make the default one - mCurrentPreset.presetName = kUntitledString; - mCurrentPreset.presetNumber = -1; - } - - CFRetain (mCurrentPreset.presetName); -#if !CA_USE_AUDIO_PLUGIN_ONLY -#ifndef __LP64__ - PropertyChanged(kAudioUnitProperty_CurrentPreset, kAudioUnitScope_Global, 0); -#endif -#endif - PropertyChanged(kAudioUnitProperty_PresentPreset, kAudioUnitScope_Global, 0); - -// Does the dict contain render quality information? - if (CFDictionaryGetValueIfPresent (dict, kRenderQualityString, reinterpret_cast(&cfnum))) - { - CFNumberGetValue (cfnum, kCFNumberSInt32Type, &value); - DispatchSetProperty (kAudioUnitProperty_RenderQuality, - kAudioUnitScope_Global, - 0, - &value, - sizeof(value)); - } - -// Does the unit support the CPULoad Quality property - if so, save it... - if (CFDictionaryGetValueIfPresent (dict, kCPULoadString, reinterpret_cast(&cfnum))) - { - Float32 floatValue; - CFNumberGetValue (cfnum, kCFNumberFloatType, &floatValue); - DispatchSetProperty (6/*kAudioUnitProperty_CPULoad*/, - kAudioUnitScope_Global, - 0, - &floatValue, - sizeof(floatValue)); - } - -// Do we have any element names for any of our scopes? - CFDictionaryRef nameDict; - if (CFDictionaryGetValueIfPresent (dict, kElementNameString, reinterpret_cast(&nameDict))) - { - char string[64]; - for (int i = 0; i < kNumScopes; ++i) - { - snprintf (string, sizeof(string), "%d", i); - CFStringRef key = CFStringCreateWithCString (NULL, string, kCFStringEncodingASCII); - CFDictionaryRef elementDict; - if (CFDictionaryGetValueIfPresent (nameDict, key, reinterpret_cast(&elementDict))) - { - bool didAddElements = GetScope (i).RestoreElementNames (elementDict); - if (didAddElements) - PropertyChanged (kAudioUnitProperty_ElementCount, i, 0); - } - CFRelease (key); - } - } - - return noErr; -} - -OSStatus AUBase::GetPresets ( CFArrayRef * outData) const -{ - return kAudioUnitErr_InvalidProperty; -} - -OSStatus AUBase::NewFactoryPresetSet (const AUPreset & inNewFactoryPreset) -{ - return kAudioUnitErr_InvalidProperty; -} - -OSStatus AUBase::NewCustomPresetSet (const AUPreset & inNewCustomPreset) -{ - CFRelease (mCurrentPreset.presetName); - mCurrentPreset = inNewCustomPreset; - CFRetain (mCurrentPreset.presetName); - return noErr; -} - - // set the default preset for the unit -> the number of the preset MUST be >= 0 - // and the name should be valid, or the preset WON'T take -bool AUBase::SetAFactoryPresetAsCurrent (const AUPreset & inPreset) -{ - if (inPreset.presetNumber < 0 || inPreset.presetName == NULL) return false; - CFRelease (mCurrentPreset.presetName); - mCurrentPreset = inPreset; - CFRetain (mCurrentPreset.presetName); - return true; -} - -#if !CA_USE_AUDIO_PLUGIN_ONLY -int AUBase::GetNumCustomUIComponents () -{ - return 0; -} - -void AUBase::GetUIComponentDescs (ComponentDescription* inDescArray) {} -#endif - -bool AUBase::HasIcon () -{ -#if !CA_NO_AU_UI_FEATURES - CFURLRef url = CopyIconLocation(); - if (url) { - CFRelease (url); - return true; - } -#endif - return false; -} - -CFURLRef AUBase::CopyIconLocation () -{ - return NULL; -} - -//_____________________________________________________________________________ -// -OSStatus AUBase::GetParameterList( AudioUnitScope inScope, - AudioUnitParameterID * outParameterList, - UInt32 & outNumParameters) -{ - AUScope &scope = GetScope(inScope); - AUElement *elementWithMostParameters = NULL; - UInt32 maxNumParams = 0; - - int nElems = scope.GetNumberOfElements(); - for (int ielem = 0; ielem < nElems; ++ielem) { - AUElement *element = scope.GetElement(ielem); - UInt32 nParams = element->GetNumberOfParameters(); - if (nParams > maxNumParams) { - maxNumParams = nParams; - elementWithMostParameters = element; - } - } - - if (outParameterList != NULL && elementWithMostParameters != NULL) - elementWithMostParameters->GetParameterList(outParameterList); - - outNumParameters = maxNumParams; - return noErr; -} - -//_____________________________________________________________________________ -// -OSStatus AUBase::GetParameterInfo( AudioUnitScope inScope, - AudioUnitParameterID inParameterID, - AudioUnitParameterInfo &outParameterInfo ) -{ - return kAudioUnitErr_InvalidParameter; -} - -//_____________________________________________________________________________ -// -OSStatus AUBase::GetParameterValueStrings(AudioUnitScope inScope, - AudioUnitParameterID inParameterID, - CFArrayRef * outStrings) -{ - return kAudioUnitErr_InvalidProperty; -} - -//_____________________________________________________________________________ -// -OSStatus AUBase::GetParameterHistoryInfo( AudioUnitScope inScope, - AudioUnitParameterID inParameterID, - Float32 & outUpdatesPerSecond, - Float32 & outHistoryDurationInSeconds) -{ - return kAudioUnitErr_InvalidProperty; -} - - -//_____________________________________________________________________________ -// -OSStatus AUBase::CopyClumpName( AudioUnitScope inScope, - UInt32 inClumpID, - UInt32 inDesiredNameLength, - CFStringRef * outClumpName) -{ - return kAudioUnitErr_InvalidProperty; -} - -//_____________________________________________________________________________ -// -void AUBase::SetNumberOfElements( AudioUnitScope inScope, - UInt32 numElements) -{ - if (inScope == kAudioUnitScope_Global && numElements != 1) - COMPONENT_THROW(kAudioUnitErr_InvalidScope); - - GetScope(inScope).SetNumberOfElements(numElements); -} - -//_____________________________________________________________________________ -// -AUElement * AUBase::CreateElement( AudioUnitScope scope, - AudioUnitElement element) -{ - switch (scope) { - case kAudioUnitScope_Global: - return new AUElement(this); - case kAudioUnitScope_Input: - return new AUInputElement(this); - case kAudioUnitScope_Output: - return new AUOutputElement(this); -#if !CA_BASIC_AU_FEATURES - case kAudioUnitScope_Group: - return new AUElement(this); - case kAudioUnitScope_Part: - return new AUElement(this); -#endif - } - COMPONENT_THROW(kAudioUnitErr_InvalidScope); - - return NULL; // get rid of compiler warning -} - -//_____________________________________________________________________________ -// -bool AUBase::FormatIsCanonical( const CAStreamBasicDescription &f) -{ - return (f.mFormatID == kAudioFormatLinearPCM - && f.mFramesPerPacket == 1 - && f.mBytesPerPacket == f.mBytesPerFrame -// && f.mChannelsPerFrame >= 0 -- this is always true since it's unsigned - // so far, it's a valid PCM format -#if CA_PREFER_FIXED_POINT - && (f.mFormatFlags & kLinearPCMFormatFlagIsFloat) == 0 - && (((f.mFormatFlags & kLinearPCMFormatFlagsSampleFractionMask) >> kLinearPCMFormatFlagsSampleFractionShift) == kAudioUnitSampleFractionBits) -#else - && (f.mFormatFlags & kLinearPCMFormatFlagIsFloat) != 0 -#endif - && ((f.mChannelsPerFrame == 1) || ((f.mFormatFlags & kAudioFormatFlagIsNonInterleaved) == 0) == (mAudioUnitAPIVersion == 1)) -#if TARGET_RT_BIG_ENDIAN - && (f.mFormatFlags & kLinearPCMFormatFlagIsBigEndian) != 0 -#else - && (f.mFormatFlags & kLinearPCMFormatFlagIsBigEndian) == 0 -#endif - && f.mBitsPerChannel == 8 * sizeof(AudioUnitSampleType) - && f.mBytesPerFrame == f.NumberInterleavedChannels() * sizeof(AudioUnitSampleType) - ); -} - -//_____________________________________________________________________________ -// -void AUBase::MakeCanonicalFormat( CAStreamBasicDescription & f, - int nChannels) -{ - f.SetAUCanonical(nChannels, mAudioUnitAPIVersion < 2); // interleaved for v1, non for v2 - f.mSampleRate = 0.0; -} - -const Float64 AUBase::kNoLastRenderedSampleTime = -1.; - -#include "AUBaseHelper.h" - -char* AUBase::GetLoggingString () const -{ - if (mLogString) return mLogString; - - AudioComponentDescription desc = GetComponentDescription(); - - const size_t logStringSize = 256; - const_cast(this)->mLogString = new char[logStringSize]; - char str[24]; - char str1[24]; - char str2[24]; - snprintf (const_cast(this)->mLogString, logStringSize, "AU (%p): %s %s %s", - GetComponentInstance(), - CAStringForOSType(desc.componentType, str, sizeof(str)), - CAStringForOSType(desc.componentSubType, str1, sizeof(str1)), - CAStringForOSType(desc.componentManufacturer, str2, sizeof(str2))); - - return mLogString; -} - diff --git a/src/CoreAudio/CoreAudioComponent/AUPublic/AUBase/AUBase.h b/src/CoreAudio/CoreAudioComponent/AUPublic/AUBase/AUBase.h deleted file mode 100644 index 0c78221cc..000000000 --- a/src/CoreAudio/CoreAudioComponent/AUPublic/AUBase/AUBase.h +++ /dev/null @@ -1,1048 +0,0 @@ -/* - File: AUBase.h - Abstract: Part of CoreAudio Utility Classes - Version: 1.1 - - Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple - Inc. ("Apple") in consideration of your agreement to the following - terms, and your use, installation, modification or redistribution of - this Apple software constitutes acceptance of these terms. If you do - not agree with these terms, please do not use, install, modify or - redistribute this Apple software. - - In consideration of your agreement to abide by the following terms, and - subject to these terms, Apple grants you a personal, non-exclusive - license, under Apple's copyrights in this original Apple software (the - "Apple Software"), to use, reproduce, modify and redistribute the Apple - Software, with or without modifications, in source and/or binary forms; - provided that if you redistribute the Apple Software in its entirety and - without modifications, you must retain this notice and the following - text and disclaimers in all such redistributions of the Apple Software. - Neither the name, trademarks, service marks or logos of Apple Inc. may - be used to endorse or promote products derived from the Apple Software - without specific prior written permission from Apple. Except as - expressly stated in this notice, no other rights or licenses, express or - implied, are granted by Apple herein, including but not limited to any - patent rights that may be infringed by your derivative works or by other - works in which the Apple Software may be incorporated. - - The Apple Software is provided by Apple on an "AS IS" basis. APPLE - MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION - THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS - FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND - OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS. - - IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL - OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, - MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED - AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), - STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE - POSSIBILITY OF SUCH DAMAGE. - - Copyright (C) 2014 Apple Inc. All Rights Reserved. - -*/ -#ifndef __AUBase_h__ -#define __AUBase_h__ - -#include - -#if TARGET_OS_MAC - #include -#elif TARGET_OS_WIN32 - #include -#else - #error Unsupported Operating System -#endif - -#include - -#include "AUScopeElement.h" -#include "AUInputElement.h" -#include "AUOutputElement.h" -#include "AUBuffer.h" -#include "CAMath.h" -#include "CAThreadSafeList.h" -#include "CAVectorUnit.h" -#include "CAMutex.h" -#if !defined(__COREAUDIO_USE_FLAT_INCLUDES__) - #include - #if !CA_BASIC_AU_FEATURES - #include - #endif -#else - #include "AudioUnit.h" - #if !CA_BASIC_AU_FEATURES - #include "MusicDevice.h" - #endif -#endif - -#ifndef AUTRACE - #define AUTRACE(code, obj, a, b, c, d) -#endif - -#include "AUPlugInDispatch.h" - - - -// ________________________________________________________________________ -// These are to be moved to the public AudioUnit headers - -#define kAUDefaultSampleRate 44100.0 -#if !TARGET_OS_WIN32 -#define kAUDefaultMaxFramesPerSlice 1156 -//this allows enough default frames for a 512 dest 44K and SRC from 96K -// add a padding of 4 frames for any altivec rounding -#else -#define kAUDefaultMaxFramesPerSlice 2048 -#endif - -// ________________________________________________________________________ - -/*! @class AUBase */ -class AUBase : public ComponentBase { -public: - - /*! @ctor AUBase */ - AUBase( AudioComponentInstance inInstance, - UInt32 numInputElements, - UInt32 numOutputElements, - UInt32 numGroupElements = 0); - /*! @dtor AUBase */ - virtual ~AUBase(); - - /*! @method PostConstructor */ - virtual void PostConstructor() { CreateElements(); } - - /*! @method PreDestructor */ - virtual void PreDestructor(); - - /*! @method CreateElements */ - void CreateElements(); - // Called immediately after construction, when virtual methods work. - // Or, a subclass may call this in order to have access to elements - // in its constructor. - - /*! @method CreateExtendedElements */ - virtual void CreateExtendedElements() {} - -#pragma mark - -#pragma mark AU dispatch - // ________________________________________________________________________ - // Virtual methods (mostly) directly corresponding to the entry points. Many of these - // have useful implementations here and will not need overriding. - - /*! @method DoInitialize */ - OSStatus DoInitialize(); - // this implements the entry point and makes sure that initialization - // is only attempted exactly once... - - /*! @method Initialize */ - virtual OSStatus Initialize(); - // ... so that overrides to this method can assume that they will only - // be called exactly once. - - /*! @method IsInitialized */ - bool IsInitialized() const { return mInitialized; } - /*! @method HasBegunInitializing */ - bool HasBegunInitializing() const { return mHasBegunInitializing; } - - /*! @method DoCleanup */ - void DoCleanup(); - // same pattern as with Initialize - - /*! @method Cleanup */ - virtual void Cleanup(); - - /*! @method Reset */ - virtual OSStatus Reset( AudioUnitScope inScope, - AudioUnitElement inElement); - - // Note about GetPropertyInfo, GetProperty, SetProperty: - // Certain properties are trapped out in these dispatch functions and handled with different virtual - // methods. (To discourage hacks and keep vtable size down, these are non-virtual) - - /*! @method DispatchGetPropertyInfo */ - OSStatus DispatchGetPropertyInfo(AudioUnitPropertyID inID, - AudioUnitScope inScope, - AudioUnitElement inElement, - UInt32 & outDataSize, - Boolean & outWritable); - - /*! @method DispatchGetProperty */ - OSStatus DispatchGetProperty( AudioUnitPropertyID inID, - AudioUnitScope inScope, - AudioUnitElement inElement, - void * outData); - - /*! @method DispatchSetProperty */ - OSStatus DispatchSetProperty( AudioUnitPropertyID inID, - AudioUnitScope inScope, - AudioUnitElement inElement, - const void * inData, - UInt32 inDataSize); - - OSStatus DispatchRemovePropertyValue( AudioUnitPropertyID inID, - AudioUnitScope inScope, - AudioUnitElement inElement); - - /*! @method GetPropertyInfo */ - virtual OSStatus GetPropertyInfo( AudioUnitPropertyID inID, - AudioUnitScope inScope, - AudioUnitElement inElement, - UInt32 & outDataSize, - Boolean & outWritable); - - /*! @method GetProperty */ - virtual OSStatus GetProperty( AudioUnitPropertyID inID, - AudioUnitScope inScope, - AudioUnitElement inElement, - void * outData); - - /*! @method SetProperty */ - virtual OSStatus SetProperty( AudioUnitPropertyID inID, - AudioUnitScope inScope, - AudioUnitElement inElement, - const void * inData, - UInt32 inDataSize); - - /*! @method ClearPropertyUsage */ - virtual OSStatus RemovePropertyValue ( AudioUnitPropertyID inID, - AudioUnitScope inScope, - AudioUnitElement inElement); - - /*! @method AddPropertyListener */ - virtual OSStatus AddPropertyListener( AudioUnitPropertyID inID, - AudioUnitPropertyListenerProc inProc, - void * inProcRefCon); - - /*! @method RemovePropertyListener */ - virtual OSStatus RemovePropertyListener( AudioUnitPropertyID inID, - AudioUnitPropertyListenerProc inProc, - void * inProcRefCon, - bool refConSpecified); - - /*! @method SetRenderNotification */ - virtual OSStatus SetRenderNotification( AURenderCallback inProc, - void * inRefCon); - - /*! @method RemoveRenderNotification */ - virtual OSStatus RemoveRenderNotification( - AURenderCallback inProc, - void * inRefCon); - - /*! @method GetParameter */ - virtual OSStatus GetParameter( AudioUnitParameterID inID, - AudioUnitScope inScope, - AudioUnitElement inElement, - AudioUnitParameterValue & outValue); - - /*! @method SetParameter */ - virtual OSStatus SetParameter( AudioUnitParameterID inID, - AudioUnitScope inScope, - AudioUnitElement inElement, - AudioUnitParameterValue inValue, - UInt32 inBufferOffsetInFrames); - - /*! @method CanScheduleParams */ - virtual bool CanScheduleParameters() const = 0; - - /*! @method ScheduleParameter */ - virtual OSStatus ScheduleParameter ( const AudioUnitParameterEvent *inParameterEvent, - UInt32 inNumEvents); - - - /*! @method DoRender */ - OSStatus DoRender( AudioUnitRenderActionFlags & ioActionFlags, - const AudioTimeStamp & inTimeStamp, - UInt32 inBusNumber, - UInt32 inNumberFrames, - AudioBufferList & ioData); - - - /*! @method Process */ - OSStatus DoProcess ( AudioUnitRenderActionFlags & ioActionFlags, - const AudioTimeStamp & inTimeStamp, - UInt32 inFramesToProcess, - AudioBufferList & ioData); - - /*! @method ProcessMultiple */ - OSStatus DoProcessMultiple ( AudioUnitRenderActionFlags & ioActionFlags, - const AudioTimeStamp & inTimeStamp, - UInt32 inFramesToProcess, - UInt32 inNumberInputBufferLists, - const AudioBufferList ** inInputBufferLists, - UInt32 inNumberOutputBufferLists, - AudioBufferList ** ioOutputBufferLists); - - /*! @method ProcessBufferLists */ - virtual OSStatus ProcessBufferLists( AudioUnitRenderActionFlags & ioActionFlags, - const AudioBufferList & inBuffer, - AudioBufferList & outBuffer, - UInt32 inFramesToProcess ) - { - return kAudio_UnimplementedError; - } - - /*! @method ProcessMultipleBufferLists */ - virtual OSStatus ProcessMultipleBufferLists( AudioUnitRenderActionFlags & ioActionFlags, - UInt32 inFramesToProcess, - UInt32 inNumberInputBufferLists, - const AudioBufferList ** inInputBufferLists, - UInt32 inNumberOutputBufferLists, - AudioBufferList ** ioOutputBufferLists) - { - return kAudio_UnimplementedError; - } - - /*! @method ComplexRender */ - virtual OSStatus ComplexRender( AudioUnitRenderActionFlags & ioActionFlags, - const AudioTimeStamp & inTimeStamp, - UInt32 inOutputBusNumber, - UInt32 inNumberOfPackets, - UInt32 * outNumberOfPackets, - AudioStreamPacketDescription * outPacketDescriptions, - AudioBufferList & ioData, - void * outMetadata, - UInt32 * outMetadataByteSize) - { - return kAudio_UnimplementedError; - } - - // Override this method if your AU processes multiple output busses completely independently -- - // you'll want to just call Render without the NeedsToRender check. - // Otherwise, override Render(). - // - // N.B. Implementations of this method can assume that the output's buffer list has already been - // prepared and access it with GetOutput(inBusNumber)->GetBufferList() instead of - // GetOutput(inBusNumber)->PrepareBuffer(nFrames) -- if PrepareBuffer is called, a - // copy may occur after rendering. - /*! @method RenderBus */ - virtual OSStatus RenderBus( AudioUnitRenderActionFlags & ioActionFlags, - const AudioTimeStamp & inTimeStamp, - UInt32 inBusNumber, - UInt32 inNumberFrames) - { - if (NeedsToRender(inTimeStamp)) - return Render(ioActionFlags, inTimeStamp, inNumberFrames); - return noErr; // was presumably already rendered via another bus - } - - // N.B. For a unit with only one output bus, it can assume in its implementation of this - // method that the output's buffer list has already been prepared and access it with - // GetOutput(0)->GetBufferList() instead of GetOutput(0)->PrepareBuffer(nFrames) - // -- if PrepareBuffer is called, a copy may occur after rendering. - /*! @method Render */ - virtual OSStatus Render( AudioUnitRenderActionFlags & ioActionFlags, - const AudioTimeStamp & inTimeStamp, - UInt32 inNumberFrames) - { - return noErr; - } - - -#pragma mark - -#pragma mark Property Dispatch - - static const Float64 kNoLastRenderedSampleTime; - - // ________________________________________________________________________ - // These are generated from DispatchGetProperty/DispatchGetPropertyInfo/DispatchSetProperty - - /*! @method BusCountWritable */ - virtual bool BusCountWritable( AudioUnitScope inScope) - { - return false; - } - virtual OSStatus SetBusCount( AudioUnitScope inScope, - UInt32 inCount); - - /*! @method SetConnection */ - virtual OSStatus SetConnection( const AudioUnitConnection & inConnection); - - /*! @method SetInputCallback */ - virtual OSStatus SetInputCallback( UInt32 inPropertyID, - AudioUnitElement inElement, - AURenderCallback inProc, - void * inRefCon); - - /*! @method GetParameterList */ - virtual OSStatus GetParameterList( AudioUnitScope inScope, - AudioUnitParameterID * outParameterList, - UInt32 & outNumParameters); - // outParameterList may be a null pointer - - /*! @method GetParameterInfo */ - virtual OSStatus GetParameterInfo( AudioUnitScope inScope, - AudioUnitParameterID inParameterID, - AudioUnitParameterInfo & outParameterInfo); - - virtual OSStatus GetParameterHistoryInfo(AudioUnitScope inScope, - AudioUnitParameterID inParameterID, - Float32 & outUpdatesPerSecond, - Float32 & outHistoryDurationInSeconds); - - /*! @method SaveState */ - virtual OSStatus SaveState( CFPropertyListRef * outData); - - /*! @method SaveExtendedScopes */ - virtual void SaveExtendedScopes( CFMutableDataRef outData) {}; - - /*! @method RestoreState */ - virtual OSStatus RestoreState( CFPropertyListRef inData); - - /*! @method GetParameterValueStrings */ - virtual OSStatus GetParameterValueStrings(AudioUnitScope inScope, - AudioUnitParameterID inParameterID, - CFArrayRef * outStrings); - - /*! @method CopyClumpName */ - virtual OSStatus CopyClumpName( AudioUnitScope inScope, - UInt32 inClumpID, - UInt32 inDesiredNameLength, - CFStringRef * outClumpName); - - /*! @method GetPresets */ - virtual OSStatus GetPresets ( CFArrayRef * outData) const; - - // set the default preset for the unit -> the number of the preset MUST be >= 0 - // and the name should be valid, or the preset WON'T take - /*! @method SetAFactoryPresetAsCurrent */ - bool SetAFactoryPresetAsCurrent (const AUPreset & inPreset); - - // Called when someone sets a new, valid preset - // If this is a valid preset, then the subclass sets its state to that preset - // and returns noErr. - // If not a valid preset, return an error, and the pre-existing preset is restored - /*! @method NewFactoryPresetSet */ - virtual OSStatus NewFactoryPresetSet (const AUPreset & inNewFactoryPreset); - - /*! @method NewCustomPresetSet */ - virtual OSStatus NewCustomPresetSet (const AUPreset & inNewCustomPreset); - -#if !CA_USE_AUDIO_PLUGIN_ONLY - /*! @method GetNumCustomUIComponents */ - virtual int GetNumCustomUIComponents (); - - /*! @method GetUIComponentDescs */ - virtual void GetUIComponentDescs (ComponentDescription* inDescArray); -#endif - - /*! @method CopyIconLocation */ - virtual CFURLRef CopyIconLocation (); - - // default is no latency, and unimplemented tail time - /*! @method GetLatency */ - virtual Float64 GetLatency() {return 0.0;} - /*! @method GetTailTime */ - virtual Float64 GetTailTime() {return 0;} - /*! @method SupportsRampAndTail */ - virtual bool SupportsTail () { return false; } - - /*! @method IsStreamFormatWritable */ - bool IsStreamFormatWritable( AudioUnitScope scope, - AudioUnitElement element); - - /*! @method StreamFormatWritable */ - virtual bool StreamFormatWritable( AudioUnitScope scope, - AudioUnitElement element) = 0; - // scope will always be input or output - - // pass in a pointer to get the struct, and num channel infos - // you can pass in NULL to just get the number - // a return value of 0 (the default in AUBase) means the property is not supported... - /*! @method SupportedNumChannels */ - virtual UInt32 SupportedNumChannels ( const AUChannelInfo** outInfo); - - /*! @method ValidFormat */ - virtual bool ValidFormat( AudioUnitScope inScope, - AudioUnitElement inElement, - const CAStreamBasicDescription & inNewFormat); - // Will only be called after StreamFormatWritable - // has succeeded. - // Default implementation requires canonical format: - // native-endian 32-bit float, any sample rate, - // any number of channels; override when other - // formats are supported. A subclass's override can - // choose to always return true and trap invalid - // formats in ChangeStreamFormat. - - - /*! @method FormatIsCanonical */ - bool FormatIsCanonical( const CAStreamBasicDescription &format); - - /*! @method MakeCanonicalFormat */ - void MakeCanonicalFormat( CAStreamBasicDescription & outDesc, - int numChannels = 2); - - /*! @method GetStreamFormat */ - virtual const CAStreamBasicDescription & - GetStreamFormat( AudioUnitScope inScope, - AudioUnitElement inElement); - - /*! @method ChangeStreamFormat */ - virtual OSStatus ChangeStreamFormat( AudioUnitScope inScope, - AudioUnitElement inElement, - const CAStreamBasicDescription & inPrevFormat, - const CAStreamBasicDescription & inNewFormat); - // Will only be called after StreamFormatWritable - // and ValidFormat have succeeded. - - // ________________________________________________________________________ - -#if !CA_USE_AUDIO_PLUGIN_ONLY - /*! @method ComponentEntryDispatch */ - static OSStatus ComponentEntryDispatch( ComponentParameters * params, - AUBase * This); -#endif - - // ________________________________________________________________________ - // Methods useful for subclasses - - /*! @method GetScope */ - AUScope & GetScope( AudioUnitScope inScope) - { - if (inScope >= kNumScopes) { - AUScope * scope = GetScopeExtended(inScope); - if (!scope) COMPONENT_THROW(kAudioUnitErr_InvalidScope); - return *scope; - } - return mScopes[inScope]; - } - - /*! @method GetScopeExtended */ - virtual AUScope * GetScopeExtended (AudioUnitScope inScope) { return NULL; } - - /*! @method GlobalScope */ - AUScope & GlobalScope() { return mScopes[kAudioUnitScope_Global]; } - /*! @method Inputs */ - AUScope & Inputs() { return mScopes[kAudioUnitScope_Input]; } - /*! @method Outputs */ - AUScope & Outputs() { return mScopes[kAudioUnitScope_Output]; } -#if !CA_BASIC_AU_FEATURES - /*! @method Groups */ - AUScope & Groups() { return mScopes[kAudioUnitScope_Group]; } -#endif - /*! @method Globals */ - AUElement * Globals() { return mScopes[kAudioUnitScope_Global].GetElement(0); } - - /*! @method SetNumberOfElements */ - void SetNumberOfElements( AudioUnitScope inScope, - UInt32 numElements); - - /*! @method GetElement */ - AUElement * GetElement( AudioUnitScope inScope, - AudioUnitElement inElement) - { - return GetScope(inScope).GetElement(inElement); - } - - /*! @method GetIOElement */ - AUIOElement * GetIOElement( AudioUnitScope inScope, - AudioUnitElement inElement) - { - return GetScope(inScope).GetIOElement(inElement); - } - - /*! @method SafeGetElement */ - AUElement * SafeGetElement( AudioUnitScope inScope, - AudioUnitElement inElement) - { - return GetScope(inScope).SafeGetElement(inElement); - } - - /*! @method GetInput */ - AUInputElement * GetInput( AudioUnitElement inElement) - { - return static_cast(Inputs().SafeGetElement(inElement)); - } - - /*! @method GetOutput */ - AUOutputElement * GetOutput( AudioUnitElement inElement) - { - return static_cast(Outputs().SafeGetElement(inElement)); - } - -#if !CA_BASIC_AU_FEATURES - /*! @method GetGroup */ - AUElement * GetGroup( AudioUnitElement inElement) - { - return Groups().SafeGetElement(inElement); - } -#endif - - /*! @method PullInput */ - OSStatus PullInput( UInt32 inBusNumber, - AudioUnitRenderActionFlags &ioActionFlags, - const AudioTimeStamp & inTimeStamp, - UInt32 inNumberFrames) - { - AUInputElement *input = GetInput(inBusNumber); // throws if error - return input->PullInput(ioActionFlags, inTimeStamp, inBusNumber, inNumberFrames); - } - - /*! @method GetMaxFramesPerSlice */ - UInt32 GetMaxFramesPerSlice() const { return mMaxFramesPerSlice; } - /*! @method UsesFixedBlockSize */ - bool UsesFixedBlockSize() const { return mUsesFixedBlockSize; } - /*! @method SetUsesFixedBlockSize */ - void SetUsesFixedBlockSize(bool inUsesFixedBlockSize) { mUsesFixedBlockSize = inUsesFixedBlockSize; } - - /*! @method GetVectorUnitType */ - static SInt32 GetVectorUnitType() { return sVectorUnitType; } - /*! @method HasVectorUnit */ - static bool HasVectorUnit() { return sVectorUnitType > 0; } - /*! @method HasAltivec */ - static bool HasAltivec() { return sVectorUnitType == kVecAltivec; } - /*! @method HasSSE2 */ - static bool HasSSE2() { return sVectorUnitType >= kVecSSE2; } - /*! @method HasSSE3 */ - static bool HasSSE3() { return sVectorUnitType >= kVecSSE3; } - - /*! @method AudioUnitAPIVersion */ - UInt8 AudioUnitAPIVersion() const { return mAudioUnitAPIVersion; } - - /*! @method IsRenderThread */ - bool InRenderThread () const - { -#if TARGET_OS_MAC - return (mRenderThreadID ? pthread_equal (mRenderThreadID, pthread_self()) : false); -#elif TARGET_OS_WIN32 - return (mRenderThreadID ? mRenderThreadID == GetCurrentThreadId() : false); -#endif - } - - /*! @method HasInput */ - bool HasInput( AudioUnitElement inElement) { - AUInputElement *in = static_cast(Inputs().GetElement(inElement)); - return in != NULL && in->IsActive(); - } - // says whether an input is connected or has a callback - - /*! @method PropertyChanged */ - virtual void PropertyChanged( AudioUnitPropertyID inID, - AudioUnitScope inScope, - AudioUnitElement inElement); - -#if !CA_NO_AU_UI_FEATURES - // These calls can be used to call a Host's Callbacks. The method returns -1 if the host - // hasn't supplied the callback. Any other result is returned by the host. - // As in the API contract, for a parameter's value, you specify a pointer - // to that data type. Specify NULL for a parameter that you are not interested - // as this can save work in the host. - - /*! @method CallHostBeatAndTempo */ - OSStatus CallHostBeatAndTempo (Float64 *outCurrentBeat, - Float64 *outCurrentTempo) - { - return (mHostCallbackInfo.beatAndTempoProc - ? (*mHostCallbackInfo.beatAndTempoProc) (mHostCallbackInfo.hostUserData, - outCurrentBeat, - outCurrentTempo) - : -1); - } - - /*! @method CallHostMusicalTimeLocation */ - OSStatus CallHostMusicalTimeLocation (UInt32 *outDeltaSampleOffsetToNextBeat, - Float32 *outTimeSig_Numerator, - UInt32 *outTimeSig_Denominator, - Float64 *outCurrentMeasureDownBeat) - { - return (mHostCallbackInfo.musicalTimeLocationProc - ? (*mHostCallbackInfo.musicalTimeLocationProc) (mHostCallbackInfo.hostUserData, - outDeltaSampleOffsetToNextBeat, - outTimeSig_Numerator, - outTimeSig_Denominator, - outCurrentMeasureDownBeat) - : -1); - } - - /*! @method CallHostTransportState */ - OSStatus CallHostTransportState (Boolean *outIsPlaying, - Boolean *outTransportStateChanged, - Float64 *outCurrentSampleInTimeLine, - Boolean *outIsCycling, - Float64 *outCycleStartBeat, - Float64 *outCycleEndBeat) - { - return (mHostCallbackInfo.transportStateProc - ? (*mHostCallbackInfo.transportStateProc) (mHostCallbackInfo.hostUserData, - outIsPlaying, - outTransportStateChanged, - outCurrentSampleInTimeLine, - outIsCycling, - outCycleStartBeat, - outCycleEndBeat) - : -1); - } -#endif - - char* GetLoggingString () const; - - CAMutex* GetMutex() { return mAUMutex; } - - // ________________________________________________________________________ - /*! @method CreateElement */ - virtual AUElement * CreateElement( AudioUnitScope scope, - AudioUnitElement element); - -#pragma mark - -#pragma mark AU Output Base Dispatch - // ________________________________________________________________________ - // ________________________________________________________________________ - // ________________________________________________________________________ - // output unit methods - /*! @method Start */ - virtual OSStatus Start() { return kAudio_UnimplementedError; } - /*! @method Stop */ - virtual OSStatus Stop() { return kAudio_UnimplementedError; } - -#if !CA_BASIC_AU_FEATURES -#pragma mark - -#pragma mark AU Music Base Dispatch - -#if !TARGET_OS_IPHONE -// these methods are deprecated, so we don't include them except for compatability - /*! @method PrepareInstrument */ - virtual OSStatus PrepareInstrument(MusicDeviceInstrumentID inInstrument) { return kAudio_UnimplementedError; } - - /*! @method PrepareInstrument */ - virtual OSStatus ReleaseInstrument(MusicDeviceInstrumentID inInstrument) { return kAudio_UnimplementedError; } -#endif - - // ________________________________________________________________________ - // ________________________________________________________________________ - // ________________________________________________________________________ - // music device/music effect methods -- incomplete - /*! @method MIDIEvent */ - virtual OSStatus MIDIEvent( UInt32 inStatus, - UInt32 inData1, - UInt32 inData2, - UInt32 inOffsetSampleFrame) { return kAudio_UnimplementedError; } - - /*! @method SysEx */ - virtual OSStatus SysEx( const UInt8 * inData, - UInt32 inLength) { return kAudio_UnimplementedError;} - - /*! @method StartNote */ - virtual OSStatus StartNote( MusicDeviceInstrumentID inInstrument, - MusicDeviceGroupID inGroupID, - NoteInstanceID * outNoteInstanceID, - UInt32 inOffsetSampleFrame, - const MusicDeviceNoteParams &inParams) { return kAudio_UnimplementedError; } - - /*! @method StopNote */ - virtual OSStatus StopNote( MusicDeviceGroupID inGroupID, - NoteInstanceID inNoteInstanceID, - UInt32 inOffsetSampleFrame) { return kAudio_UnimplementedError; } -#endif - - // ________________________________________________________________________ - // ________________________________________________________________________ - // ________________________________________________________________________ - -protected: -#pragma mark - -#pragma mark Implementation methods - - /*! @method ReallocateBuffers */ - virtual void ReallocateBuffers(); - // needs to be called when mMaxFramesPerSlice changes - virtual void DeallocateIOBuffers(); - - /*! @method FillInParameterName */ - static void FillInParameterName (AudioUnitParameterInfo& ioInfo, CFStringRef inName, bool inShouldRelease) - { - ioInfo.cfNameString = inName; - ioInfo.flags |= kAudioUnitParameterFlag_HasCFNameString; - if (inShouldRelease) - ioInfo.flags |= kAudioUnitParameterFlag_CFNameRelease; - CFStringGetCString (inName, ioInfo.name, offsetof (AudioUnitParameterInfo, clumpID), kCFStringEncodingUTF8); - } - - static void HasClump (AudioUnitParameterInfo& ioInfo, UInt32 inClumpID) - { - ioInfo.clumpID = inClumpID; - ioInfo.flags |= kAudioUnitParameterFlag_HasClump; - } - - /*! @method SetMaxFramesPerSlice */ - virtual void SetMaxFramesPerSlice(UInt32 nFrames); - - /*! @method CanSetMaxFrames */ - virtual OSStatus CanSetMaxFrames() const; - - /*! @method WantsRenderThreadID */ - bool WantsRenderThreadID () const { return mWantsRenderThreadID; } - - /*! @method SetWantsRenderThreadID */ - void SetWantsRenderThreadID (bool inFlag); - - /*! @method SetRenderError */ - OSStatus SetRenderError (OSStatus inErr) - { - if (inErr && mLastRenderError == 0) { - mLastRenderError = inErr; - PropertyChanged(kAudioUnitProperty_LastRenderError, kAudioUnitScope_Global, 0); - } - return inErr; - } - -private: - /*! @method DoRenderBus */ - // shared between Render and RenderSlice, inlined to minimize function call overhead - OSStatus DoRenderBus( AudioUnitRenderActionFlags & ioActionFlags, - const AudioTimeStamp & inTimeStamp, - UInt32 inBusNumber, - AUOutputElement * theOutput, - UInt32 inNumberFrames, - AudioBufferList & ioData) - { - if (ioData.mBuffers[0].mData == NULL || (theOutput->WillAllocateBuffer() && Outputs().GetNumberOfElements() > 1)) - // will render into cache buffer - theOutput->PrepareBuffer(inNumberFrames); - else - // will render into caller's buffer - theOutput->SetBufferList(ioData); - OSStatus result = RenderBus(ioActionFlags, inTimeStamp, inBusNumber, inNumberFrames); - if (result == noErr) { - if (ioData.mBuffers[0].mData == NULL) { - theOutput->CopyBufferListTo(ioData); - AUTRACE(kCATrace_AUBaseDoRenderBus, mComponentInstance, inNumberFrames, (intptr_t)theOutput->GetBufferList().mBuffers[0].mData, 0, *(UInt32 *)ioData.mBuffers[0].mData); - } else { - theOutput->CopyBufferContentsTo(ioData); - AUTRACE(kCATrace_AUBaseDoRenderBus, mComponentInstance, inNumberFrames, (intptr_t)theOutput->GetBufferList().mBuffers[0].mData, (intptr_t)ioData.mBuffers[0].mData, *(UInt32 *)ioData.mBuffers[0].mData); - theOutput->InvalidateBufferList(); - } - } - return result; - } - - /*! @method HasIcon */ - bool HasIcon (); - - /*! @method ResetRenderTime */ - void ResetRenderTime () - { - memset (&mCurrentRenderTime, 0, sizeof(mCurrentRenderTime)); - mCurrentRenderTime.mSampleTime = kNoLastRenderedSampleTime; - } - -protected: - /*! @method GetAudioChannelLayout */ - virtual UInt32 GetChannelLayoutTags( AudioUnitScope scope, - AudioUnitElement element, - AudioChannelLayoutTag * outLayoutTags); - - /*! @method GetAudioChannelLayout */ - virtual UInt32 GetAudioChannelLayout( AudioUnitScope scope, - AudioUnitElement element, - AudioChannelLayout * outLayoutPtr, - Boolean & outWritable); - - /*! @method SetAudioChannelLayout */ - virtual OSStatus SetAudioChannelLayout( AudioUnitScope scope, - AudioUnitElement element, - const AudioChannelLayout * inLayout); - - /*! @method RemoveAudioChannelLayout */ - virtual OSStatus RemoveAudioChannelLayout(AudioUnitScope scope, AudioUnitElement element); - - /*! @method NeedsToRender */ - bool NeedsToRender( const AudioTimeStamp & inTimeStamp) - { - bool needsToRender = fnotequal(inTimeStamp.mSampleTime, mCurrentRenderTime.mSampleTime); - if (needsToRender) // only copy this if we need to render - mCurrentRenderTime = inTimeStamp; - return needsToRender; - } - - // Scheduled parameter implementation: - - typedef std::vector ParameterEventList; - - // Usually, you won't override this method. You only need to call this if your DSP code - // is prepared to handle scheduled immediate and ramped parameter changes. - // Before calling this method, it is assumed you have already called PullInput() on the input busses - // for which the DSP code depends. ProcessForScheduledParams() will call (potentially repeatedly) - // virtual method ProcessScheduledSlice() to perform the actual DSP for a given sub-division of - // the buffer. The job of ProcessForScheduledParams() is to sub-divide the buffer into smaller - // pieces according to the scheduled times found in the ParameterEventList (usually coming - // directly from a previous call to ScheduleParameter() ), setting the appropriate immediate or - // ramped parameter values for the corresponding scopes and elements, then calling ProcessScheduledSlice() - // to do the actual DSP for each of these divisions. - virtual OSStatus ProcessForScheduledParams( ParameterEventList &inParamList, - UInt32 inFramesToProcess, - void *inUserData ); - - // This method is called (potentially repeatedly) by ProcessForScheduledParams() - // in order to perform the actual DSP required for this portion of the entire buffer - // being processed. The entire buffer can be divided up into smaller "slices" - // according to the timestamps on the scheduled parameters... - // - // sub-classes wishing to handle scheduled parameter changes should override this method - // in order to do the appropriate DSP. AUEffectBase already overrides this for standard - // effect AudioUnits. - virtual OSStatus ProcessScheduledSlice( void *inUserData, - UInt32 inStartFrameInBuffer, - UInt32 inSliceFramesToProcess, - UInt32 inTotalBufferFrames ) {return noErr;}; // default impl does nothing... - - - /*! @method CurrentRenderTime */ - const AudioTimeStamp & CurrentRenderTime () const { return mCurrentRenderTime; } - - // ________________________________________________________________________ - // Private data members to discourage hacking in subclasses -private: - struct RenderCallback { - RenderCallback(AURenderCallback proc, void *ref) : - mRenderNotify(proc), - mRenderNotifyRefCon(ref) - { } - - AURenderCallback mRenderNotify; - void * mRenderNotifyRefCon; - - bool operator == (const RenderCallback &other) { - return this->mRenderNotify == other.mRenderNotify && - this->mRenderNotifyRefCon == other.mRenderNotifyRefCon; - } - }; - typedef TThreadSafeList RenderCallbackList; - -#if !CA_BASIC_AU_FEATURES - enum { kNumScopes = 4 }; -#else - enum { kNumScopes = 3 }; -#endif - - /*! @var mElementsCreated */ - bool mElementsCreated; -protected: - /*! @var mInitialized */ - bool mInitialized; - /*! @var mHasBegunInitializing */ - bool mHasBegunInitializing; -private: - /*! @var mAudioUnitAPIVersion */ - UInt8 mAudioUnitAPIVersion; - - /*! @var mInitNumInputEls */ - const UInt32 mInitNumInputEls; - /*! @var mInitNumOutputEls */ - const UInt32 mInitNumOutputEls; -#if !CA_BASIC_AU_FEATURES - /*! @var mInitNumGroupEls */ - const UInt32 mInitNumGroupEls; -#endif - /*! @var mScopes */ - AUScope mScopes[kNumScopes]; - - /*! @var mRenderCallbacks */ - RenderCallbackList mRenderCallbacks; - bool mRenderCallbacksTouched; - - /*! @var mRenderThreadID */ -#if TARGET_OS_MAC - pthread_t mRenderThreadID; -#elif TARGET_OS_WIN32 - UInt32 mRenderThreadID; -#endif - - /*! @var mWantsRenderThreadID */ - bool mWantsRenderThreadID; - - /*! @var mCurrentRenderTime */ - AudioTimeStamp mCurrentRenderTime; - - /*! @var mMaxFramesPerSlice */ - UInt32 mMaxFramesPerSlice; - - /*! @var mLastRenderError */ - OSStatus mLastRenderError; - /*! @var mCurrentPreset */ - AUPreset mCurrentPreset; - -protected: - /*! @var mUsesFixedBlockSize */ - bool mUsesFixedBlockSize; - - struct PropertyListener { - AudioUnitPropertyID propertyID; - AudioUnitPropertyListenerProc listenerProc; - void * listenerRefCon; - }; - typedef std::vector PropertyListeners; - - /*! @var mParamList */ - ParameterEventList mParamList; - /*! @var mPropertyListeners */ - PropertyListeners mPropertyListeners; - - /*! @var mBuffersAllocated */ - bool mBuffersAllocated; - - /*! @var mLogString */ - // if this is NOT null, it will contain identifying info about this AU. - char* mLogString; - - /*! @var mNickName */ - CFStringRef mNickName; - - /*! @var mAUMutex */ - CAMutex * mAUMutex; - -private: - /*! @var sVectorUnitType */ - static SInt32 sVectorUnitType; - -#if !CA_NO_AU_HOST_CALLBACKS -protected: - /*! @var mHostCallbackInfo */ - HostCallbackInfo mHostCallbackInfo; - -#endif -#if !CA_NO_AU_UI_FEATURES -protected: - /*! @var mContextInfo */ - CFStringRef mContextName; -#endif -}; - -inline OSStatus AUInputElement::PullInputWithBufferList( - AudioUnitRenderActionFlags & ioActionFlags, - const AudioTimeStamp & inTimeStamp, - AudioUnitElement inElement, - UInt32 nFrames, - AudioBufferList * inBufferList) -{ - OSStatus theResult; - - if (HasConnection()) { - // only support connections for V2 audio units -#if !CA_USE_AUDIO_PLUGIN_ONLY - if (mConnRenderProc != NULL) - theResult = reinterpret_cast(mConnRenderProc)( - mConnInstanceStorage, &ioActionFlags, &inTimeStamp, mConnection.sourceOutputNumber, nFrames, inBufferList); - else -#endif - theResult = AudioUnitRender( - mConnection.sourceAudioUnit, &ioActionFlags, &inTimeStamp, mConnection.sourceOutputNumber, nFrames, inBufferList); - } else { - // kFromCallback: - theResult = (mInputProc)( - mInputProcRefCon, &ioActionFlags, &inTimeStamp, inElement, nFrames, inBufferList); - } - - if (mInputType == kNoInput) // defense: the guy upstream could have disconnected - // it's a horrible thing to do, but may happen! - return kAudioUnitErr_NoConnection; - - - return theResult; -} - -#endif // __AUBase_h__ diff --git a/src/CoreAudio/CoreAudioComponent/AUPublic/AUBase/AUDispatch.cpp b/src/CoreAudio/CoreAudioComponent/AUPublic/AUBase/AUDispatch.cpp deleted file mode 100644 index 1f0f01c7d..000000000 --- a/src/CoreAudio/CoreAudioComponent/AUPublic/AUBase/AUDispatch.cpp +++ /dev/null @@ -1,438 +0,0 @@ -/* - File: AUDispatch.cpp - Abstract: AUDispatch.h - Version: 1.1 - - Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple - Inc. ("Apple") in consideration of your agreement to the following - terms, and your use, installation, modification or redistribution of - this Apple software constitutes acceptance of these terms. If you do - not agree with these terms, please do not use, install, modify or - redistribute this Apple software. - - In consideration of your agreement to abide by the following terms, and - subject to these terms, Apple grants you a personal, non-exclusive - license, under Apple's copyrights in this original Apple software (the - "Apple Software"), to use, reproduce, modify and redistribute the Apple - Software, with or without modifications, in source and/or binary forms; - provided that if you redistribute the Apple Software in its entirety and - without modifications, you must retain this notice and the following - text and disclaimers in all such redistributions of the Apple Software. - Neither the name, trademarks, service marks or logos of Apple Inc. may - be used to endorse or promote products derived from the Apple Software - without specific prior written permission from Apple. Except as - expressly stated in this notice, no other rights or licenses, express or - implied, are granted by Apple herein, including but not limited to any - patent rights that may be infringed by your derivative works or by other - works in which the Apple Software may be incorporated. - - The Apple Software is provided by Apple on an "AS IS" basis. APPLE - MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION - THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS - FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND - OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS. - - IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL - OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, - MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED - AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), - STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE - POSSIBILITY OF SUCH DAMAGE. - - Copyright (C) 2014 Apple Inc. All Rights Reserved. - -*/ -#include "AUBase.h" -#include "CAXException.h" -#include "AUDispatch.h" - - - -#if TARGET_OS_MAC - #if __LP64__ - // comp instance, parameters in forward order - #define PARAM(_typ, _name, _index, _nparams) \ - _typ _name = *(_typ *)¶ms->params[_index + 1]; - #else - // parameters in reverse order, then comp instance - #define PARAM(_typ, _name, _index, _nparams) \ - _typ _name = *(_typ *)¶ms->params[_nparams - 1 - _index]; - #endif -#elif TARGET_OS_WIN32 - // (no comp instance), parameters in forward order - #define PARAM(_typ, _name, _index, _nparams) \ - _typ _name = *(_typ *)¶ms->params[_index]; -#endif - - -OSStatus AUBase::ComponentEntryDispatch(ComponentParameters *params, AUBase *This) -{ - if (This == NULL) return kAudio_ParamError; - - OSStatus result = noErr; - - switch (params->what) { - case kComponentCanDoSelect: - switch (GetSelectorForCanDo(params)) { - // any selectors - case kAudioUnitInitializeSelect: - case kAudioUnitUninitializeSelect: - case kAudioUnitGetPropertyInfoSelect: - case kAudioUnitGetPropertySelect: - case kAudioUnitSetPropertySelect: - case kAudioUnitAddPropertyListenerSelect: -#if (!__LP64__) - case kAudioUnitRemovePropertyListenerSelect: -#endif - case kAudioUnitGetParameterSelect: - case kAudioUnitSetParameterSelect: - case kAudioUnitResetSelect: - result = 1; - break; - // v1 selectors - - // v2 selectors - case kAudioUnitRemovePropertyListenerWithUserDataSelect: - case kAudioUnitAddRenderNotifySelect: - case kAudioUnitRemoveRenderNotifySelect: - case kAudioUnitScheduleParametersSelect: - case kAudioUnitRenderSelect: - result = (This->AudioUnitAPIVersion() > 1); - break; - - default: - return ComponentBase::ComponentEntryDispatch(params, This); - } - break; - - case kAudioUnitInitializeSelect: - { - CAMutex::Locker lock2(This->GetMutex()); - result = This->DoInitialize(); - } - break; - - case kAudioUnitUninitializeSelect: - { - CAMutex::Locker lock2(This->GetMutex()); - This->DoCleanup(); - result = noErr; - } - break; - - case kAudioUnitGetPropertyInfoSelect: - { - CAMutex::Locker lock(This->GetMutex()); - PARAM(AudioUnitPropertyID, pinID, 0, 5); - PARAM(AudioUnitScope, pinScope, 1, 5); - PARAM(AudioUnitElement, pinElement, 2, 5); - PARAM(UInt32 *, poutDataSize, 3, 5); - PARAM(Boolean *, poutWritable, 4, 5); - - // pass our own copies so that we assume responsibility for testing - // the caller's pointers against null and our C++ classes can - // always assume they're non-null - UInt32 dataSize; - Boolean writable; - - result = This->DispatchGetPropertyInfo(pinID, pinScope, pinElement, dataSize, writable); - if (poutDataSize != NULL) - *poutDataSize = dataSize; - if (poutWritable != NULL) - *poutWritable = writable; - } - break; - - case kAudioUnitGetPropertySelect: - { - CAMutex::Locker lock(This->GetMutex()); - PARAM(AudioUnitPropertyID, pinID, 0, 5); - PARAM(AudioUnitScope, pinScope, 1, 5); - PARAM(AudioUnitElement, pinElement, 2, 5); - PARAM(void *, poutData, 3, 5); - PARAM(UInt32 *, pioDataSize, 4, 5); - - UInt32 actualPropertySize, clientBufferSize; - Boolean writable; - char *tempBuffer; - void *destBuffer; - - if (pioDataSize == NULL) { - ca_debug_string("AudioUnitGetProperty: null size pointer"); - result = kAudio_ParamError; - goto finishGetProperty; - } - if (poutData == NULL) { - UInt32 dataSize; - - result = This->DispatchGetPropertyInfo(pinID, pinScope, pinElement, dataSize, writable); - *pioDataSize = dataSize; - goto finishGetProperty; - } - - clientBufferSize = *pioDataSize; - if (clientBufferSize == 0) - { - ca_debug_string("AudioUnitGetProperty: *ioDataSize == 0 on entry"); - // $$$ or should we allow this as a shortcut for finding the size? - result = kAudio_ParamError; - goto finishGetProperty; - } - - result = This->DispatchGetPropertyInfo(pinID, pinScope, pinElement, - actualPropertySize, writable); - if (result) - goto finishGetProperty; - - if (clientBufferSize < actualPropertySize) - { - tempBuffer = new char[actualPropertySize]; - destBuffer = tempBuffer; - } else { - tempBuffer = NULL; - destBuffer = poutData; - } - - result = This->DispatchGetProperty(pinID, pinScope, pinElement, destBuffer); - - if (result == noErr) { - if (clientBufferSize < actualPropertySize && tempBuffer != NULL) - { - memcpy(poutData, tempBuffer, clientBufferSize); - delete[] tempBuffer; - // pioDataSize remains correct, the number of bytes we wrote - } else - *pioDataSize = actualPropertySize; - } else - *pioDataSize = 0; - - finishGetProperty: - ; - - } - break; - - case kAudioUnitSetPropertySelect: - { - CAMutex::Locker lock(This->GetMutex()); - PARAM(AudioUnitPropertyID, pinID, 0, 5); - PARAM(AudioUnitScope, pinScope, 1, 5); - PARAM(AudioUnitElement, pinElement, 2, 5); - PARAM(const void *, pinData, 3, 5); - PARAM(UInt32, pinDataSize, 4, 5); - - if (pinData && pinDataSize) - result = This->DispatchSetProperty(pinID, pinScope, pinElement, pinData, pinDataSize); - else { - if (pinData == NULL && pinDataSize == 0) { - result = This->DispatchRemovePropertyValue (pinID, pinScope, pinElement); - } else { - if (pinData == NULL) { - ca_debug_string("AudioUnitSetProperty: inData == NULL"); - result = kAudio_ParamError; - goto finishSetProperty; - } - - if (pinDataSize == 0) { - ca_debug_string("AudioUnitSetProperty: inDataSize == 0"); - result = kAudio_ParamError; - goto finishSetProperty; - } - } - } - finishSetProperty: - ; - - } - break; - - case kAudioUnitAddPropertyListenerSelect: - { - CAMutex::Locker lock(This->GetMutex()); - PARAM(AudioUnitPropertyID, pinID, 0, 3); - PARAM(AudioUnitPropertyListenerProc, pinProc, 1, 3); - PARAM(void *, pinProcRefCon, 2, 3); - result = This->AddPropertyListener(pinID, pinProc, pinProcRefCon); - } - break; - -#if (!__LP64__) - case kAudioUnitRemovePropertyListenerSelect: - { - CAMutex::Locker lock(This->GetMutex()); - PARAM(AudioUnitPropertyID, pinID, 0, 2); - PARAM(AudioUnitPropertyListenerProc, pinProc, 1, 2); - result = This->RemovePropertyListener(pinID, pinProc, NULL, false); - } - break; -#endif - - case kAudioUnitRemovePropertyListenerWithUserDataSelect: - { - CAMutex::Locker lock(This->GetMutex()); - PARAM(AudioUnitPropertyID, pinID, 0, 3); - PARAM(AudioUnitPropertyListenerProc, pinProc, 1, 3); - PARAM(void *, pinProcRefCon, 2, 3); - result = This->RemovePropertyListener(pinID, pinProc, pinProcRefCon, true); - } - break; - - case kAudioUnitAddRenderNotifySelect: - { - CAMutex::Locker lock(This->GetMutex()); - PARAM(AURenderCallback, pinProc, 0, 2); - PARAM(void *, pinProcRefCon, 1, 2); - result = This->SetRenderNotification (pinProc, pinProcRefCon); - } - break; - - case kAudioUnitRemoveRenderNotifySelect: - { - CAMutex::Locker lock(This->GetMutex()); - PARAM(AURenderCallback, pinProc, 0, 2); - PARAM(void *, pinProcRefCon, 1, 2); - result = This->RemoveRenderNotification (pinProc, pinProcRefCon); - } - break; - - case kAudioUnitGetParameterSelect: - { - CAMutex::Locker lock(This->GetMutex()); - PARAM(AudioUnitParameterID, pinID, 0, 4); - PARAM(AudioUnitScope, pinScope, 1, 4); - PARAM(AudioUnitElement, pinElement, 2, 4); - PARAM(AudioUnitParameterValue *, poutValue, 3, 4); - result = (poutValue == NULL ? kAudio_ParamError : This->GetParameter(pinID, pinScope, pinElement, *poutValue)); - } - break; - - case kAudioUnitSetParameterSelect: - { - CAMutex::Locker lock(This->GetMutex()); // is this realtime or no??? - PARAM(AudioUnitParameterID, pinID, 0, 5); - PARAM(AudioUnitScope, pinScope, 1, 5); - PARAM(AudioUnitElement, pinElement, 2, 5); - PARAM(AudioUnitParameterValue, pinValue, 3, 5); - PARAM(UInt32, pinBufferOffsetInFrames, 4, 5); - result = This->SetParameter(pinID, pinScope, pinElement, pinValue, pinBufferOffsetInFrames); - } - break; - - case kAudioUnitScheduleParametersSelect: - { - CAMutex::Locker lock(This->GetMutex()); // is this realtime or no??? - if (This->AudioUnitAPIVersion() > 1) - { - PARAM(AudioUnitParameterEvent *, pinParameterEvent, 0, 2); - PARAM(UInt32, pinNumParamEvents, 1, 2); - result = This->ScheduleParameter (pinParameterEvent, pinNumParamEvents); - } else - result = badComponentSelector; - } - break; - - - case kAudioUnitRenderSelect: - { - // realtime; no lock - { - PARAM(AudioUnitRenderActionFlags *, pinActionFlags, 0, 5); - PARAM(const AudioTimeStamp *, pinTimeStamp, 1, 5); - PARAM(UInt32, pinOutputBusNumber, 2, 5); - PARAM(UInt32, pinNumberFrames, 3, 5); - PARAM(AudioBufferList *, pioData, 4, 5); - AudioUnitRenderActionFlags tempFlags; - - if (pinTimeStamp == NULL || pioData == NULL) - result = kAudio_ParamError; - else { - if (pinActionFlags == NULL) { - tempFlags = 0; - pinActionFlags = &tempFlags; - } - result = This->DoRender(*pinActionFlags, *pinTimeStamp, pinOutputBusNumber, pinNumberFrames, *pioData); - } - } - } - break; - - case kAudioUnitResetSelect: - { - CAMutex::Locker lock(This->GetMutex()); - PARAM(AudioUnitScope, pinScope, 0, 2); - PARAM(AudioUnitElement, pinElement, 1, 2); - This->ResetRenderTime(); - result = This->Reset(pinScope, pinElement); - } - break; - - default: - result = ComponentBase::ComponentEntryDispatch(params, This); - break; - } - - return result; -} - -// Fast dispatch entry points -- these need to replicate all error-checking logic from above - -OSStatus CMgr_AudioUnitBaseGetParameter( AUBase * This, - AudioUnitParameterID inID, - AudioUnitScope inScope, - AudioUnitElement inElement, - float *outValue) -{ - OSStatus result = AUBase::noErr; - - try { - if (This == NULL || outValue == NULL) return kAudio_ParamError; - result = This->GetParameter(inID, inScope, inElement, *outValue); - } - COMPONENT_CATCH - - return result; -} - -OSStatus CMgr_AudioUnitBaseSetParameter( AUBase * This, - AudioUnitParameterID inID, - AudioUnitScope inScope, - AudioUnitElement inElement, - float inValue, - UInt32 inBufferOffset) -{ - OSStatus result = AUBase::noErr; - - try { - if (This == NULL) return kAudio_ParamError; - result = This->SetParameter(inID, inScope, inElement, inValue, inBufferOffset); - } - COMPONENT_CATCH - - return result; -} - -OSStatus CMgr_AudioUnitBaseRender( AUBase * This, - AudioUnitRenderActionFlags *ioActionFlags, - const AudioTimeStamp * inTimeStamp, - UInt32 inBusNumber, - UInt32 inNumberFrames, - AudioBufferList * ioData) -{ - if (inTimeStamp == NULL || ioData == NULL) return kAudio_ParamError; - - OSStatus result = AUBase::noErr; - AudioUnitRenderActionFlags tempFlags; - - try { - if (ioActionFlags == NULL) { - tempFlags = 0; - ioActionFlags = &tempFlags; - } - result = This->DoRender(*ioActionFlags, *inTimeStamp, inBusNumber, inNumberFrames, *ioData); - } - COMPONENT_CATCH - - return result; -} diff --git a/src/CoreAudio/CoreAudioComponent/AUPublic/AUBase/AUDispatch.h b/src/CoreAudio/CoreAudioComponent/AUPublic/AUBase/AUDispatch.h deleted file mode 100644 index 5acd96250..000000000 --- a/src/CoreAudio/CoreAudioComponent/AUPublic/AUBase/AUDispatch.h +++ /dev/null @@ -1,82 +0,0 @@ -/* - File: AUDispatch.h - Abstract: Part of CoreAudio Utility Classes - Version: 1.1 - - Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple - Inc. ("Apple") in consideration of your agreement to the following - terms, and your use, installation, modification or redistribution of - this Apple software constitutes acceptance of these terms. If you do - not agree with these terms, please do not use, install, modify or - redistribute this Apple software. - - In consideration of your agreement to abide by the following terms, and - subject to these terms, Apple grants you a personal, non-exclusive - license, under Apple's copyrights in this original Apple software (the - "Apple Software"), to use, reproduce, modify and redistribute the Apple - Software, with or without modifications, in source and/or binary forms; - provided that if you redistribute the Apple Software in its entirety and - without modifications, you must retain this notice and the following - text and disclaimers in all such redistributions of the Apple Software. - Neither the name, trademarks, service marks or logos of Apple Inc. may - be used to endorse or promote products derived from the Apple Software - without specific prior written permission from Apple. Except as - expressly stated in this notice, no other rights or licenses, express or - implied, are granted by Apple herein, including but not limited to any - patent rights that may be infringed by your derivative works or by other - works in which the Apple Software may be incorporated. - - The Apple Software is provided by Apple on an "AS IS" basis. APPLE - MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION - THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS - FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND - OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS. - - IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL - OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, - MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED - AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), - STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE - POSSIBILITY OF SUCH DAMAGE. - - Copyright (C) 2014 Apple Inc. All Rights Reserved. - -*/ -#ifndef __AUDispatch_h__ -#define __AUDispatch_h__ - - -#if !defined(__COREAUDIO_USE_FLAT_INCLUDES__) - #include -#else - #include "AudioUnit.h" -#endif - -#if !CA_USE_AUDIO_PLUGIN_ONLY -/*! @function AudioUnitBaseGetParameter */ -OSStatus CMgr_AudioUnitBaseGetParameter( AUBase * This, - AudioUnitParameterID inID, - AudioUnitScope inScope, - AudioUnitElement inElement, - float * outValue); - -/*! @function AudioUnitBaseSetParameter */ -OSStatus CMgr_AudioUnitBaseSetParameter( AUBase * This, - AudioUnitParameterID inID, - AudioUnitScope inScope, - AudioUnitElement inElement, - float inValue, - UInt32 inBufferOffset); - -/*! @function AudioUnitBaseRender */ -OSStatus CMgr_AudioUnitBaseRender( AUBase * This, - AudioUnitRenderActionFlags *ioActionFlags, - const AudioTimeStamp * inTimeStamp, - UInt32 inBusNumber, - UInt32 inNumberFrames, - AudioBufferList * ioData); -#endif - -#endif // __AUDispatch_h__ diff --git a/src/CoreAudio/CoreAudioComponent/AUPublic/AUBase/AUInputElement.cpp b/src/CoreAudio/CoreAudioComponent/AUPublic/AUBase/AUInputElement.cpp deleted file mode 100644 index 2e148e8ba..000000000 --- a/src/CoreAudio/CoreAudioComponent/AUPublic/AUBase/AUInputElement.cpp +++ /dev/null @@ -1,151 +0,0 @@ -/* - File: AUInputElement.cpp - Abstract: AUInputElement.h - Version: 1.1 - - Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple - Inc. ("Apple") in consideration of your agreement to the following - terms, and your use, installation, modification or redistribution of - this Apple software constitutes acceptance of these terms. If you do - not agree with these terms, please do not use, install, modify or - redistribute this Apple software. - - In consideration of your agreement to abide by the following terms, and - subject to these terms, Apple grants you a personal, non-exclusive - license, under Apple's copyrights in this original Apple software (the - "Apple Software"), to use, reproduce, modify and redistribute the Apple - Software, with or without modifications, in source and/or binary forms; - provided that if you redistribute the Apple Software in its entirety and - without modifications, you must retain this notice and the following - text and disclaimers in all such redistributions of the Apple Software. - Neither the name, trademarks, service marks or logos of Apple Inc. may - be used to endorse or promote products derived from the Apple Software - without specific prior written permission from Apple. Except as - expressly stated in this notice, no other rights or licenses, express or - implied, are granted by Apple herein, including but not limited to any - patent rights that may be infringed by your derivative works or by other - works in which the Apple Software may be incorporated. - - The Apple Software is provided by Apple on an "AS IS" basis. APPLE - MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION - THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS - FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND - OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS. - - IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL - OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, - MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED - AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), - STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE - POSSIBILITY OF SUCH DAMAGE. - - Copyright (C) 2014 Apple Inc. All Rights Reserved. - -*/ -#include "AUBase.h" - -inline bool HasGoodBufferPointers(const AudioBufferList &abl, UInt32 nBytes) -{ - const AudioBuffer *buf = abl.mBuffers; - for (UInt32 i = abl.mNumberBuffers; i--;++buf) { - if (buf->mData == NULL || buf->mDataByteSize < nBytes) - return false; - } - return true; -} - - -//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -// AUInputElement::AUInputElement -// -//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -AUInputElement::AUInputElement(AUBase *audioUnit) : - AUIOElement(audioUnit), - mInputType(kNoInput) -{ -} - -//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -// AUInputElement::SetConnection -// -//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -void AUInputElement::SetConnection(const AudioUnitConnection &conn) -{ - if (conn.sourceAudioUnit == 0) { - Disconnect(); - return; - } - - mInputType = kFromConnection; - mConnection = conn; - AllocateBuffer(); - - mConnInstanceStorage = NULL; - -#if !CA_USE_AUDIO_PLUGIN_ONLY - mConnRenderProc = NULL; - UInt32 size = sizeof(AudioUnitRenderProc); - OSStatus result = AudioUnitGetProperty( conn.sourceAudioUnit, - kAudioUnitProperty_FastDispatch, - kAudioUnitScope_Global, - kAudioUnitRenderSelect, - &mConnRenderProc, - &size); - if (result == noErr) - mConnInstanceStorage = CMgr_GetComponentInstanceStorage (conn.sourceAudioUnit); - else - mConnRenderProc = NULL; -#endif -} - -void AUInputElement::Disconnect() -{ - mInputType = kNoInput; - mIOBuffer.Deallocate(); -} - - - -//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -// AUInputElement::SetInputCallback -// -//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -void AUInputElement::SetInputCallback(AURenderCallback proc, void *refCon) -{ - if (proc == NULL) - Disconnect(); - else { - mInputType = kFromCallback; - mInputProc = proc; - mInputProcRefCon = refCon; - AllocateBuffer(); - } -} - -OSStatus AUInputElement::SetStreamFormat(const CAStreamBasicDescription &fmt) -{ - OSStatus err = AUIOElement::SetStreamFormat(fmt); - if (err == AUBase::noErr) - AllocateBuffer(); - return err; -} - -OSStatus AUInputElement::PullInput( AudioUnitRenderActionFlags & ioActionFlags, - const AudioTimeStamp & inTimeStamp, - AudioUnitElement inElement, - UInt32 nFrames) -{ - if (!IsActive()) - return kAudioUnitErr_NoConnection; - - AudioBufferList *pullBuffer; - - if (HasConnection() || !WillAllocateBuffer()) - pullBuffer = &mIOBuffer.PrepareNullBuffer(mStreamFormat, nFrames); - else - pullBuffer = &mIOBuffer.PrepareBuffer(mStreamFormat, nFrames); - - return PullInputWithBufferList (ioActionFlags, inTimeStamp, inElement, nFrames, pullBuffer); -} diff --git a/src/CoreAudio/CoreAudioComponent/AUPublic/AUBase/AUInputElement.h b/src/CoreAudio/CoreAudioComponent/AUPublic/AUBase/AUInputElement.h deleted file mode 100644 index 891e4c60b..000000000 --- a/src/CoreAudio/CoreAudioComponent/AUPublic/AUBase/AUInputElement.h +++ /dev/null @@ -1,119 +0,0 @@ -/* - File: AUInputElement.h - Abstract: Part of CoreAudio Utility Classes - Version: 1.1 - - Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple - Inc. ("Apple") in consideration of your agreement to the following - terms, and your use, installation, modification or redistribution of - this Apple software constitutes acceptance of these terms. If you do - not agree with these terms, please do not use, install, modify or - redistribute this Apple software. - - In consideration of your agreement to abide by the following terms, and - subject to these terms, Apple grants you a personal, non-exclusive - license, under Apple's copyrights in this original Apple software (the - "Apple Software"), to use, reproduce, modify and redistribute the Apple - Software, with or without modifications, in source and/or binary forms; - provided that if you redistribute the Apple Software in its entirety and - without modifications, you must retain this notice and the following - text and disclaimers in all such redistributions of the Apple Software. - Neither the name, trademarks, service marks or logos of Apple Inc. may - be used to endorse or promote products derived from the Apple Software - without specific prior written permission from Apple. Except as - expressly stated in this notice, no other rights or licenses, express or - implied, are granted by Apple herein, including but not limited to any - patent rights that may be infringed by your derivative works or by other - works in which the Apple Software may be incorporated. - - The Apple Software is provided by Apple on an "AS IS" basis. APPLE - MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION - THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS - FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND - OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS. - - IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL - OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, - MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED - AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), - STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE - POSSIBILITY OF SUCH DAMAGE. - - Copyright (C) 2014 Apple Inc. All Rights Reserved. - -*/ -#ifndef __AUInput_h__ -#define __AUInput_h__ - -#include "AUScopeElement.h" -#include "AUBuffer.h" - -/*! @class AUInputElement */ -class AUInputElement : public AUIOElement { -public: - - /*! @ctor AUInputElement */ - AUInputElement(AUBase *audioUnit); - /*! @dtor ~AUInputElement */ - virtual ~AUInputElement() { } - - // AUElement override - /*! @method SetStreamFormat */ - virtual OSStatus SetStreamFormat(const CAStreamBasicDescription &desc); - /*! @method NeedsBufferSpace */ - virtual bool NeedsBufferSpace() const { return IsCallback(); } - - /*! @method SetConnection */ - void SetConnection(const AudioUnitConnection &conn); - /*! @method SetInputCallback */ - void SetInputCallback(AURenderCallback proc, void *refCon); - - /*! @method IsActive */ - bool IsActive() const { return mInputType != kNoInput; } - /*! @method IsCallback */ - bool IsCallback() const { return mInputType == kFromCallback; } - /*! @method HasConnection */ - bool HasConnection() const { return mInputType == kFromConnection; } - - /*! @method PullInput */ - OSStatus PullInput( AudioUnitRenderActionFlags & ioActionFlags, - const AudioTimeStamp & inTimeStamp, - AudioUnitElement inElement, - UInt32 inNumberFrames); - - /*! @method PullInputWithBufferList */ - OSStatus PullInputWithBufferList( AudioUnitRenderActionFlags & ioActionFlags, - const AudioTimeStamp & inTimeStamp, - AudioUnitElement inElement, - UInt32 nFrames, - AudioBufferList * inBufferList); -protected: - /*! @method Disconnect */ - void Disconnect(); - - enum EInputType { kNoInput, kFromConnection, kFromCallback }; - - /*! @var mInputType */ - EInputType mInputType; - - // if from callback: - /*! @var mInputProc */ - AURenderCallback mInputProc; - /*! @var mInputProcRefCon */ - void * mInputProcRefCon; - - // if from connection: - /*! @var mConnection */ - AudioUnitConnection mConnection; -#if !CA_USE_AUDIO_PLUGIN_ONLY - /*! @var mConnRenderProc */ - AudioUnitRenderProc mConnRenderProc; -#endif - /*! @var mConnInstanceStorage */ - void * mConnInstanceStorage; // for the input component -}; - - -#endif // __AUInput_h__ diff --git a/src/CoreAudio/CoreAudioComponent/AUPublic/AUBase/AUOutputElement.cpp b/src/CoreAudio/CoreAudioComponent/AUPublic/AUBase/AUOutputElement.cpp deleted file mode 100644 index 5eb34a1c2..000000000 --- a/src/CoreAudio/CoreAudioComponent/AUPublic/AUBase/AUOutputElement.cpp +++ /dev/null @@ -1,62 +0,0 @@ -/* - File: AUOutputElement.cpp - Abstract: AUOutputElement.h - Version: 1.1 - - Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple - Inc. ("Apple") in consideration of your agreement to the following - terms, and your use, installation, modification or redistribution of - this Apple software constitutes acceptance of these terms. If you do - not agree with these terms, please do not use, install, modify or - redistribute this Apple software. - - In consideration of your agreement to abide by the following terms, and - subject to these terms, Apple grants you a personal, non-exclusive - license, under Apple's copyrights in this original Apple software (the - "Apple Software"), to use, reproduce, modify and redistribute the Apple - Software, with or without modifications, in source and/or binary forms; - provided that if you redistribute the Apple Software in its entirety and - without modifications, you must retain this notice and the following - text and disclaimers in all such redistributions of the Apple Software. - Neither the name, trademarks, service marks or logos of Apple Inc. may - be used to endorse or promote products derived from the Apple Software - without specific prior written permission from Apple. Except as - expressly stated in this notice, no other rights or licenses, express or - implied, are granted by Apple herein, including but not limited to any - patent rights that may be infringed by your derivative works or by other - works in which the Apple Software may be incorporated. - - The Apple Software is provided by Apple on an "AS IS" basis. APPLE - MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION - THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS - FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND - OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS. - - IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL - OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, - MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED - AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), - STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE - POSSIBILITY OF SUCH DAMAGE. - - Copyright (C) 2014 Apple Inc. All Rights Reserved. - -*/ -#include "AUOutputElement.h" -#include "AUBase.h" - -AUOutputElement::AUOutputElement(AUBase *audioUnit) : - AUIOElement(audioUnit) -{ - AllocateBuffer(); -} - -OSStatus AUOutputElement::SetStreamFormat(const CAStreamBasicDescription &desc) -{ - OSStatus result = AUIOElement::SetStreamFormat(desc); // inherited - if (result == AUBase::noErr) - AllocateBuffer(); - return result; -} diff --git a/src/CoreAudio/CoreAudioComponent/AUPublic/AUBase/AUOutputElement.h b/src/CoreAudio/CoreAudioComponent/AUPublic/AUBase/AUOutputElement.h deleted file mode 100644 index 3e6a938ff..000000000 --- a/src/CoreAudio/CoreAudioComponent/AUPublic/AUBase/AUOutputElement.h +++ /dev/null @@ -1,66 +0,0 @@ -/* - File: AUOutputElement.h - Abstract: Part of CoreAudio Utility Classes - Version: 1.1 - - Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple - Inc. ("Apple") in consideration of your agreement to the following - terms, and your use, installation, modification or redistribution of - this Apple software constitutes acceptance of these terms. If you do - not agree with these terms, please do not use, install, modify or - redistribute this Apple software. - - In consideration of your agreement to abide by the following terms, and - subject to these terms, Apple grants you a personal, non-exclusive - license, under Apple's copyrights in this original Apple software (the - "Apple Software"), to use, reproduce, modify and redistribute the Apple - Software, with or without modifications, in source and/or binary forms; - provided that if you redistribute the Apple Software in its entirety and - without modifications, you must retain this notice and the following - text and disclaimers in all such redistributions of the Apple Software. - Neither the name, trademarks, service marks or logos of Apple Inc. may - be used to endorse or promote products derived from the Apple Software - without specific prior written permission from Apple. Except as - expressly stated in this notice, no other rights or licenses, express or - implied, are granted by Apple herein, including but not limited to any - patent rights that may be infringed by your derivative works or by other - works in which the Apple Software may be incorporated. - - The Apple Software is provided by Apple on an "AS IS" basis. APPLE - MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION - THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS - FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND - OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS. - - IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL - OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, - MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED - AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), - STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE - POSSIBILITY OF SUCH DAMAGE. - - Copyright (C) 2014 Apple Inc. All Rights Reserved. - -*/ -#ifndef __AUOutput_h__ -#define __AUOutput_h__ - -#include "AUScopeElement.h" -#include "AUBuffer.h" - - /*! @class AUOutputElement */ -class AUOutputElement : public AUIOElement { -public: - /*! @ctor AUOutputElement */ - AUOutputElement(AUBase *audioUnit); - - // AUElement override - /*! @method SetStreamFormat */ - virtual OSStatus SetStreamFormat(const CAStreamBasicDescription &desc); - /*! @method NeedsBufferSpace */ - virtual bool NeedsBufferSpace() const { return true; } -}; - -#endif // __AUOutput_h__ diff --git a/src/CoreAudio/CoreAudioComponent/AUPublic/AUBase/AUPlugInDispatch.cpp b/src/CoreAudio/CoreAudioComponent/AUPublic/AUBase/AUPlugInDispatch.cpp deleted file mode 100644 index 3bab19836..000000000 --- a/src/CoreAudio/CoreAudioComponent/AUPublic/AUBase/AUPlugInDispatch.cpp +++ /dev/null @@ -1,669 +0,0 @@ -/* - File: AUPlugInDispatch.cpp - Abstract: AUPlugInDispatch.h - Version: 1.1 - - Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple - Inc. ("Apple") in consideration of your agreement to the following - terms, and your use, installation, modification or redistribution of - this Apple software constitutes acceptance of these terms. If you do - not agree with these terms, please do not use, install, modify or - redistribute this Apple software. - - In consideration of your agreement to abide by the following terms, and - subject to these terms, Apple grants you a personal, non-exclusive - license, under Apple's copyrights in this original Apple software (the - "Apple Software"), to use, reproduce, modify and redistribute the Apple - Software, with or without modifications, in source and/or binary forms; - provided that if you redistribute the Apple Software in its entirety and - without modifications, you must retain this notice and the following - text and disclaimers in all such redistributions of the Apple Software. - Neither the name, trademarks, service marks or logos of Apple Inc. may - be used to endorse or promote products derived from the Apple Software - without specific prior written permission from Apple. Except as - expressly stated in this notice, no other rights or licenses, express or - implied, are granted by Apple herein, including but not limited to any - patent rights that may be infringed by your derivative works or by other - works in which the Apple Software may be incorporated. - - The Apple Software is provided by Apple on an "AS IS" basis. APPLE - MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION - THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS - FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND - OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS. - - IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL - OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, - MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED - AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), - STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE - POSSIBILITY OF SUCH DAMAGE. - - Copyright (C) 2014 Apple Inc. All Rights Reserved. - -*/ -#include "AUPlugInDispatch.h" -#include "CAXException.h" -#include "ComponentBase.h" -#include "AUBase.h" - -#define ACPI ((AudioComponentPlugInInstance *)self) -#define AUI ((AUBase *)&ACPI->mInstanceStorage) - -#define AUI_LOCK CAMutex::Locker auLock(AUI->GetMutex()); - -// ------------------------------------------------------------------------------------------------ -static OSStatus AUMethodInitialize(void *self) -{ - OSStatus result = noErr; - try { - AUI_LOCK - result = AUI->DoInitialize(); - } - COMPONENT_CATCH - return result; -} - -static OSStatus AUMethodUninitialize(void *self) -{ - OSStatus result = noErr; - try { - AUI_LOCK - AUI->DoCleanup(); - } - COMPONENT_CATCH - return result; -} - -static OSStatus AUMethodGetPropertyInfo(void *self, AudioUnitPropertyID prop, AudioUnitScope scope, AudioUnitElement elem, UInt32 *outDataSize, Boolean *outWritable) -{ - OSStatus result = noErr; - try { - UInt32 dataSize = 0; // 13517289 GetPropetyInfo was returning an uninitialized value when there is an error. This is a problem for auval. - Boolean writable = false; - - AUI_LOCK - result = AUI->DispatchGetPropertyInfo(prop, scope, elem, dataSize, writable); - if (outDataSize != NULL) - *outDataSize = dataSize; - if (outWritable != NULL) - *outWritable = writable; - } - COMPONENT_CATCH - return result; -} - -static OSStatus AUMethodGetProperty(void *self, AudioUnitPropertyID inID, AudioUnitScope inScope, AudioUnitElement inElement, void *outData, UInt32 *ioDataSize) -{ - OSStatus result = noErr; - try { - UInt32 actualPropertySize, clientBufferSize; - Boolean writable; - char *tempBuffer; - void *destBuffer; - - AUI_LOCK - if (ioDataSize == NULL) { - ca_debug_string("AudioUnitGetProperty: null size pointer"); - result = kAudio_ParamError; - goto finishGetProperty; - } - if (outData == NULL) { - UInt32 dataSize; - - result = AUI->DispatchGetPropertyInfo(inID, inScope, inElement, dataSize, writable); - *ioDataSize = dataSize; - goto finishGetProperty; - } - - clientBufferSize = *ioDataSize; - if (clientBufferSize == 0) - { - ca_debug_string("AudioUnitGetProperty: *ioDataSize == 0 on entry"); - // $$$ or should we allow this as a shortcut for finding the size? - result = kAudio_ParamError; - goto finishGetProperty; - } - - result = AUI->DispatchGetPropertyInfo(inID, inScope, inElement, actualPropertySize, writable); - if (result != noErr) - goto finishGetProperty; - - if (clientBufferSize < actualPropertySize) - { - tempBuffer = new char[actualPropertySize]; - destBuffer = tempBuffer; - } else { - tempBuffer = NULL; - destBuffer = outData; - } - - result = AUI->DispatchGetProperty(inID, inScope, inElement, destBuffer); - - if (result == noErr) { - if (clientBufferSize < actualPropertySize && tempBuffer != NULL) - { - memcpy(outData, tempBuffer, clientBufferSize); - delete[] tempBuffer; - // ioDataSize remains correct, the number of bytes we wrote - } else - *ioDataSize = actualPropertySize; - } else - *ioDataSize = 0; - } - COMPONENT_CATCH -finishGetProperty: - return result; -} - -static OSStatus AUMethodSetProperty(void *self, AudioUnitPropertyID inID, AudioUnitScope inScope, AudioUnitElement inElement, const void *inData, UInt32 inDataSize) -{ - OSStatus result = noErr; - try { - AUI_LOCK - if (inData && inDataSize) - result = AUI->DispatchSetProperty(inID, inScope, inElement, inData, inDataSize); - else { - if (inData == NULL && inDataSize == 0) { - result = AUI->DispatchRemovePropertyValue(inID, inScope, inElement); - } else { - if (inData == NULL) { - ca_debug_string("AudioUnitSetProperty: inData == NULL"); - result = kAudio_ParamError; - goto finishSetProperty; - } - - if (inDataSize == 0) { - ca_debug_string("AudioUnitSetProperty: inDataSize == 0"); - result = kAudio_ParamError; - goto finishSetProperty; - } - } - } - } - COMPONENT_CATCH -finishSetProperty: - return result; -} - -static OSStatus AUMethodAddPropertyListener(void *self, AudioUnitPropertyID prop, AudioUnitPropertyListenerProc proc, void *userData) -{ - OSStatus result = noErr; - try { - AUI_LOCK - result = AUI->AddPropertyListener(prop, proc, userData); - } - COMPONENT_CATCH - return result; -} - -static OSStatus AUMethodRemovePropertyListener(void *self, AudioUnitPropertyID prop, AudioUnitPropertyListenerProc proc) -{ - OSStatus result = noErr; - try { - AUI_LOCK - result = AUI->RemovePropertyListener(prop, proc, NULL, false); - } - COMPONENT_CATCH - return result; -} - -static OSStatus AUMethodRemovePropertyListenerWithUserData(void *self, AudioUnitPropertyID prop, AudioUnitPropertyListenerProc proc, void *userData) -{ - OSStatus result = noErr; - try { - AUI_LOCK - result = AUI->RemovePropertyListener(prop, proc, userData, true); - } - COMPONENT_CATCH - return result; -} - -static OSStatus AUMethodAddRenderNotify(void *self, AURenderCallback proc, void *userData) -{ - OSStatus result = noErr; - try { - AUI_LOCK - result = AUI->SetRenderNotification(proc, userData); - } - COMPONENT_CATCH - return result; -} - -static OSStatus AUMethodRemoveRenderNotify(void *self, AURenderCallback proc, void *userData) -{ - OSStatus result = noErr; - try { - AUI_LOCK - result = AUI->RemoveRenderNotification(proc, userData); - } - COMPONENT_CATCH - return result; -} - -static OSStatus AUMethodGetParameter(void *self, AudioUnitParameterID param, AudioUnitScope scope, AudioUnitElement elem, AudioUnitParameterValue *value) -{ - OSStatus result = noErr; - try { - AUI_LOCK - result = (value == NULL ? kAudio_ParamError : AUI->GetParameter(param, scope, elem, *value)); - } - COMPONENT_CATCH - return result; -} - -static OSStatus AUMethodSetParameter(void *self, AudioUnitParameterID param, AudioUnitScope scope, AudioUnitElement elem, AudioUnitParameterValue value, UInt32 bufferOffset) -{ - OSStatus result = noErr; - try { - // this is a (potentially) realtime method; no lock - result = AUI->SetParameter(param, scope, elem, value, bufferOffset); - } - COMPONENT_CATCH - return result; -} - -static OSStatus AUMethodScheduleParameters(void *self, const AudioUnitParameterEvent *events, UInt32 numEvents) -{ - OSStatus result = noErr; - try { - // this is a (potentially) realtime method; no lock - result = AUI->ScheduleParameter(events, numEvents); - } - COMPONENT_CATCH - return result; -} - -static OSStatus AUMethodRender(void *self, AudioUnitRenderActionFlags *ioActionFlags, const AudioTimeStamp *inTimeStamp, UInt32 inOutputBusNumber, UInt32 inNumberFrames, AudioBufferList *ioData) -{ - OSStatus result = noErr; - -#if !TARGET_OS_IPHONE - try { -#endif - // this is a processing method; no lock - AudioUnitRenderActionFlags tempFlags; - - if (inTimeStamp == NULL || ioData == NULL) - result = kAudio_ParamError; - else { - if (ioActionFlags == NULL) { - tempFlags = 0; - ioActionFlags = &tempFlags; - } - result = AUI->DoRender(*ioActionFlags, *inTimeStamp, inOutputBusNumber, inNumberFrames, *ioData); - } - -#if !TARGET_OS_IPHONE - } - COMPONENT_CATCH -#endif - - return result; -} - -static OSStatus AUMethodComplexRender(void *self, AudioUnitRenderActionFlags *ioActionFlags, const AudioTimeStamp *inTimeStamp, UInt32 inOutputBusNumber, UInt32 inNumberOfPackets, UInt32 *outNumberOfPackets, AudioStreamPacketDescription *outPacketDescriptions, AudioBufferList *ioData, void *outMetadata, UInt32 *outMetadataByteSize) -{ - OSStatus result = noErr; - -#if !TARGET_OS_IPHONE - try { -#endif - // this is a processing method; no lock - AudioUnitRenderActionFlags tempFlags; - - if (inTimeStamp == NULL || ioData == NULL) - result = kAudio_ParamError; - else { - if (ioActionFlags == NULL) { - tempFlags = 0; - ioActionFlags = &tempFlags; - } - result = AUI->ComplexRender(*ioActionFlags, *inTimeStamp, inOutputBusNumber, inNumberOfPackets, outNumberOfPackets, outPacketDescriptions, *ioData, outMetadata, outMetadataByteSize); - } - -#if !TARGET_OS_IPHONE - } - COMPONENT_CATCH -#endif - - return result; -} - -static OSStatus AUMethodReset(void *self, AudioUnitScope scope, AudioUnitElement elem) -{ - OSStatus result = noErr; - try { - AUI_LOCK - result = AUI->Reset(scope, elem); - } - COMPONENT_CATCH - return result; -} - -static OSStatus AUMethodProcess (void *self, AudioUnitRenderActionFlags *ioActionFlags, const AudioTimeStamp *inTimeStamp, UInt32 inNumberFrames, AudioBufferList *ioData) -{ - OSStatus result = noErr; - -#if !TARGET_OS_IPHONE - try { -#endif - // this is a processing method; no lock - bool doParamCheck = true; - - AudioUnitRenderActionFlags tempFlags; - - if (ioActionFlags == NULL) { - tempFlags = 0; - ioActionFlags = &tempFlags; - } else { - if (*ioActionFlags & (1 << 9)/*kAudioUnitRenderAction_DoNotCheckRenderArgs*/) - doParamCheck = false; - } - - if (doParamCheck && (inTimeStamp == NULL || ioData == NULL)) - result = kAudio_ParamError; - else { - result = AUI->DoProcess(*ioActionFlags, *inTimeStamp, inNumberFrames, *ioData); - } - -#if !TARGET_OS_IPHONE - } - COMPONENT_CATCH -#endif - - return result; -} - -static OSStatus AUMethodProcessMultiple (void *self, AudioUnitRenderActionFlags *ioActionFlags, const AudioTimeStamp *inTimeStamp, UInt32 inNumberFrames, UInt32 inNumberInputBufferLists, const AudioBufferList **inInputBufferLists, UInt32 inNumberOutputBufferLists, AudioBufferList **ioOutputBufferLists) -{ - OSStatus result = noErr; - -#if !TARGET_OS_IPHONE - try { -#endif - // this is a processing method; no lock - bool doParamCheck = true; - - AudioUnitRenderActionFlags tempFlags; - - if (ioActionFlags == NULL) { - tempFlags = 0; - ioActionFlags = &tempFlags; - } else { - if (*ioActionFlags & (1 << 9)/*kAudioUnitRenderAction_DoNotCheckRenderArgs*/) - doParamCheck = false; - } - - if (doParamCheck && (inTimeStamp == NULL || inInputBufferLists == NULL || ioOutputBufferLists == NULL)) - result = kAudio_ParamError; - else { - result = AUI->DoProcessMultiple(*ioActionFlags, *inTimeStamp, inNumberFrames, inNumberInputBufferLists, inInputBufferLists, inNumberOutputBufferLists, ioOutputBufferLists); - } - -#if !TARGET_OS_IPHONE - } - COMPONENT_CATCH -#endif - - return result; -} -// ------------------------------------------------------------------------------------------------ - -static OSStatus AUMethodStart(void *self) -{ - OSStatus result = noErr; - try { - AUI_LOCK - result = AUI->Start(); - } - COMPONENT_CATCH - return result; -} - -static OSStatus AUMethodStop(void *self) -{ - OSStatus result = noErr; - try { - AUI_LOCK - result = AUI->Stop(); - } - COMPONENT_CATCH - return result; -} - -// ------------------------------------------------------------------------------------------------ - -#if !CA_BASIC_AU_FEATURES -// I don't know what I'm doing here; conflicts with the multiple inheritence in MusicDeviceBase. -static OSStatus AUMethodMIDIEvent(void *self, UInt32 inStatus, UInt32 inData1, UInt32 inData2, UInt32 inOffsetSampleFrame) -{ - OSStatus result = noErr; - try { - // this is a potential render-time method; no lock - result = AUI->MIDIEvent(inStatus, inData1, inData2, inOffsetSampleFrame); - } - COMPONENT_CATCH - return result; -} - -static OSStatus AUMethodSysEx(void *self, const UInt8 *inData, UInt32 inLength) -{ - OSStatus result = noErr; - try { - // this is a potential render-time method; no lock - result = AUI->SysEx(inData, inLength); - } - COMPONENT_CATCH - return result; -} - -static OSStatus AUMethodStartNote(void *self, MusicDeviceInstrumentID inInstrument, MusicDeviceGroupID inGroupID, NoteInstanceID *outNoteInstanceID, UInt32 inOffsetSampleFrame, const MusicDeviceNoteParams *inParams) -{ - OSStatus result = noErr; - try { - // this is a potential render-time method; no lock - if (inParams == NULL || outNoteInstanceID == NULL) - result = kAudio_ParamError; - else - result = AUI->StartNote(inInstrument, inGroupID, outNoteInstanceID, inOffsetSampleFrame, *inParams); - } - COMPONENT_CATCH - return result; -} - -static OSStatus AUMethodStopNote(void *self, MusicDeviceGroupID inGroupID, NoteInstanceID inNoteInstanceID, UInt32 inOffsetSampleFrame) -{ - OSStatus result = noErr; - try { - // this is a potential render-time method; no lock - result = AUI->StopNote(inGroupID, inNoteInstanceID, inOffsetSampleFrame); - } - COMPONENT_CATCH - return result; -} - -#if !TARGET_OS_IPHONE -static OSStatus AUMethodPrepareInstrument (void *self, MusicDeviceInstrumentID inInstrument) -{ - OSStatus result = noErr; - try { - // this is a potential render-time method; no lock - result = AUI->PrepareInstrument(inInstrument); - } - COMPONENT_CATCH - return result; -} - -static OSStatus AUMethodReleaseInstrument (void *self, MusicDeviceInstrumentID inInstrument) -{ - OSStatus result = noErr; - try { - // this is a potential render-time method; no lock - result = AUI->ReleaseInstrument(inInstrument); - } - COMPONENT_CATCH - return result; -} -#endif // TARGET_OS_IPHONE -#endif // CA_BASIC_AU_FEATURES - - -//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -#pragma mark - -#pragma mark Lookup Methods - -AudioComponentMethod AUBaseLookup::Lookup (SInt16 selector) -{ - switch (selector) { - case kAudioUnitInitializeSelect: return (AudioComponentMethod)AUMethodInitialize; - case kAudioUnitUninitializeSelect: return (AudioComponentMethod)AUMethodUninitialize; - case kAudioUnitGetPropertyInfoSelect: return (AudioComponentMethod)AUMethodGetPropertyInfo; - case kAudioUnitGetPropertySelect: return (AudioComponentMethod)AUMethodGetProperty; - case kAudioUnitSetPropertySelect: return (AudioComponentMethod)AUMethodSetProperty; - case kAudioUnitAddPropertyListenerSelect:return (AudioComponentMethod)AUMethodAddPropertyListener; - case kAudioUnitRemovePropertyListenerSelect: - return (AudioComponentMethod)AUMethodRemovePropertyListener; - case kAudioUnitRemovePropertyListenerWithUserDataSelect: - return (AudioComponentMethod)AUMethodRemovePropertyListenerWithUserData; - case kAudioUnitAddRenderNotifySelect: return (AudioComponentMethod)AUMethodAddRenderNotify; - case kAudioUnitRemoveRenderNotifySelect:return (AudioComponentMethod)AUMethodRemoveRenderNotify; - case kAudioUnitGetParameterSelect: return (AudioComponentMethod)AUMethodGetParameter; - case kAudioUnitSetParameterSelect: return (AudioComponentMethod)AUMethodSetParameter; - case kAudioUnitScheduleParametersSelect:return (AudioComponentMethod)AUMethodScheduleParameters; - case kAudioUnitRenderSelect: return (AudioComponentMethod)AUMethodRender; - case kAudioUnitResetSelect: return (AudioComponentMethod)AUMethodReset; - default: - break; - } - return NULL; -} - -AudioComponentMethod AUOutputLookup::Lookup (SInt16 selector) -{ - AudioComponentMethod method = AUBaseLookup::Lookup(selector); - if (method) return method; - - switch (selector) { - case kAudioOutputUnitStartSelect: return (AudioComponentMethod)AUMethodStart; - case kAudioOutputUnitStopSelect: return (AudioComponentMethod)AUMethodStop; - default: - break; - } - return NULL; -} - -AudioComponentMethod AUComplexOutputLookup::Lookup (SInt16 selector) -{ - AudioComponentMethod method = AUBaseLookup::Lookup(selector); - if (method) return method; - - method = AUOutputLookup::Lookup(selector); - if (method) return method; - - if (selector == kAudioUnitComplexRenderSelect) - return (AudioComponentMethod)AUMethodComplexRender; - return NULL; -} - -AudioComponentMethod AUBaseProcessLookup::Lookup (SInt16 selector) -{ - AudioComponentMethod method = AUBaseLookup::Lookup(selector); - if (method) return method; - - if (selector == kAudioUnitProcessSelect) - return (AudioComponentMethod)AUMethodProcess; - - return NULL; -} - -AudioComponentMethod AUBaseProcessMultipleLookup::Lookup (SInt16 selector) -{ - AudioComponentMethod method = AUBaseLookup::Lookup(selector); - if (method) return method; - - if (selector == kAudioUnitProcessMultipleSelect) - return (AudioComponentMethod)AUMethodProcessMultiple; - - return NULL; -} - -AudioComponentMethod AUBaseProcessAndMultipleLookup::Lookup (SInt16 selector) -{ - AudioComponentMethod method = AUBaseLookup::Lookup(selector); - if (method) return method; - - method = AUBaseProcessMultipleLookup::Lookup(selector); - if (method) return method; - - method = AUBaseProcessLookup::Lookup(selector); - if (method) return method; - - return NULL; -} - -#if !CA_BASIC_AU_FEATURES -inline AudioComponentMethod MIDI_Lookup (SInt16 selector) -{ - switch (selector) { - case kMusicDeviceMIDIEventSelect: return (AudioComponentMethod)AUMethodMIDIEvent; - case kMusicDeviceSysExSelect: return (AudioComponentMethod)AUMethodSysEx; - default: - break; - } - return NULL; -} - -AudioComponentMethod AUMIDILookup::Lookup (SInt16 selector) -{ - AudioComponentMethod method = AUBaseLookup::Lookup(selector); - if (method) return method; - - return MIDI_Lookup(selector); -} - -AudioComponentMethod AUMIDIProcessLookup::Lookup (SInt16 selector) -{ - AudioComponentMethod method = AUBaseProcessLookup::Lookup(selector); - if (method) return method; - - return MIDI_Lookup(selector); -} - -AudioComponentMethod AUMusicLookup::Lookup (SInt16 selector) -{ - AudioComponentMethod method = AUBaseLookup::Lookup(selector); - if (method) return method; - - switch (selector) { - case kMusicDeviceStartNoteSelect: return (AudioComponentMethod)AUMethodStartNote; - case kMusicDeviceStopNoteSelect: return (AudioComponentMethod)AUMethodStopNote; -#if !TARGET_OS_IPHONE - case kMusicDevicePrepareInstrumentSelect: return (AudioComponentMethod)AUMethodPrepareInstrument; - case kMusicDeviceReleaseInstrumentSelect: return (AudioComponentMethod)AUMethodReleaseInstrument; -#endif - default: - break; - } - return MIDI_Lookup (selector); -} - -AudioComponentMethod AUAuxBaseLookup::Lookup (SInt16 selector) -{ - switch (selector) { - case kAudioUnitGetPropertyInfoSelect: return (AudioComponentMethod)AUMethodGetPropertyInfo; - case kAudioUnitGetPropertySelect: return (AudioComponentMethod)AUMethodGetProperty; - case kAudioUnitSetPropertySelect: return (AudioComponentMethod)AUMethodSetProperty; - - case kAudioUnitGetParameterSelect: return (AudioComponentMethod)AUMethodGetParameter; - case kAudioUnitSetParameterSelect: return (AudioComponentMethod)AUMethodSetParameter; - - default: - break; - } - return NULL; -} -#endif - diff --git a/src/CoreAudio/CoreAudioComponent/AUPublic/AUBase/AUPlugInDispatch.h b/src/CoreAudio/CoreAudioComponent/AUPublic/AUBase/AUPlugInDispatch.h deleted file mode 100644 index 6ebea75fd..000000000 --- a/src/CoreAudio/CoreAudioComponent/AUPublic/AUBase/AUPlugInDispatch.h +++ /dev/null @@ -1,144 +0,0 @@ -/* - File: AUPlugInDispatch.h - Abstract: Part of CoreAudio Utility Classes - Version: 1.1 - - Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple - Inc. ("Apple") in consideration of your agreement to the following - terms, and your use, installation, modification or redistribution of - this Apple software constitutes acceptance of these terms. If you do - not agree with these terms, please do not use, install, modify or - redistribute this Apple software. - - In consideration of your agreement to abide by the following terms, and - subject to these terms, Apple grants you a personal, non-exclusive - license, under Apple's copyrights in this original Apple software (the - "Apple Software"), to use, reproduce, modify and redistribute the Apple - Software, with or without modifications, in source and/or binary forms; - provided that if you redistribute the Apple Software in its entirety and - without modifications, you must retain this notice and the following - text and disclaimers in all such redistributions of the Apple Software. - Neither the name, trademarks, service marks or logos of Apple Inc. may - be used to endorse or promote products derived from the Apple Software - without specific prior written permission from Apple. Except as - expressly stated in this notice, no other rights or licenses, express or - implied, are granted by Apple herein, including but not limited to any - patent rights that may be infringed by your derivative works or by other - works in which the Apple Software may be incorporated. - - The Apple Software is provided by Apple on an "AS IS" basis. APPLE - MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION - THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS - FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND - OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS. - - IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL - OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, - MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED - AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), - STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE - POSSIBILITY OF SUCH DAMAGE. - - Copyright (C) 2014 Apple Inc. All Rights Reserved. - -*/ -#ifndef __AUPlugInBase_h__ -#define __AUPlugInBase_h__ - -#if !defined(__COREAUDIO_USE_FLAT_INCLUDES__) - #include - #if !CA_BASIC_AU_FEATURES - #include - #endif -#else - #include "AudioComponent.h" - #include "MusicDevice.h" -#endif - -#include "ComponentBase.h" - -struct AUBaseLookup { - static AudioComponentMethod Lookup (SInt16 selector); -}; -template -class AUBaseFactory : public APFactory -{ -}; - -struct AUOutputLookup { - static AudioComponentMethod Lookup (SInt16 selector); -}; -template -class AUOutputBaseFactory : public APFactory -{ -}; - -struct AUComplexOutputLookup { - static AudioComponentMethod Lookup (SInt16 selector); -}; -template -class AUOutputComplexBaseFactory : public APFactory -{ -}; - -struct AUBaseProcessLookup { - static AudioComponentMethod Lookup (SInt16 selector); -}; -template -class AUBaseProcessFactory : public APFactory -{ -}; - -struct AUBaseProcessMultipleLookup { - static AudioComponentMethod Lookup (SInt16 selector); -}; -template -class AUBaseProcessMultipleFactory : public APFactory -{ -}; - -struct AUBaseProcessAndMultipleLookup { - static AudioComponentMethod Lookup (SInt16 selector); -}; -template -class AUBaseProcessAndMultipleFactory : public APFactory -{ -}; - -#if !CA_BASIC_AU_FEATURES -struct AUMIDILookup { - static AudioComponentMethod Lookup (SInt16 selector); -}; -template -class AUMIDIEffectFactory : public APFactory -{ -}; - -struct AUMIDIProcessLookup { - static AudioComponentMethod Lookup (SInt16 selector); -}; -template -class AUMIDIProcessFactory : public APFactory -{ -}; - -struct AUMusicLookup { - static AudioComponentMethod Lookup (SInt16 selector); -}; -template -class AUMusicDeviceFactory : public APFactory -{ -}; - -struct AUAuxBaseLookup { - static AudioComponentMethod Lookup (SInt16 selector); -}; -template -class AUAuxBaseFactory : public APFactory -{ -}; -#endif // CA_BASIC_AU_FEATURES - -#endif // __AUPlugInBase_h__ diff --git a/src/CoreAudio/CoreAudioComponent/AUPublic/AUBase/AUScopeElement.cpp b/src/CoreAudio/CoreAudioComponent/AUPublic/AUBase/AUScopeElement.cpp deleted file mode 100644 index 24bd18e43..000000000 --- a/src/CoreAudio/CoreAudioComponent/AUPublic/AUBase/AUScopeElement.cpp +++ /dev/null @@ -1,565 +0,0 @@ -/* - File: AUScopeElement.cpp - Abstract: AUScopeElement.h - Version: 1.1 - - Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple - Inc. ("Apple") in consideration of your agreement to the following - terms, and your use, installation, modification or redistribution of - this Apple software constitutes acceptance of these terms. If you do - not agree with these terms, please do not use, install, modify or - redistribute this Apple software. - - In consideration of your agreement to abide by the following terms, and - subject to these terms, Apple grants you a personal, non-exclusive - license, under Apple's copyrights in this original Apple software (the - "Apple Software"), to use, reproduce, modify and redistribute the Apple - Software, with or without modifications, in source and/or binary forms; - provided that if you redistribute the Apple Software in its entirety and - without modifications, you must retain this notice and the following - text and disclaimers in all such redistributions of the Apple Software. - Neither the name, trademarks, service marks or logos of Apple Inc. may - be used to endorse or promote products derived from the Apple Software - without specific prior written permission from Apple. Except as - expressly stated in this notice, no other rights or licenses, express or - implied, are granted by Apple herein, including but not limited to any - patent rights that may be infringed by your derivative works or by other - works in which the Apple Software may be incorporated. - - The Apple Software is provided by Apple on an "AS IS" basis. APPLE - MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION - THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS - FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND - OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS. - - IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL - OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, - MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED - AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), - STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE - POSSIBILITY OF SUCH DAMAGE. - - Copyright (C) 2014 Apple Inc. All Rights Reserved. - -*/ -#include "AUScopeElement.h" -#include "AUBase.h" - -//_____________________________________________________________________________ -// -// By default, parameterIDs may be arbitrarily spaced, and an STL map -// will be used for access. Calling UseIndexedParameters() will -// instead use an STL vector for faster indexed access. -// This assumes the paramIDs are numbered 0.....inNumberOfParameters-1 -// Call this before defining/adding any parameters with SetParameter() -// -void AUElement::UseIndexedParameters(int inNumberOfParameters) -{ - mIndexedParameters.resize (inNumberOfParameters); - mUseIndexedParameters = true; -} - -//_____________________________________________________________________________ -// -// Helper method. -// returns the ParameterMapEvent object associated with the paramID -// -inline ParameterMapEvent& AUElement::GetParamEvent(AudioUnitParameterID paramID) -{ - ParameterMapEvent *event; - - if(mUseIndexedParameters) - { - if(paramID >= mIndexedParameters.size() ) - COMPONENT_THROW(kAudioUnitErr_InvalidParameter); - - event = &mIndexedParameters[paramID]; - } - else - { - ParameterMap::iterator i = mParameters.find(paramID); - if (i == mParameters.end()) - COMPONENT_THROW(kAudioUnitErr_InvalidParameter); - - event = &(*i).second; - } - - return *event; -} - -//_____________________________________________________________________________ -// -// Helper method. -// returns whether the specified paramID is known to the element -// -bool AUElement::HasParameterID (AudioUnitParameterID paramID) const -{ - if(mUseIndexedParameters) - { - if(paramID >= mIndexedParameters.size() ) - return false; - - return true; - } - - ParameterMap::const_iterator i = mParameters.find(paramID); - if (i == mParameters.end()) - return false; - - return true; -} - -//_____________________________________________________________________________ -// -// caller assumes that this is actually an immediate parameter -// -AudioUnitParameterValue AUElement::GetParameter(AudioUnitParameterID paramID) -{ - ParameterMapEvent &event = GetParamEvent(paramID); - - return event.GetValue(); -} - - -//_____________________________________________________________________________ -// -void AUElement::GetRampSliceStartEnd( AudioUnitParameterID paramID, - AudioUnitParameterValue & outStartValue, - AudioUnitParameterValue & outEndValue, - AudioUnitParameterValue & outValuePerFrameDelta ) - -{ - ParameterMapEvent &event = GetParamEvent(paramID); - - // works even if the value is constant (immediate parameter value) - event.GetRampSliceStartEnd(outStartValue, outEndValue, outValuePerFrameDelta ); -} - -//_____________________________________________________________________________ -// -AudioUnitParameterValue AUElement::GetEndValue( AudioUnitParameterID paramID) - -{ - ParameterMapEvent &event = GetParamEvent(paramID); - - // works even if the value is constant (immediate parameter value) - return event.GetEndValue(); -} - -//_____________________________________________________________________________ -// -void AUElement::SetParameter(AudioUnitParameterID paramID, AudioUnitParameterValue inValue, bool okWhenInitialized) -{ - if(mUseIndexedParameters) - { - ParameterMapEvent &event = GetParamEvent(paramID); - event.SetValue(inValue); - } - else - { - ParameterMap::iterator i = mParameters.find(paramID); - - if (i == mParameters.end()) - { - if (mAudioUnit->IsInitialized() && !okWhenInitialized) { - // The AU should not be creating new parameters once initialized. - // If a client tries to set an undefined parameter, we could throw as follows, - // but this might cause a regression. So it is better to just fail silently. - // COMPONENT_THROW(kAudioUnitErr_InvalidParameter); -#if DEBUG - fprintf(stderr, "WARNING: %s SetParameter for undefined param ID %d while initialized. Ignoring..\n", - mAudioUnit->GetLoggingString(), (int)paramID); -#endif - } else { - // create new entry in map for the paramID (only happens first time) - ParameterMapEvent event(inValue); - mParameters[paramID] = event; - } - } - else - { - // paramID already exists in map so simply change its value - ParameterMapEvent &event = (*i).second; - event.SetValue(inValue); - } - } -} - -//_____________________________________________________________________________ -// -void AUElement::SetScheduledEvent( AudioUnitParameterID paramID, - const AudioUnitParameterEvent &inEvent, - UInt32 inSliceOffsetInBuffer, - UInt32 inSliceDurationFrames, - bool okWhenInitialized ) -{ - if(mUseIndexedParameters) - { - ParameterMapEvent &event = GetParamEvent(paramID); - event.SetScheduledEvent(inEvent, inSliceOffsetInBuffer, inSliceDurationFrames ); - } - else - { - ParameterMap::iterator i = mParameters.find(paramID); - - if (i == mParameters.end()) - { - if (mAudioUnit->IsInitialized() && !okWhenInitialized) { - // The AU should not be creating new parameters once initialized. - // If a client tries to set an undefined parameter, we could throw as follows, - // but this might cause a regression. So it is better to just fail silently. - // COMPONENT_THROW(kAudioUnitErr_InvalidParameter); -#if DEBUG - fprintf(stderr, "WARNING: %s SetScheduledEvent for undefined param ID %d while initialized. Ignoring..\n", - mAudioUnit->GetLoggingString(), (int)paramID); -#endif - } else { - // create new entry in map for the paramID (only happens first time) - ParameterMapEvent event(inEvent, inSliceOffsetInBuffer, inSliceDurationFrames); - mParameters[paramID] = event; - } - } - else - { - // paramID already exists in map so simply change its value - ParameterMapEvent &event = (*i).second; - - event.SetScheduledEvent(inEvent, inSliceOffsetInBuffer, inSliceDurationFrames ); - } - } -} - - - -//_____________________________________________________________________________ -// -void AUElement::GetParameterList(AudioUnitParameterID *outList) -{ - if(mUseIndexedParameters) - { - UInt32 nparams = static_cast(mIndexedParameters.size()); - for (UInt32 i = 0; i < nparams; i++ ) - *outList++ = (AudioUnitParameterID)i; - } - else - { - for (ParameterMap::iterator i = mParameters.begin(); i != mParameters.end(); ++i) - *outList++ = (*i).first; - } -} - -//_____________________________________________________________________________ -// -void AUElement::SaveState(CFMutableDataRef data) -{ - if(mUseIndexedParameters) - { - UInt32 nparams = static_cast(mIndexedParameters.size()); - UInt32 theData = CFSwapInt32HostToBig(nparams); - CFDataAppendBytes(data, (UInt8 *)&theData, sizeof(nparams)); - - for (UInt32 i = 0; i < nparams; i++) - { - struct { - UInt32 paramID; - //CFSwappedFloat32 value; crashes gcc3 PFE - UInt32 value; // really a big-endian float - } entry; - - entry.paramID = CFSwapInt32HostToBig(i); - - AudioUnitParameterValue v = mIndexedParameters[i].GetValue(); - entry.value = CFSwapInt32HostToBig(*(UInt32 *)&v ); - - CFDataAppendBytes(data, (UInt8 *)&entry, sizeof(entry)); - } - } - else - { - UInt32 nparams = CFSwapInt32HostToBig(static_cast(mParameters.size())); - CFDataAppendBytes(data, (UInt8 *)&nparams, sizeof(nparams)); - - for (ParameterMap::iterator i = mParameters.begin(); i != mParameters.end(); ++i) { - struct { - UInt32 paramID; - //CFSwappedFloat32 value; crashes gcc3 PFE - UInt32 value; // really a big-endian float - } entry; - - entry.paramID = CFSwapInt32HostToBig((*i).first); - - AudioUnitParameterValue v = (*i).second.GetValue(); - entry.value = CFSwapInt32HostToBig(*(UInt32 *)&v ); - - CFDataAppendBytes(data, (UInt8 *)&entry, sizeof(entry)); - } - } -} - -//_____________________________________________________________________________ -// -const UInt8 * AUElement::RestoreState(const UInt8 *state) -{ - union FloatInt32 { UInt32 i; AudioUnitParameterValue f; }; - const UInt8 *p = state; - UInt32 nparams = CFSwapInt32BigToHost(*(UInt32 *)p); - p += sizeof(UInt32); - - for (UInt32 i = 0; i < nparams; ++i) { - struct { - AudioUnitParameterID paramID; - AudioUnitParameterValue value; - } entry; - - entry.paramID = CFSwapInt32BigToHost(*(UInt32 *)p); - p += sizeof(UInt32); - FloatInt32 temp; - temp.i = CFSwapInt32BigToHost(*(UInt32 *)p); - entry.value = temp.f; - p += sizeof(AudioUnitParameterValue); - - SetParameter(entry.paramID, entry.value); - } - return p; -} - -//_____________________________________________________________________________ -// -void AUElement::SetName (CFStringRef inName) -{ - if (mElementName) CFRelease (mElementName); - mElementName = inName; - if (mElementName) CFRetain (mElementName); -} - - -//_____________________________________________________________________________ -// -AUIOElement::AUIOElement(AUBase *audioUnit) : - AUElement(audioUnit), - mWillAllocate (true) -{ - mStreamFormat.SetAUCanonical(2, // stereo - audioUnit->AudioUnitAPIVersion() == 1); - // interleaved if API version 1, deinterleaved if version 2 - mStreamFormat.mSampleRate = kAUDefaultSampleRate; -} - -//_____________________________________________________________________________ -// -OSStatus AUIOElement::SetStreamFormat(const CAStreamBasicDescription &desc) -{ - mStreamFormat = desc; - return AUBase::noErr; -} - -//_____________________________________________________________________________ -// inFramesToAllocate == 0 implies the AudioUnit's max-frames-per-slice will be used -void AUIOElement::AllocateBuffer(UInt32 inFramesToAllocate) -{ - if (GetAudioUnit()->HasBegunInitializing()) - { - UInt32 framesToAllocate = inFramesToAllocate > 0 ? inFramesToAllocate : GetAudioUnit()->GetMaxFramesPerSlice(); - -// printf ("will allocate: %d\n", (int)((mWillAllocate && NeedsBufferSpace()) ? framesToAllocate : 0)); - - mIOBuffer.Allocate(mStreamFormat, (mWillAllocate && NeedsBufferSpace()) ? framesToAllocate : 0); - } -} - -//_____________________________________________________________________________ -// -void AUIOElement::DeallocateBuffer() -{ - mIOBuffer.Deallocate(); -} - -//_____________________________________________________________________________ -// -// AudioChannelLayout support - -// outLayoutTagsPtr WILL be NULL if called to find out how many -// layouts that Audio Unit will report -// return 0 (ie. NO channel layouts) if the AU doesn't require channel layout knowledge -UInt32 AUIOElement::GetChannelLayoutTags (AudioChannelLayoutTag *outLayoutTagsPtr) -{ - return 0; -} - -// As the AudioChannelLayout can be a variable length structure -// (though in most cases it won't be!!!) -// The size of the ACL is always returned by the method -// if outMapPtr is NOT-NULL, then AU should copy into this pointer (outMapPtr) the current ACL that it has in use. -// the AU should also return whether the property is writable (that is the client can provide any arbitrary ACL that the audio unit will then honour) -// or if the property is read only - which is the generally preferred mode. -// If the AU doesn't require an AudioChannelLayout, then just return 0. -UInt32 AUIOElement::GetAudioChannelLayout (AudioChannelLayout *outMapPtr, - Boolean &outWritable) -{ - return 0; -} - -// the incoming channel map will be at least as big as a basic AudioChannelLayout -// but its contents will determine its actual size -// Subclass should overide if channel map is writable -OSStatus AUIOElement::SetAudioChannelLayout (const AudioChannelLayout &inData) -{ - return kAudioUnitErr_InvalidProperty; -} - -// Some units support optional usage of channel maps - typically converter units -// that can do channel remapping between different maps. In that optional case -// the user should be able to remove a channel map if that is possible. -// Typically this is NOT the case (e.g., the 3DMixer even in the stereo case -// needs to know if it is rendering to speakers or headphones) -OSStatus AUIOElement::RemoveAudioChannelLayout () -{ - return kAudioUnitErr_InvalidPropertyValue; -} - - -//_____________________________________________________________________________ -// -AUScope::~AUScope() -{ - for (ElementVector::iterator it = mElements.begin(); it != mElements.end(); ++it) - delete *it; -} - -//_____________________________________________________________________________ -// -void AUScope::SetNumberOfElements(UInt32 numElements) -{ - if (mDelegate) - return mDelegate->SetNumberOfElements(numElements); - - if (numElements > mElements.size()) { - mElements.reserve(numElements); - while (numElements > mElements.size()) { - AUElement *elem = mCreator->CreateElement(GetScope(), static_cast(mElements.size())); - mElements.push_back(elem); - } - } else - while (numElements < mElements.size()) { - AUElement *elem = mElements.back(); - mElements.pop_back(); - delete elem; - } -} - -//_____________________________________________________________________________ -// -bool AUScope::HasElementWithName () const -{ - for (UInt32 i = 0; i < GetNumberOfElements(); ++i) { - AUElement * el = const_cast(this)->GetElement (i); - if (el && el->HasName()) { - return true; - } - } - return false; -} - -//_____________________________________________________________________________ -// - -void AUScope::AddElementNamesToDict (CFMutableDictionaryRef & inNameDict) -{ - if (HasElementWithName()) - { - static char string[32]; - CFMutableDictionaryRef elementDict = CFDictionaryCreateMutable (NULL, 0, - &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); - CFStringRef str; - for (UInt32 i = 0; i < GetNumberOfElements(); ++i) { - AUElement * el = GetElement (i); - if (el && el->HasName()) { - snprintf (string, sizeof(string), "%d", int(i)); - str = CFStringCreateWithCString (NULL, string, kCFStringEncodingASCII); - CFDictionarySetValue (elementDict, str, el->GetName()); - CFRelease (str); - } - } - - snprintf (string, sizeof(string), "%d", int(mScope)); - str = CFStringCreateWithCString (NULL, string, kCFStringEncodingASCII); - CFDictionarySetValue (inNameDict, str, elementDict); - CFRelease (str); - CFRelease (elementDict); - } -} - -//_____________________________________________________________________________ -// -bool AUScope::RestoreElementNames (CFDictionaryRef& inNameDict) -{ - static char string[32]; - - //first we have to see if we have enough elements - bool didAddElements = false; - unsigned int maxElNum = GetNumberOfElements(); - - int dictSize = static_cast(CFDictionaryGetCount(inNameDict)); - CFStringRef * keys = (CFStringRef*)CA_malloc (dictSize * sizeof (CFStringRef)); - CFDictionaryGetKeysAndValues (inNameDict, reinterpret_cast(keys), NULL); - for (int i = 0; i < dictSize; i++) - { - unsigned int intKey = 0; - CFStringGetCString (keys[i], string, 32, kCFStringEncodingASCII); - int result = sscanf (string, "%u", &intKey); - // check if sscanf succeeded and element index is less than max elements. - if (result && UInt32(intKey) < maxElNum) - { - CFStringRef elName = reinterpret_cast(CFDictionaryGetValue (inNameDict, keys[i])); - AUElement* element = GetElement (intKey); - if (element) - element->SetName (elName); - } - } - free (keys); - - return didAddElements; -} - -void AUScope::SaveState(CFMutableDataRef data) -{ - AudioUnitElement nElems = GetNumberOfElements(); - for (AudioUnitElement ielem = 0; ielem < nElems; ++ielem) { - AUElement *element = GetElement(ielem); - UInt32 nparams = element->GetNumberOfParameters(); - if (nparams > 0) { - struct { - UInt32 scope; - UInt32 element; - } hdr; - - hdr.scope = CFSwapInt32HostToBig(GetScope()); - hdr.element = CFSwapInt32HostToBig(ielem); - CFDataAppendBytes(data, (UInt8 *)&hdr, sizeof(hdr)); - - element->SaveState(data); - } - } -} - -const UInt8 * AUScope::RestoreState(const UInt8 *state) -{ - const UInt8 *p = state; - UInt32 elementIdx = CFSwapInt32BigToHost(*(UInt32 *)p); p += sizeof(UInt32); - AUElement *element = GetElement(elementIdx); - if (!element) { - struct { - AudioUnitParameterID paramID; - AudioUnitParameterValue value; - } entry; - UInt32 nparams = CFSwapInt32BigToHost(*(UInt32 *)p); - p += sizeof(UInt32); - - p += nparams * sizeof(entry); - } else - p = element->RestoreState(p); - - return p; -} diff --git a/src/CoreAudio/CoreAudioComponent/AUPublic/AUBase/AUScopeElement.h b/src/CoreAudio/CoreAudioComponent/AUPublic/AUBase/AUScopeElement.h deleted file mode 100644 index 47ebe2f33..000000000 --- a/src/CoreAudio/CoreAudioComponent/AUPublic/AUBase/AUScopeElement.h +++ /dev/null @@ -1,553 +0,0 @@ -/* - File: AUScopeElement.h - Abstract: Part of CoreAudio Utility Classes - Version: 1.1 - - Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple - Inc. ("Apple") in consideration of your agreement to the following - terms, and your use, installation, modification or redistribution of - this Apple software constitutes acceptance of these terms. If you do - not agree with these terms, please do not use, install, modify or - redistribute this Apple software. - - In consideration of your agreement to abide by the following terms, and - subject to these terms, Apple grants you a personal, non-exclusive - license, under Apple's copyrights in this original Apple software (the - "Apple Software"), to use, reproduce, modify and redistribute the Apple - Software, with or without modifications, in source and/or binary forms; - provided that if you redistribute the Apple Software in its entirety and - without modifications, you must retain this notice and the following - text and disclaimers in all such redistributions of the Apple Software. - Neither the name, trademarks, service marks or logos of Apple Inc. may - be used to endorse or promote products derived from the Apple Software - without specific prior written permission from Apple. Except as - expressly stated in this notice, no other rights or licenses, express or - implied, are granted by Apple herein, including but not limited to any - patent rights that may be infringed by your derivative works or by other - works in which the Apple Software may be incorporated. - - The Apple Software is provided by Apple on an "AS IS" basis. APPLE - MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION - THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS - FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND - OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS. - - IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL - OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, - MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED - AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), - STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE - POSSIBILITY OF SUCH DAMAGE. - - Copyright (C) 2014 Apple Inc. All Rights Reserved. - -*/ -#ifndef __AUScopeElement_h__ -#define __AUScopeElement_h__ - -#include -#include - -#if !defined(__COREAUDIO_USE_FLAT_INCLUDES__) - #include -#else - #include -#endif -#include "ComponentBase.h" -#include "AUBuffer.h" - - -class AUBase; - -// ____________________________________________________________________________ -// -// represents a parameter's value (either constant or ramped) -/*! @class ParameterMapEvent */ -class ParameterMapEvent -{ -public: -/*! @ctor ParameterMapEvent */ - ParameterMapEvent() - : mEventType(kParameterEvent_Immediate), mBufferOffset(0), mDurationInFrames(0), mValue1(0.0f), mValue2(0.0f), mSliceDurationFrames(0) - {} - -/*! @ctor ParameterMapEvent */ - ParameterMapEvent(AudioUnitParameterValue inValue) - : mEventType(kParameterEvent_Immediate), mBufferOffset(0), mDurationInFrames(0), mValue1(inValue), mValue2(inValue), mSliceDurationFrames(0) - {} - - // constructor for scheduled event -/*! @ctor ParameterMapEvent */ - ParameterMapEvent( const AudioUnitParameterEvent &inEvent, - UInt32 inSliceOffsetInBuffer, - UInt32 inSliceDurationFrames ) - { - SetScheduledEvent(inEvent, inSliceOffsetInBuffer, inSliceDurationFrames ); - }; - -/*! @method SetScheduledEvent */ - void SetScheduledEvent( const AudioUnitParameterEvent &inEvent, - UInt32 inSliceOffsetInBuffer, - UInt32 inSliceDurationFrames ) - { - mEventType = inEvent.eventType; - mSliceDurationFrames = inSliceDurationFrames; - - if(mEventType == kParameterEvent_Immediate ) - { - // constant immediate value for the whole slice - mValue1 = inEvent.eventValues.immediate.value; - mValue2 = mValue1; - mDurationInFrames = inSliceDurationFrames; - mBufferOffset = 0; - } - else - { - mDurationInFrames = inEvent.eventValues.ramp.durationInFrames; - mBufferOffset = inEvent.eventValues.ramp.startBufferOffset - inSliceOffsetInBuffer; // shift over for this slice - mValue1 = inEvent.eventValues.ramp.startValue; - mValue2 = inEvent.eventValues.ramp.endValue; - } - }; - - - -/*! @method GetEventType */ - AUParameterEventType GetEventType() const {return mEventType;}; - -/*! @method GetValue */ - AudioUnitParameterValue GetValue() const {return mValue1;}; // only valid if immediate event type -/*! @method GetEndValue */ - AudioUnitParameterValue GetEndValue() const {return mValue2;}; // only valid if immediate event type -/*! @method SetValue */ - void SetValue(AudioUnitParameterValue inValue) - { - mEventType = kParameterEvent_Immediate; - mValue1 = inValue; - mValue2 = inValue; - } - - // interpolates the start and end values corresponding to the current processing slice - // most ramp parameter implementations will want to use this method - // the start value will correspond to the start of the slice - // the end value will correspond to the end of the slice -/*! @method GetRampSliceStartEnd */ - void GetRampSliceStartEnd( AudioUnitParameterValue & outStartValue, - AudioUnitParameterValue & outEndValue, - AudioUnitParameterValue & outValuePerFrameDelta ) - { - if (mEventType == kParameterEvent_Ramped) { - outValuePerFrameDelta = (mValue2 - mValue1) / mDurationInFrames; - - outStartValue = mValue1 + outValuePerFrameDelta * (-mBufferOffset); // corresponds to frame 0 of this slice - outEndValue = outStartValue + outValuePerFrameDelta * mSliceDurationFrames; - } else { - outValuePerFrameDelta = 0; - outStartValue = outEndValue = mValue1; - } - }; - - // Some ramp parameter implementations will want to interpret the ramp using their - // own interpolation method (perhaps non-linear) - // This method gives the raw ramp information, relative to this processing slice - // for the client to interpret as desired -/*! @method GetRampInfo */ - void GetRampInfo( SInt32 & outBufferOffset, - UInt32 & outDurationInFrames, - AudioUnitParameterValue & outStartValue, - AudioUnitParameterValue & outEndValue ) - { - outBufferOffset = mBufferOffset; - outDurationInFrames = mDurationInFrames; - outStartValue = mValue1; - outEndValue = mValue2; - }; - -#if DEBUG - void Print() - { - printf("ParameterEvent @ %p\n", this); - printf(" mEventType = %d\n", (int)mEventType); - printf(" mBufferOffset = %d\n", (int)mBufferOffset); - printf(" mDurationInFrames = %d\n", (int)mDurationInFrames); - printf(" mSliceDurationFrames = %d\n", (int)mSliceDurationFrames); - printf(" mValue1 = %.5f\n", mValue1); - printf(" mValue2 = %.5f\n", mValue2); - } -#endif - -private: - AUParameterEventType mEventType; - - SInt32 mBufferOffset; // ramp start offset relative to start of this slice (may be negative) - UInt32 mDurationInFrames; // total duration of ramp parameter - AudioUnitParameterValue mValue1; // value if immediate : startValue if ramp - AudioUnitParameterValue mValue2; // endValue (only used for ramp) - - UInt32 mSliceDurationFrames; // duration of this processing slice -}; - - - -// ____________________________________________________________________________ -// -class AUIOElement; - -/*! @class AUElement */ -class AUElement { -public: -/*! @ctor AUElement */ - AUElement(AUBase *audioUnit) : mAudioUnit(audioUnit), - mUseIndexedParameters(false), mElementName(0) { } - -/*! @dtor ~AUElement */ - virtual ~AUElement() { if (mElementName) CFRelease (mElementName); } - -/*! @method GetNumberOfParameters */ - virtual UInt32 GetNumberOfParameters() - { - if(mUseIndexedParameters) return static_cast(mIndexedParameters.size()); else return static_cast(mParameters.size()); - } -/*! @method GetParameterList */ - virtual void GetParameterList(AudioUnitParameterID *outList); -/*! @method HasParameterID */ - bool HasParameterID (AudioUnitParameterID paramID) const; - -/*! @method GetParameter */ - AudioUnitParameterValue GetParameter(AudioUnitParameterID paramID); -/*! @method SetParameter */ - void SetParameter(AudioUnitParameterID paramID, AudioUnitParameterValue value, bool okWhenInitialized = false); - // Only set okWhenInitialized to true when you know the outside world cannot access this element. Otherwise the parameter map could get corrupted. - - // interpolates the start and end values corresponding to the current processing slice - // most ramp parameter implementations will want to use this method -/*! @method GetRampSliceStartEnd */ - void GetRampSliceStartEnd( AudioUnitParameterID paramID, - AudioUnitParameterValue & outStartValue, - AudioUnitParameterValue & outEndValue, - AudioUnitParameterValue & outValuePerFrameDelta ); - -/*! @method GetEndValue */ - AudioUnitParameterValue GetEndValue( AudioUnitParameterID paramID); - -/*! @method SetRampParameter */ - void SetScheduledEvent( AudioUnitParameterID paramID, - const AudioUnitParameterEvent &inEvent, - UInt32 inSliceOffsetInBuffer, - UInt32 inSliceDurationFrames, - bool okWhenInitialized = false ); - // Only set okWhenInitialized to true when you know the outside world cannot access this element. Otherwise the parameter map could get corrupted. - - -/*! @method GetAudioUnit */ - AUBase * GetAudioUnit() const { return mAudioUnit; }; - -/*! @method SaveState */ - void SaveState(CFMutableDataRef data); -/*! @method RestoreState */ - const UInt8 * RestoreState(const UInt8 *state); -/*! @method GetName */ - CFStringRef GetName () const { return mElementName; } -/*! @method SetName */ - void SetName (CFStringRef inName); -/*! @method HasName */ - bool HasName () const { return mElementName != 0; } -/*! @method UseIndexedParameters */ - virtual void UseIndexedParameters(int inNumberOfParameters); - -/*! @method AsIOElement*/ - virtual AUIOElement* AsIOElement () { return NULL; } - -protected: - inline ParameterMapEvent& GetParamEvent(AudioUnitParameterID paramID); - -private: - typedef std::map > ParameterMap; - -/*! @var mAudioUnit */ - AUBase * mAudioUnit; -/*! @var mParameters */ - ParameterMap mParameters; - -/*! @var mUseIndexedParameters */ - bool mUseIndexedParameters; -/*! @var mIndexedParameters */ - std::vector mIndexedParameters; - -/*! @var mElementName */ - CFStringRef mElementName; -}; - - - -// ____________________________________________________________________________ -// -/*! @class AUIOElement */ -class AUIOElement : public AUElement { -public: -/*! @ctor AUIOElement */ - AUIOElement(AUBase *audioUnit); - -/*! @method GetStreamFormat */ - const CAStreamBasicDescription &GetStreamFormat() const { return mStreamFormat; } - -/*! @method SetStreamFormat */ - virtual OSStatus SetStreamFormat(const CAStreamBasicDescription &desc); - -/*! @method AllocateBuffer */ - virtual void AllocateBuffer(UInt32 inFramesToAllocate = 0); -/*! @method DeallocateBuffer */ - void DeallocateBuffer(); -/*! @method NeedsBufferSpace */ - virtual bool NeedsBufferSpace() const = 0; - -/*! @method SetWillAllocateBuffer */ - void SetWillAllocateBuffer(bool inFlag) { - mWillAllocate = inFlag; - } -/*! @method WillAllocateBuffer */ - bool WillAllocateBuffer() const { - return mWillAllocate; - } - -/*! @method UseExternalBuffer */ - void UseExternalBuffer(const AudioUnitExternalBuffer &buf) { - mIOBuffer.UseExternalBuffer(mStreamFormat, buf); - } -/*! @method PrepareBuffer */ - AudioBufferList & PrepareBuffer(UInt32 nFrames) { - if (mWillAllocate) - return mIOBuffer.PrepareBuffer(mStreamFormat, nFrames); - throw OSStatus(kAudioUnitErr_InvalidPropertyValue); - } -/*! @method PrepareNullBuffer */ - AudioBufferList & PrepareNullBuffer(UInt32 nFrames) { - return mIOBuffer.PrepareNullBuffer(mStreamFormat, nFrames); - } -/*! @method SetBufferList */ - AudioBufferList & SetBufferList(AudioBufferList &abl) { return mIOBuffer.SetBufferList(abl); } -/*! @method SetBuffer */ - void SetBuffer(UInt32 index, AudioBuffer &ab) { mIOBuffer.SetBuffer(index, ab); } -/*! @method InvalidateBufferList */ - void InvalidateBufferList() { mIOBuffer.InvalidateBufferList(); } - -/*! @method GetBufferList */ - AudioBufferList & GetBufferList() const { return mIOBuffer.GetBufferList(); } - -/*! @method GetChannelData */ - AudioUnitSampleType * GetChannelData(int ch) const { - if (mStreamFormat.IsInterleaved()) - return static_cast(mIOBuffer.GetBufferList().mBuffers[0].mData) + ch; - else - return static_cast(mIOBuffer.GetBufferList().mBuffers[ch].mData); - } - Float32 * GetFloat32ChannelData(int ch) const { - if (mStreamFormat.IsInterleaved()) - return static_cast(mIOBuffer.GetBufferList().mBuffers[0].mData) + ch; - else - return static_cast(mIOBuffer.GetBufferList().mBuffers[ch].mData); - } - SInt32 * GetSInt32ChannelData(int ch) const { - if (mStreamFormat.IsInterleaved()) - return static_cast(mIOBuffer.GetBufferList().mBuffers[0].mData) + ch; - else - return static_cast(mIOBuffer.GetBufferList().mBuffers[ch].mData); - } - SInt16 * GetInt16ChannelData(int ch) const { - if (mStreamFormat.IsInterleaved()) - return static_cast(mIOBuffer.GetBufferList().mBuffers[0].mData) + ch; - else - return static_cast(mIOBuffer.GetBufferList().mBuffers[ch].mData); - } - -/*! @method CopyBufferListTo */ - void CopyBufferListTo(AudioBufferList &abl) const { - mIOBuffer.CopyBufferListTo(abl); - } -/*! @method CopyBufferContentsTo */ - void CopyBufferContentsTo(AudioBufferList &abl) const { - mIOBuffer.CopyBufferContentsTo(abl); - } - -/* UInt32 BytesToFrames(UInt32 nBytes) { return nBytes / mStreamFormat.mBytesPerFrame; } - UInt32 BytesToFrames(AudioBufferList &abl) { - return BytesToFrames(abl.mBuffers[0].mDataByteSize); - } - UInt32 FramesToBytes(UInt32 nFrames) { return nFrames * mStreamFormat.mBytesPerFrame; }*/ - -/*! @method IsInterleaved */ - bool IsInterleaved() const { return mStreamFormat.IsInterleaved(); } -/*! @method NumberChannels */ - UInt32 NumberChannels() const { return mStreamFormat.NumberChannels(); } -/*! @method NumberInterleavedChannels */ - UInt32 NumberInterleavedChannels() const { return mStreamFormat.NumberInterleavedChannels(); } - -/*! @method GetChannelMapTags */ - virtual UInt32 GetChannelLayoutTags (AudioChannelLayoutTag *outLayoutTagsPtr); - -/*! @method GetAudioChannelLayout */ - virtual UInt32 GetAudioChannelLayout (AudioChannelLayout *outMapPtr, Boolean &outWritable); - -/*! @method SetAudioChannelLayout */ - virtual OSStatus SetAudioChannelLayout (const AudioChannelLayout &inData); - -/*! @method RemoveAudioChannelLayout */ - virtual OSStatus RemoveAudioChannelLayout (); - -/*! @method AsIOElement*/ - virtual AUIOElement* AsIOElement () { return this; } - -protected: -/*! @var mStreamFormat */ - CAStreamBasicDescription mStreamFormat; -/*! @var mIOBuffer */ - AUBufferList mIOBuffer; // for input: input proc buffer, only allocated when needed - // for output: output cache, usually allocated early on -/*! @var mWillAllocate */ - bool mWillAllocate; -}; - -// ____________________________________________________________________________ -// -// AUScopeDelegates are a way to get virtual scopes. -/*! @class AUScopeDelegate */ -class AUScopeDelegate { -public: -/*! @ctor AUScopeDelegate */ - AUScopeDelegate() : mCreator(NULL), mScope(0) { } -/*! @dtor ~AUScopeDelegate */ - virtual ~AUScopeDelegate() {} - -/*! @method Initialize */ - void Initialize( AUBase *creator, - AudioUnitScope scope, - UInt32 numElements) - { - mCreator = creator; - mScope = scope; - SetNumberOfElements(numElements); - } - -/*! @method SetNumberOfElements */ - virtual void SetNumberOfElements(UInt32 numElements) = 0; - -/*! @method GetNumberOfElements */ - virtual UInt32 GetNumberOfElements() = 0; - -/*! @method GetElement */ - virtual AUElement * GetElement(UInt32 elementIndex) = 0; - - AUBase * GetCreator() const { return mCreator; } - AudioUnitScope GetScope() const { return mScope; } - - -private: -/*! @var mCreator */ - AUBase * mCreator; -/*! @var mScope */ - AudioUnitScope mScope; -}; - - - -// ____________________________________________________________________________ -// -/*! @class AUScope */ -class AUScope { -public: -/*! @ctor AUScope */ - AUScope() : mCreator(NULL), mScope(0), mDelegate(0) { } -/*! @dtor ~AUScope */ - ~AUScope(); - -/*! @method Initialize */ - void Initialize(AUBase *creator, - AudioUnitScope scope, - UInt32 numElements) - { - mCreator = creator; - mScope = scope; - - if (mDelegate) - return mDelegate->Initialize(creator, scope, numElements); - - SetNumberOfElements(numElements); - } - -/*! @method SetNumberOfElements */ - void SetNumberOfElements(UInt32 numElements); - -/*! @method GetNumberOfElements */ - UInt32 GetNumberOfElements() const - { - if (mDelegate) - return mDelegate->GetNumberOfElements(); - - return static_cast(mElements.size()); - } - -/*! @method GetElement */ - AUElement * GetElement(UInt32 elementIndex) const - { - if (mDelegate) - return mDelegate->GetElement(elementIndex); - - ElementVector::const_iterator i = mElements.begin() + elementIndex; - // catch passing -1 in as the elementIndex - causes a wrap around - return (i >= mElements.end() || i < mElements.begin()) ? NULL : *i; - } - -/*! @method SafeGetElement */ - AUElement * SafeGetElement(UInt32 elementIndex) - { - AUElement *element = GetElement(elementIndex); - if (element == NULL) - COMPONENT_THROW(kAudioUnitErr_InvalidElement); - return element; - } - -/*! @method GetIOElement */ - AUIOElement * GetIOElement(UInt32 elementIndex) const - { - AUElement *element = GetElement(elementIndex); - AUIOElement *ioel = element ? element->AsIOElement () : NULL; - if (!ioel) - COMPONENT_THROW (kAudioUnitErr_InvalidElement); - return ioel; - } - -/*! @method HasElementWithName */ - bool HasElementWithName () const; - -/*! @method AddElementNamesToDict */ - void AddElementNamesToDict (CFMutableDictionaryRef & inNameDict); - - bool RestoreElementNames (CFDictionaryRef& inNameDict); - - AudioUnitScope GetScope() const { return mScope; } - - void SetDelegate(AUScopeDelegate* inDelegate) { mDelegate = inDelegate; } - -/*! @method SaveState */ - void SaveState(CFMutableDataRef data); - -/*! @method RestoreState */ - const UInt8 * RestoreState(const UInt8 *state); - -private: - typedef std::vector ElementVector; -/*! @var mCreator */ - AUBase * mCreator; -/*! @var mScope */ - AudioUnitScope mScope; -/*! @var mElements */ - ElementVector mElements; -/*! @var mDelegate */ - AUScopeDelegate * mDelegate; -}; - - - -#endif // __AUScopeElement_h__ diff --git a/src/CoreAudio/CoreAudioComponent/AUPublic/AUBase/ComponentBase.cpp b/src/CoreAudio/CoreAudioComponent/AUPublic/AUBase/ComponentBase.cpp deleted file mode 100644 index fc987335d..000000000 --- a/src/CoreAudio/CoreAudioComponent/AUPublic/AUBase/ComponentBase.cpp +++ /dev/null @@ -1,370 +0,0 @@ -/* - File: ComponentBase.cpp - Abstract: ComponentBase.h - Version: 1.1 - - Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple - Inc. ("Apple") in consideration of your agreement to the following - terms, and your use, installation, modification or redistribution of - this Apple software constitutes acceptance of these terms. If you do - not agree with these terms, please do not use, install, modify or - redistribute this Apple software. - - In consideration of your agreement to abide by the following terms, and - subject to these terms, Apple grants you a personal, non-exclusive - license, under Apple's copyrights in this original Apple software (the - "Apple Software"), to use, reproduce, modify and redistribute the Apple - Software, with or without modifications, in source and/or binary forms; - provided that if you redistribute the Apple Software in its entirety and - without modifications, you must retain this notice and the following - text and disclaimers in all such redistributions of the Apple Software. - Neither the name, trademarks, service marks or logos of Apple Inc. may - be used to endorse or promote products derived from the Apple Software - without specific prior written permission from Apple. Except as - expressly stated in this notice, no other rights or licenses, express or - implied, are granted by Apple herein, including but not limited to any - patent rights that may be infringed by your derivative works or by other - works in which the Apple Software may be incorporated. - - The Apple Software is provided by Apple on an "AS IS" basis. APPLE - MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION - THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS - FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND - OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS. - - IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL - OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, - MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED - AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), - STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE - POSSIBILITY OF SUCH DAMAGE. - - Copyright (C) 2014 Apple Inc. All Rights Reserved. - -*/ -#include "ComponentBase.h" -#include "CAXException.h" - -#if TARGET_OS_MAC -pthread_mutex_t ComponentInitLocker::sComponentOpenMutex = PTHREAD_MUTEX_INITIALIZER; -pthread_once_t ComponentInitLocker::sOnce = PTHREAD_ONCE_INIT; - -void ComponentInitLocker::InitComponentInitLocker() -{ - // have to do this because OS X lacks PTHREAD_MUTEX_RECURSIVE_INITIALIZER_NP - pthread_mutexattr_t attr; - pthread_mutexattr_init(&attr); - pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE); - pthread_mutex_init(&sComponentOpenMutex, &attr); - pthread_mutexattr_destroy(&attr); -} - -#elif TARGET_OS_WIN32 -CAGuard ComponentInitLocker::sComponentOpenGuard("sComponentOpenGuard"); -#endif - -ComponentBase::EInstanceType ComponentBase::sNewInstanceType; - -static OSStatus CB_GetComponentDescription (const AudioComponentInstance inInstance, AudioComponentDescription * outDesc); -#if !CA_USE_AUDIO_PLUGIN_ONLY && !TARGET_OS_WIN32 - static OSStatus CMgr_GetComponentDescription (const AudioComponentInstance inInstance, AudioComponentDescription * outDesc); -#endif - -ComponentBase::ComponentBase(AudioComponentInstance inInstance) - : mComponentInstance(inInstance), - mInstanceType(sNewInstanceType) -{ - GetComponentDescription(); -} - -ComponentBase::~ComponentBase() -{ -} - -void ComponentBase::PostConstructor() -{ -} - -void ComponentBase::PreDestructor() -{ -} - -#define ACPI ((AudioComponentPlugInInstance *)self) -#define ACImp ((ComponentBase *)&ACPI->mInstanceStorage) - -OSStatus ComponentBase::AP_Open(void *self, AudioUnit compInstance) -{ - OSStatus result = noErr; - try { - ComponentInitLocker lock; - - ComponentBase::sNewInstanceType = ComponentBase::kAudioComponentInstance; - ComponentBase *cb = (ComponentBase *)(*ACPI->mConstruct)(&ACPI->mInstanceStorage, compInstance); - cb->PostConstructor(); // allows base class to do additional initialization - // once the derived class is fully constructed - result = noErr; - } - COMPONENT_CATCH - if (result) - delete ACPI; - return result; -} - -OSStatus ComponentBase::AP_Close(void *self) -{ - OSStatus result = noErr; - try { - if (ACImp) { - ACImp->PreDestructor(); - (*ACPI->mDestruct)(&ACPI->mInstanceStorage); - free(self); - } - } - COMPONENT_CATCH - return result; -} - -#if !CA_USE_AUDIO_PLUGIN_ONLY -OSStatus ComponentBase::Version() -{ - return 0x00000001; -} - -OSStatus ComponentBase::ComponentEntryDispatch(ComponentParameters *p, ComponentBase *This) -{ - if (This == NULL) return kAudio_ParamError; - - OSStatus result = noErr; - - switch (p->what) { - case kComponentCloseSelect: - This->PreDestructor(); - delete This; - break; - - case kComponentVersionSelect: - result = This->Version(); - break; - - case kComponentCanDoSelect: - switch (GetSelectorForCanDo(p)) { - case kComponentOpenSelect: - case kComponentCloseSelect: - case kComponentVersionSelect: - case kComponentCanDoSelect: - return 1; - default: - return 0; - } - - default: - result = badComponentSelector; - break; - } - return result; -} - -SInt16 ComponentBase::GetSelectorForCanDo(ComponentParameters *params) -{ - if (params->what != kComponentCanDoSelect) return 0; - - #if TARGET_CPU_X86 - SInt16 sel = params->params[0]; - #elif TARGET_CPU_X86_64 - SInt16 sel = params->params[1]; - #elif TARGET_CPU_PPC - SInt16 sel = (params->params[0] >> 16); - #else - SInt16 sel = params->params[0]; - #endif - - return sel; -/* - printf ("flags:%d, paramSize: %d, what: %d\n\t", params->flags, params->paramSize, params->what); - for (int i = 0; i < params->paramSize; ++i) { - printf ("[%d]:%d(0x%x), ", i, params->params[i], params->params[i]); - } - printf("\n\tsel:%d\n", sel); -*/ -} - -#endif - -#if CA_DO_NOT_USE_AUDIO_COMPONENT -static OSStatus ComponentBase_GetComponentDescription (const AudioComponentInstance & inInstance, AudioComponentDescription &outDesc); -#endif - -AudioComponentDescription ComponentBase::GetComponentDescription() const -{ - AudioComponentDescription desc; - OSStatus result = 1; - - if (IsPluginObject()) { - ca_require_noerr(result = CB_GetComponentDescription (mComponentInstance, &desc), home); - } -#if !CA_USE_AUDIO_PLUGIN_ONLY - else { - ca_require_noerr(result = CMgr_GetComponentDescription (mComponentInstance, &desc), home); - } -#endif - -home: - if (result) - memset (&desc, 0, sizeof(AudioComponentDescription)); - - return desc; -} - -#if CA_USE_AUDIO_PLUGIN_ONLY -// everything we need is there and we should be linking against it -static OSStatus CB_GetComponentDescription (const AudioComponentInstance inInstance, AudioComponentDescription * outDesc) -{ - AudioComponent comp = AudioComponentInstanceGetComponent(inInstance); - if (comp) - return AudioComponentGetDescription(comp, outDesc); - - return kAudio_ParamError; -} - -#elif !TARGET_OS_WIN32 -// these are the direct dependencies on ComponentMgr calls that an AU -// that is a component mgr is dependent on - -// these are dynamically loaded so that these calls will work on Leopard -#include - -static OSStatus CB_GetComponentDescription (const AudioComponentInstance inInstance, AudioComponentDescription * outDesc) -{ - typedef AudioComponent (*AudioComponentInstanceGetComponentProc) (AudioComponentInstance); - static AudioComponentInstanceGetComponentProc aciGCProc = NULL; - - typedef OSStatus (*AudioComponentGetDescriptionProc)(AudioComponent, AudioComponentDescription *); - static AudioComponentGetDescriptionProc acGDProc = NULL; - - static int doneInit = 0; - if (doneInit == 0) { - doneInit = 1; - void* theImage = dlopen("/System/Library/Frameworks/AudioUnit.framework/AudioUnit", RTLD_LAZY); - if (theImage != NULL) - { - aciGCProc = (AudioComponentInstanceGetComponentProc)dlsym (theImage, "AudioComponentInstanceGetComponent"); - if (aciGCProc) { - acGDProc = (AudioComponentGetDescriptionProc)dlsym (theImage, "AudioComponentGetDescription"); - } - } - } - - OSStatus result = kAudio_UnimplementedError; - if (acGDProc && aciGCProc) { - AudioComponent comp = (*aciGCProc)(inInstance); - if (comp) - result = (*acGDProc)(comp, outDesc); - } -#if !CA_USE_AUDIO_PLUGIN_ONLY - else { - result = CMgr_GetComponentDescription (inInstance, outDesc); - } -#endif - - return result; -} - -#if !CA_USE_AUDIO_PLUGIN_ONLY -// these are the direct dependencies on ComponentMgr calls that an AU -// that is a component mgr is dependent on - -// these are dynamically loaded - -#include -#include -#include "CAXException.h" -#include "ComponentBase.h" - -//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -// Component Manager -// Used for fast dispatch with audio units -typedef Handle (*GetComponentInstanceStorageProc)(ComponentInstance aComponentInstance); -static GetComponentInstanceStorageProc sGetComponentInstanceStorageProc = NULL; - -typedef OSErr (*GetComponentInfoProc)(Component, ComponentDescription *, void*, void*, void*); -static GetComponentInfoProc sGetComponentInfoProc = NULL; - -typedef void (*SetComponentInstanceStorageProc)(ComponentInstance, Handle); -static SetComponentInstanceStorageProc sSetComponentInstanceStorageProc = NULL; - -//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -static void CSInitOnce(void* /*unused*/) -{ - void *theImage = dlopen("/System/Library/Frameworks/CoreServices.framework/CoreServices", RTLD_LAZY); - if (!theImage) return; - - sGetComponentInstanceStorageProc = (GetComponentInstanceStorageProc) dlsym(theImage, "GetComponentInstanceStorage"); - sGetComponentInfoProc = (GetComponentInfoProc)dlsym (theImage, "GetComponentInfo"); - sSetComponentInstanceStorageProc = (SetComponentInstanceStorageProc) dlsym(theImage, "SetComponentInstanceStorage"); -} - -#if TARGET_OS_MAC - -#include - -static dispatch_once_t sCSInitOnce = 0; - -static void CSInit () -{ - dispatch_once_f(&sCSInitOnce, NULL, CSInitOnce); -} - -#else - -static void CSInit () -{ - static int sDoCSLoad = 1; - if (sDoCSLoad) { - sDoCSLoad = 0; - CSInitOnce(NULL); - } -} - -#endif - -OSStatus CMgr_GetComponentDescription (const AudioComponentInstance inInstance, AudioComponentDescription * outDesc) -{ - CSInit(); - if (sGetComponentInfoProc) - return (*sGetComponentInfoProc)((Component)inInstance, (ComponentDescription*)outDesc, NULL, NULL, NULL); - return kAudio_UnimplementedError; -} - -Handle CMgr_GetComponentInstanceStorage(ComponentInstance aComponentInstance) -{ - CSInit(); - if (sGetComponentInstanceStorageProc) - return (*sGetComponentInstanceStorageProc)(aComponentInstance); - return NULL; -} - -void CMgr_SetComponentInstanceStorage(ComponentInstance aComponentInstance, Handle theStorage) -{ - CSInit(); - if (sSetComponentInstanceStorageProc) - (*sSetComponentInstanceStorageProc)(aComponentInstance, theStorage); -} -#endif // !CA_USE_AUDIO_PLUGIN_ONLY - -#else -//#include "ComponentManagerDependenciesWin.h" -// everything we need is there and we should be linking against it -static OSStatus CB_GetComponentDescription (const AudioComponentInstance inInstance, AudioComponentDescription * outDesc) -{ - AudioComponent comp = AudioComponentInstanceGetComponent(inInstance); - if (comp) - return AudioComponentGetDescription(comp, outDesc); - - return kAudio_ParamError; -} - -#endif - diff --git a/src/CoreAudio/CoreAudioComponent/AUPublic/AUBase/ComponentBase.h b/src/CoreAudio/CoreAudioComponent/AUPublic/AUBase/ComponentBase.h deleted file mode 100644 index a1654416a..000000000 --- a/src/CoreAudio/CoreAudioComponent/AUPublic/AUBase/ComponentBase.h +++ /dev/null @@ -1,353 +0,0 @@ -/* - File: ComponentBase.h - Abstract: Part of CoreAudio Utility Classes - Version: 1.1 - - Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple - Inc. ("Apple") in consideration of your agreement to the following - terms, and your use, installation, modification or redistribution of - this Apple software constitutes acceptance of these terms. If you do - not agree with these terms, please do not use, install, modify or - redistribute this Apple software. - - In consideration of your agreement to abide by the following terms, and - subject to these terms, Apple grants you a personal, non-exclusive - license, under Apple's copyrights in this original Apple software (the - "Apple Software"), to use, reproduce, modify and redistribute the Apple - Software, with or without modifications, in source and/or binary forms; - provided that if you redistribute the Apple Software in its entirety and - without modifications, you must retain this notice and the following - text and disclaimers in all such redistributions of the Apple Software. - Neither the name, trademarks, service marks or logos of Apple Inc. may - be used to endorse or promote products derived from the Apple Software - without specific prior written permission from Apple. Except as - expressly stated in this notice, no other rights or licenses, express or - implied, are granted by Apple herein, including but not limited to any - patent rights that may be infringed by your derivative works or by other - works in which the Apple Software may be incorporated. - - The Apple Software is provided by Apple on an "AS IS" basis. APPLE - MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION - THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS - FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND - OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS. - - IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL - OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, - MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED - AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), - STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE - POSSIBILITY OF SUCH DAMAGE. - - Copyright (C) 2014 Apple Inc. All Rights Reserved. - -*/ -#ifndef __ComponentBase_h__ -#define __ComponentBase_h__ - -#include -#include "CADebugMacros.h" -#include "CAXException.h" - -#if !defined(__COREAUDIO_USE_FLAT_INCLUDES__) - #include - #include - - #if !CA_USE_AUDIO_PLUGIN_ONLY - #include - - #if (MAC_OS_X_VERSION_MAX_ALLOWED <= MAC_OS_X_VERSION_10_5) - #define AudioComponentInstance ComponentInstance - #define AudioComponentDescription ComponentDescription - #define AudioComponent Component - #endif - Handle CMgr_GetComponentInstanceStorage(ComponentInstance aComponentInstance); - void CMgr_SetComponentInstanceStorage(ComponentInstance aComponentInstance, Handle theStorage); - #endif - - #if MAC_OS_X_VERSION_MAX_ALLOWED <= MAC_OS_X_VERSION_10_4 - typedef Float32 AudioUnitParameterValue; - #endif - #if COREAUDIOTYPES_VERSION < 1051 - typedef Float32 AudioUnitSampleType; - #endif - - #if !TARGET_OS_WIN32 - #include - #endif - - #if TARGET_OS_WIN32 - #include "CAGuard.h" - #endif -#else - #include "CoreAudioTypes.h" - #if !CA_USE_AUDIO_PLUGIN_ONLY - #include "ComponentManagerDependenciesWin.h" - #endif - #include "AudioUnit.h" - #include "CAGuard.h" -#endif - -#ifndef COMPONENT_THROW - #if VERBOSE_COMPONENT_THROW - #define COMPONENT_THROW(throw_err) \ - do { DebugMessage(#throw_err); throw static_cast(throw_err); } while (0) - #else - #define COMPONENT_THROW(throw_err) \ - throw static_cast(throw_err) - #endif -#endif - -#define COMPONENT_CATCH \ - catch (const CAXException &ex) { result = ex.mError; } \ - catch (std::bad_alloc &) { result = kAudio_MemFullError; } \ - catch (OSStatus catch_err) { result = catch_err; } \ - catch (OSErr catch_err) { result = catch_err; } \ - catch (...) { result = -1; } - -/*! @class ComponentBase */ -class ComponentBase { -public: - // classic MacErrors - enum { noErr = 0}; - - /*! @ctor ComponentBase */ - ComponentBase(AudioComponentInstance inInstance); - - /*! @dtor ~ComponentBase */ - virtual ~ComponentBase(); - - /*! @method PostConstructor */ - virtual void PostConstructor(); - - /*! @method PreDestructor */ - virtual void PreDestructor(); - -#if !CA_USE_AUDIO_PLUGIN_ONLY - /*! @method Version */ - virtual OSStatus Version(); - - /*! @method ComponentEntryDispatch */ - static OSStatus ComponentEntryDispatch(ComponentParameters *p, ComponentBase *This); - - /*! GetSelectorForCanDo */ - static SInt16 GetSelectorForCanDo(ComponentParameters *params); -#endif - - /*! @method GetComponentInstance */ - AudioComponentInstance GetComponentInstance() const { return mComponentInstance; } - - /*! @method GetComponentDescription */ - AudioComponentDescription GetComponentDescription() const; - - // This global variable is so that new instances know how they were instantiated: via the Component Manager, - // or as AudioComponents. It's ugly, but preferable to altering the constructor of every class in the hierarchy. - // It's safe because construction is protected by ComponentInitLocker. - enum EInstanceType { kComponentMgrInstance, kAudioComponentInstance }; - static EInstanceType sNewInstanceType; - - /*! @method IsPluginObject */ - bool IsPluginObject () const { return mInstanceType == kAudioComponentInstance; } - /*! @method IsCMgrObject */ - bool IsCMgrObject () const { return mInstanceType == kComponentMgrInstance; } - - /*! @method AP_Open */ - static OSStatus AP_Open(void *self, AudioUnit compInstance); - - /*! @method AP_Close */ - static OSStatus AP_Close(void *self); - -protected: - /*! @var mComponentInstance */ - AudioComponentInstance mComponentInstance; - EInstanceType mInstanceType; -}; - -class ComponentInitLocker -{ -#if TARGET_OS_MAC -public: - ComponentInitLocker() - { - pthread_once(&sOnce, InitComponentInitLocker); - pthread_mutex_lock(&sComponentOpenMutex); - mPreviousNewInstanceType = ComponentBase::sNewInstanceType; - } - ~ComponentInitLocker() - { - ComponentBase::sNewInstanceType = mPreviousNewInstanceType; - pthread_mutex_unlock(&sComponentOpenMutex); - } - - // There are situations (11844772) where we need to be able to release the lock early. - class Unlocker { - public: - Unlocker() - { - pthread_mutex_unlock(&sComponentOpenMutex); - } - ~Unlocker() - { - pthread_mutex_lock(&sComponentOpenMutex); - } - }; - -private: - static pthread_mutex_t sComponentOpenMutex; - static pthread_once_t sOnce; - static void InitComponentInitLocker(); - -#elif TARGET_OS_WIN32 -public: - bool sNeedsUnlocking; - ComponentInitLocker() { sNeedsUnlocking = sComponentOpenGuard.Lock(); } - ~ComponentInitLocker() { if(sNeedsUnlocking) { sComponentOpenGuard.Unlock(); } } -private: - static CAGuard sComponentOpenGuard; -#endif - -private: - ComponentBase::EInstanceType mPreviousNewInstanceType; -}; - -/*! @class AudioComponentPlugInInstance */ -struct AudioComponentPlugInInstance { - AudioComponentPlugInInterface mPlugInInterface; - void * (*mConstruct)(void *memory, AudioComponentInstance ci); - void (*mDestruct)(void *memory); - void * mPad[2]; // pad to a 16-byte boundary (in either 32 or 64 bit mode) - UInt32 mInstanceStorage; // the ACI implementation object is constructed into this memory - // this member is just a placeholder. it is aligned to a 16byte boundary -}; - -/*! @class APFactory */ -template -class APFactory { -public: - static void *Construct(void *memory, AudioComponentInstance compInstance) - { - return new(memory) Implementor(compInstance); - } - - static void Destruct(void *memory) - { - ((Implementor *)memory)->~Implementor(); - } - - // This is the AudioComponentFactoryFunction. It returns an AudioComponentPlugInInstance. - // The actual implementation object is not created until Open(). - static AudioComponentPlugInInterface *Factory(const AudioComponentDescription * /* inDesc */) - { - AudioComponentPlugInInstance *acpi = - (AudioComponentPlugInInstance *)malloc( offsetof(AudioComponentPlugInInstance, mInstanceStorage) + sizeof(Implementor) ); - acpi->mPlugInInterface.Open = ComponentBase::AP_Open; - acpi->mPlugInInterface.Close = ComponentBase::AP_Close; - acpi->mPlugInInterface.Lookup = APMethodLookup::Lookup; - acpi->mPlugInInterface.reserved = NULL; - acpi->mConstruct = Construct; - acpi->mDestruct = Destruct; - acpi->mPad[0] = NULL; - acpi->mPad[1] = NULL; - return (AudioComponentPlugInInterface*)acpi; - } - - // This is for runtime registration (not for plug-ins loaded from bundles). - static AudioComponent Register(UInt32 type, UInt32 subtype, UInt32 manuf, CFStringRef name, UInt32 vers, UInt32 flags=0) - { - AudioComponentDescription desc = { type, subtype, manuf, flags, 0 }; - return AudioComponentRegister(&desc, name, vers, Factory); - } -}; - -#if !CA_USE_AUDIO_PLUGIN_ONLY -/*! @class ComponentEntryPoint - * @discussion This is only used for a component manager version -*/ -template -class ComponentEntryPoint { -public: - /*! @method Dispatch */ - static OSStatus Dispatch(ComponentParameters *params, Class *obj) - { - OSStatus result = noErr; - - try { - if (params->what == kComponentOpenSelect) { - // solve a host of initialization thread safety issues. - ComponentInitLocker lock; - - ComponentBase::sNewInstanceType = ComponentBase::kComponentMgrInstance; - ComponentInstance ci = (ComponentInstance)(params->params[0]); - Class *This = new Class((AudioComponentInstance)ci); - This->PostConstructor(); // allows base class to do additional initialization - // once the derived class is fully constructed - - CMgr_SetComponentInstanceStorage(ci, (Handle)This); - } else - result = Class::ComponentEntryDispatch(params, obj); - } - COMPONENT_CATCH - - return result; - } - - /*! @method Register */ - static Component Register(OSType compType, OSType subType, OSType manufacturer) - { - ComponentDescription description = {compType, subType, manufacturer, 0, 0}; - Component component = RegisterComponent(&description, (ComponentRoutineUPP) Dispatch, registerComponentGlobal, NULL, NULL, NULL); - if (component != NULL) { - SetDefaultComponent(component, defaultComponentAnyFlagsAnyManufacturerAnySubType); - } - return component; - } -}; - -// NOTE: Component Mgr is deprecated in ML. -// this macro should not be used with new audio components -// it is only for backwards compatibility with Lion and SL. -// this macro registers both a plugin and a component mgr version. -#define AUDIOCOMPONENT_ENTRY(FactoryType, Class) \ - extern "C" OSStatus Class##Entry(ComponentParameters *params, Class *obj); \ - extern "C" OSStatus Class##Entry(ComponentParameters *params, Class *obj) { \ - return ComponentEntryPoint::Dispatch(params, obj); \ - } \ - extern "C" void * Class##Factory(const AudioComponentDescription *inDesc); \ - extern "C" void * Class##Factory(const AudioComponentDescription *inDesc) { \ - return FactoryType::Factory(inDesc); \ - } - // the only component we still support are the carbon based view components - // you should be using this macro now to exclusively register those types -#define VIEW_COMPONENT_ENTRY(Class) \ - extern "C" OSStatus Class##Entry(ComponentParameters *params, Class *obj); \ - extern "C" OSStatus Class##Entry(ComponentParameters *params, Class *obj) { \ - return ComponentEntryPoint::Dispatch(params, obj); \ - } - - /*! @class ComponentRegistrar */ -template -class ComponentRegistrar { -public: - /*! @ctor ComponentRegistrar */ - ComponentRegistrar() { ComponentEntryPoint::Register(Type, Subtype, Manufacturer); } -}; - -#define COMPONENT_REGISTER(Class,Type,Subtype,Manufacturer) \ - static ComponentRegistrar gRegistrar##Class -#else -#define COMPONENT_ENTRY(Class) -#define COMPONENT_REGISTER(Class) -// this macro is used to generate the Entry Point for a given Audio Plugin -// you should be using this macro now with audio components -#define AUDIOCOMPONENT_ENTRY(FactoryType, Class) \ - extern "C" void * Class##Factory(const AudioComponentDescription *inDesc); \ - extern "C" void * Class##Factory(const AudioComponentDescription *inDesc) { \ - return FactoryType::Factory(inDesc); \ - } - -#endif // !CA_USE_AUDIO_PLUGIN_ONLY - - -#endif // __ComponentBase_h__ diff --git a/src/CoreAudio/CoreAudioComponent/AUPublic/AUInstrumentBase/AUInstrumentBase.cpp b/src/CoreAudio/CoreAudioComponent/AUPublic/AUInstrumentBase/AUInstrumentBase.cpp deleted file mode 100644 index 1ce8b308b..000000000 --- a/src/CoreAudio/CoreAudioComponent/AUPublic/AUInstrumentBase/AUInstrumentBase.cpp +++ /dev/null @@ -1,843 +0,0 @@ -/* - File: AUInstrumentBase.cpp - Abstract: AUInstrumentBase.h - Version: 1.1 - - Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple - Inc. ("Apple") in consideration of your agreement to the following - terms, and your use, installation, modification or redistribution of - this Apple software constitutes acceptance of these terms. If you do - not agree with these terms, please do not use, install, modify or - redistribute this Apple software. - - In consideration of your agreement to abide by the following terms, and - subject to these terms, Apple grants you a personal, non-exclusive - license, under Apple's copyrights in this original Apple software (the - "Apple Software"), to use, reproduce, modify and redistribute the Apple - Software, with or without modifications, in source and/or binary forms; - provided that if you redistribute the Apple Software in its entirety and - without modifications, you must retain this notice and the following - text and disclaimers in all such redistributions of the Apple Software. - Neither the name, trademarks, service marks or logos of Apple Inc. may - be used to endorse or promote products derived from the Apple Software - without specific prior written permission from Apple. Except as - expressly stated in this notice, no other rights or licenses, express or - implied, are granted by Apple herein, including but not limited to any - patent rights that may be infringed by your derivative works or by other - works in which the Apple Software may be incorporated. - - The Apple Software is provided by Apple on an "AS IS" basis. APPLE - MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION - THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS - FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND - OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS. - - IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL - OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, - MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED - AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), - STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE - POSSIBILITY OF SUCH DAMAGE. - - Copyright (C) 2014 Apple Inc. All Rights Reserved. - -*/ -#include "AUInstrumentBase.h" -#include "AUMIDIDefs.h" - -#if DEBUG - #define DEBUG_PRINT 0 - #define DEBUG_PRINT_NOTE 0 - #define DEBUG_PRINT_RENDER 0 -#endif - -//////////////////////////////////////////////////////////////////////////////////////////////////////////// - -const UInt32 kEventQueueSize = 1024; - -AUInstrumentBase::AUInstrumentBase( - AudioComponentInstance inInstance, - UInt32 numInputs, - UInt32 numOutputs, - UInt32 numGroups, - UInt32 numParts) - : MusicDeviceBase(inInstance, numInputs, numOutputs, numGroups), - mAbsoluteSampleFrame(0), - mEventQueue(kEventQueueSize), - mNumNotes(0), - mNumActiveNotes(0), - mMaxActiveNotes(0), - mNotes(0), - mNoteSize(0), - mInitNumPartEls(numParts) -{ -#if DEBUG_PRINT - printf("new AUInstrumentBase\n"); -#endif - mFreeNotes.mState = kNoteState_Free; - SetWantsRenderThreadID(true); -} - - -AUInstrumentBase::~AUInstrumentBase() -{ -#if DEBUG_PRINT - printf("delete AUInstrumentBase\n"); -#endif -} - -AUElement * AUInstrumentBase::CreateElement(AudioUnitScope inScope, AudioUnitElement element) -{ - switch (inScope) - { - case kAudioUnitScope_Group: - return new SynthGroupElement(this, element, new MidiControls); - case kAudioUnitScope_Part: - return new SynthPartElement (this, element); - } - return MusicDeviceBase::CreateElement(inScope, element); -} - -void AUInstrumentBase::CreateExtendedElements() -{ - Parts().Initialize(this, kAudioUnitScope_Part, mInitNumPartEls); -} - -AUScope * AUInstrumentBase::GetScopeExtended (AudioUnitScope inScope) -{ - if (inScope == kAudioUnitScope_Part) - return &mPartScope; - return NULL; -} - - -void AUInstrumentBase::SetNotes(UInt32 inNumNotes, UInt32 inMaxActiveNotes, SynthNote* inNotes, UInt32 inNoteDataSize) -{ -#if DEBUG_PRINT_NOTE - printf("AUInstrumentBase::SetNotes %d %d %p %d\n", inNumNotes, inMaxActiveNotes, inNotes, inNoteDataSize); -#endif - mNumNotes = inNumNotes; - mMaxActiveNotes = inMaxActiveNotes; - mNoteSize = inNoteDataSize; - mNotes = inNotes; - - for (UInt32 i=0; iReset(); - mFreeNotes.AddNote(note); - } -} - -UInt32 AUInstrumentBase::CountActiveNotes() -{ - // debugging tool. - UInt32 sum = 0; - for (UInt32 i=0; iGetState() <= kNoteState_Released) - sum++; - } - return sum; -} - -void AUInstrumentBase::AddFreeNote(SynthNote* inNote) -{ - // Fast-released notes are already considered inactive and have already decr'd the active count - if (inNote->GetState() < kNoteState_FastReleased) { - DecNumActiveNotes(); - } -#if DEBUG_PRINT_NOTE - else { - printf("AUInstrumentBase::AddFreeNote: adding fast-released note %p\n", inNote); - } - printf("AUInstrumentBase::AddFreeNote (%p) mNumActiveNotes %lu\n", inNote, mNumActiveNotes); -#endif - mFreeNotes.AddNote(inNote); -} - -OSStatus AUInstrumentBase::Initialize() -{ -/* -TO DO: - Currently ValidFormat will check and validate that the num channels is not being - changed if the AU doesn't support the SupportedNumChannels property - which is correct - - What needs to happen here is that IFF the AU does support this property, (ie, the AU - can be configured to have different num channels than its original configuration) then - the state of the AU at Initialization needs to be validated. - - This is work still to be done - see AUEffectBase for the kind of logic that needs to be applied here -*/ - - // override to call SetNotes - - mNoteIDCounter = 128; // reset this every time we initialise - mAbsoluteSampleFrame = 0; - return noErr; -} - -void AUInstrumentBase::Cleanup() -{ - mFreeNotes.Empty(); -} - - -OSStatus AUInstrumentBase::Reset( AudioUnitScope inScope, - AudioUnitElement inElement) -{ -#if DEBUG_PRINT - printf("AUInstrumentBase::Reset\n"); -#endif - if (inScope == kAudioUnitScope_Global) - { - // kill all notes.. - mFreeNotes.Empty(); - for (UInt32 i=0; iIsSounding()) - note->Kill(0); - note->ListRemove(); - mFreeNotes.AddNote(note); - } - mNumActiveNotes = 0; - mAbsoluteSampleFrame = 0; - - // empty lists. - UInt32 numGroups = Groups().GetNumberOfElements(); - for (UInt32 j = 0; j < numGroups; ++j) - { - SynthGroupElement *group = (SynthGroupElement*)Groups().GetElement(j); - group->Reset(); - } - } - return MusicDeviceBase::Reset(inScope, inElement); -} - -void AUInstrumentBase::PerformEvents(const AudioTimeStamp& inTimeStamp) -{ -#if DEBUG_PRINT_RENDER - printf("AUInstrumentBase::PerformEvents\n"); -#endif - SynthEvent *event; - SynthGroupElement *group; - - while ((event = mEventQueue.ReadItem()) != NULL) - { -#if DEBUG_PRINT_RENDER - printf("event %08X %d\n", event, event->GetEventType()); -#endif - switch(event->GetEventType()) - { - case SynthEvent::kEventType_NoteOn : - RealTimeStartNote(GetElForGroupID (event->GetGroupID()), event->GetNoteID(), - event->GetOffsetSampleFrame(), *event->GetParams()); - break; - case SynthEvent::kEventType_NoteOff : - RealTimeStopNote(event->GetGroupID(), event->GetNoteID(), - event->GetOffsetSampleFrame()); - break; - case SynthEvent::kEventType_SustainOn : - group = GetElForGroupID (event->GetGroupID()); - group->SustainOn(event->GetOffsetSampleFrame()); - break; - case SynthEvent::kEventType_SustainOff : - group = GetElForGroupID (event->GetGroupID()); - group->SustainOff(event->GetOffsetSampleFrame()); - break; - case SynthEvent::kEventType_SostenutoOn : - group = GetElForGroupID (event->GetGroupID()); - group->SostenutoOn(event->GetOffsetSampleFrame()); - break; - case SynthEvent::kEventType_SostenutoOff : - group = GetElForGroupID (event->GetGroupID()); - group->SostenutoOff(event->GetOffsetSampleFrame()); - break; - case SynthEvent::kEventType_AllNotesOff : - group = GetElForGroupID (event->GetGroupID()); - group->AllNotesOff(event->GetOffsetSampleFrame()); - break; - case SynthEvent::kEventType_AllSoundOff : - group = GetElForGroupID (event->GetGroupID()); - group->AllSoundOff(event->GetOffsetSampleFrame()); - break; - case SynthEvent::kEventType_ResetAllControllers : - group = GetElForGroupID (event->GetGroupID()); - group->ResetAllControllers(event->GetOffsetSampleFrame()); - break; - } - - mEventQueue.AdvanceReadPtr(); - } -} - - -OSStatus AUInstrumentBase::Render( AudioUnitRenderActionFlags & ioActionFlags, - const AudioTimeStamp & inTimeStamp, - UInt32 inNumberFrames) -{ - PerformEvents(inTimeStamp); - - AUScope &outputs = Outputs(); - UInt32 numOutputs = outputs.GetNumberOfElements(); - for (UInt32 j = 0; j < numOutputs; ++j) - { - GetOutput(j)->PrepareBuffer(inNumberFrames); // AUBase::DoRenderBus() only does this for the first output element - AudioBufferList& bufferList = GetOutput(j)->GetBufferList(); - for (UInt32 k = 0; k < bufferList.mNumberBuffers; ++k) - { - memset(bufferList.mBuffers[k].mData, 0, bufferList.mBuffers[k].mDataByteSize); - } - } - UInt32 numGroups = Groups().GetNumberOfElements(); - for (UInt32 j = 0; j < numGroups; ++j) - { - SynthGroupElement *group = (SynthGroupElement*)Groups().GetElement(j); - OSStatus err = group->Render((SInt64)inTimeStamp.mSampleTime, inNumberFrames, outputs); - if (err) return err; - } - mAbsoluteSampleFrame += inNumberFrames; - return noErr; -} - -//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -// AUInstrumentBase::ValidFormat -// -//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -bool AUInstrumentBase::ValidFormat( AudioUnitScope inScope, - AudioUnitElement inElement, - const CAStreamBasicDescription & inNewFormat) -{ - // if the AU supports this, then we should just let this go through to the Init call - if (SupportedNumChannels (NULL)) - return MusicDeviceBase::ValidFormat(inScope, inElement, inNewFormat); - - bool isGood = MusicDeviceBase::ValidFormat (inScope, inElement, inNewFormat); - if (!isGood) return false; - - // if we get to here, then the basic criteria is that the - // num channels cannot change on an existing bus - AUIOElement *el = GetIOElement (inScope, inElement); - return (el->GetStreamFormat().NumberChannels() == inNewFormat.NumberChannels()); -} - - -bool AUInstrumentBase::StreamFormatWritable( AudioUnitScope scope, - AudioUnitElement element) -{ - return IsInitialized() ? false : true; -} - -OSStatus AUInstrumentBase::RealTimeStartNote( SynthGroupElement *inGroup, - NoteInstanceID inNoteInstanceID, - UInt32 inOffsetSampleFrame, - const MusicDeviceNoteParams &inParams) -{ - return noErr; -} - -SynthPartElement * AUInstrumentBase::GetPartElement (AudioUnitElement inPartElement) -{ - AUScope & parts = Parts(); - unsigned int numEls = parts.GetNumberOfElements(); - for (unsigned int i = 0; i < numEls; ++i) { - SynthPartElement* el = reinterpret_cast(parts.GetElement(i)); - if (el->GetIndex() == inPartElement) { - return el; - } - } - return NULL; -} - -SynthGroupElement * AUInstrumentBase::GetElForGroupID (MusicDeviceGroupID inGroupID) -{ - AUScope & groups = Groups(); - unsigned int numEls = groups.GetNumberOfElements(); - SynthGroupElement* unassignedEl = NULL; - - for (unsigned int i = 0; i < numEls; ++i) { - SynthGroupElement* el = reinterpret_cast(groups.GetElement(i)); - if (el->GroupID() == inGroupID) - return el; - if (el->GroupID() == SynthGroupElement::kUnassignedGroup) { - unassignedEl = el; - break; // we fill this up from the start of the group scope vector - } - } - if (unassignedEl) { - unassignedEl->SetGroupID(inGroupID); - return unassignedEl; - } - throw static_cast(kAudioUnitErr_InvalidElement); -} - -OSStatus AUInstrumentBase::RealTimeStopNote( - MusicDeviceGroupID inGroupID, - NoteInstanceID inNoteInstanceID, - UInt32 inOffsetSampleFrame) -{ -#if DEBUG_PRINT - printf("AUInstrumentBase::RealTimeStopNote ch %d id %d\n", inGroupID, inNoteInstanceID); -#endif - - SynthGroupElement *gp = (inGroupID == kMusicNoteEvent_Unused - ? GetElForNoteID (inNoteInstanceID) - : GetElForGroupID(inGroupID)); - if (gp) - { - gp->NoteOff (inNoteInstanceID, inOffsetSampleFrame); - } - - return noErr; -} - -SynthGroupElement * AUInstrumentBase::GetElForNoteID (NoteInstanceID inNoteID) -{ -#if DEBUG_PRINT - printf("GetElForNoteID id %u\n", inNoteID); -#endif - AUScope & groups = Groups(); - unsigned int numEls = groups.GetNumberOfElements(); - - for (unsigned int i = 0; i < numEls; ++i) { - SynthGroupElement* el = reinterpret_cast(groups.GetElement(i)); - if (el->GetNote(inNoteID) != NULL) // searches for any note state - return el; - } - throw static_cast(kAudioUnitErr_InvalidElement); -} - -OSStatus AUInstrumentBase::StartNote( MusicDeviceInstrumentID inInstrument, - MusicDeviceGroupID inGroupID, - NoteInstanceID * outNoteInstanceID, - UInt32 inOffsetSampleFrame, - const MusicDeviceNoteParams &inParams) -{ - OSStatus err = noErr; - - NoteInstanceID noteID; - if (outNoteInstanceID) { - noteID = NextNoteID(); - *outNoteInstanceID = noteID; - } else - noteID = (UInt32)inParams.mPitch; - -#if DEBUG_PRINT - printf("AUInstrumentBase::StartNote ch %u, key %u, offset %u\n", inGroupID, (unsigned) inParams.mPitch, inOffsetSampleFrame); -#endif - - if (InRenderThread ()) - { - err = RealTimeStartNote( - GetElForGroupID(inGroupID), - noteID, - inOffsetSampleFrame, - inParams); - } - else - { - SynthEvent *event = mEventQueue.WriteItem(); - if (!event) return -1; // queue full - - event->Set( - SynthEvent::kEventType_NoteOn, - inGroupID, - noteID, - inOffsetSampleFrame, - &inParams - ); - - mEventQueue.AdvanceWritePtr(); - } - return err; -} - -OSStatus AUInstrumentBase::StopNote( MusicDeviceGroupID inGroupID, - NoteInstanceID inNoteInstanceID, - UInt32 inOffsetSampleFrame) -{ -#if DEBUG_PRINT - printf("AUInstrumentBase::StopNote ch %u, id %u, offset %u\n", (unsigned)inGroupID, (unsigned)inNoteInstanceID, inOffsetSampleFrame); -#endif - OSStatus err = noErr; - - if (InRenderThread ()) - { - err = RealTimeStopNote( - inGroupID, - inNoteInstanceID, - inOffsetSampleFrame); - } - else - { - SynthEvent *event = mEventQueue.WriteItem(); - if (!event) return -1; // queue full - - event->Set( - SynthEvent::kEventType_NoteOff, - inGroupID, - inNoteInstanceID, - inOffsetSampleFrame, - NULL - ); - - mEventQueue.AdvanceWritePtr(); - } - return err; -} - -OSStatus AUInstrumentBase::SendPedalEvent(MusicDeviceGroupID inGroupID, UInt32 inEventType, UInt32 inOffsetSampleFrame) -{ - - if (InRenderThread ()) - { - SynthGroupElement *group = GetElForGroupID(inGroupID); - if (!group) - return kAudioUnitErr_InvalidElement; - - switch (inEventType) - { - case SynthEvent::kEventType_SustainOn : - group->SustainOn(inOffsetSampleFrame); - break; - case SynthEvent::kEventType_SustainOff : - group->SustainOff(inOffsetSampleFrame); - break; - case SynthEvent::kEventType_SostenutoOn : - group->SostenutoOn(inOffsetSampleFrame); - break; - case SynthEvent::kEventType_SostenutoOff : - group->SostenutoOff(inOffsetSampleFrame); - break; - case SynthEvent::kEventType_AllNotesOff : - group->AllNotesOff(inOffsetSampleFrame); - mNumActiveNotes = CountActiveNotes(); - break; - case SynthEvent::kEventType_AllSoundOff : - group->AllSoundOff(inOffsetSampleFrame); - mNumActiveNotes = CountActiveNotes(); - break; - case SynthEvent::kEventType_ResetAllControllers : - group->ResetAllControllers(inOffsetSampleFrame); - break; - } - } - else - { - SynthEvent *event = mEventQueue.WriteItem(); - if (!event) return -1; // queue full - - event->Set(inEventType, inGroupID, 0, 0, NULL); - - mEventQueue.AdvanceWritePtr(); - } - return noErr; -} - -OSStatus AUInstrumentBase::HandleControlChange( UInt8 inChannel, - UInt8 inController, - UInt8 inValue, - UInt32 inStartFrame) -{ -#if DEBUG_PRINT - printf("AUInstrumentBase::HandleControlChange ch %u ctlr: %u val: %u frm: %u\n", inChannel, inController, inValue, inStartFrame); -#endif - SynthGroupElement *gp = GetElForGroupID(inChannel); - if (gp) - { - gp->ChannelMessage(inController, inValue); - } - else - return kAudioUnitErr_InvalidElement; - switch (inController) - { - case kMidiController_Sustain : - if (inValue >= 64) - SendPedalEvent(inChannel, SynthEvent::kEventType_SustainOn, inStartFrame); - else - SendPedalEvent(inChannel, SynthEvent::kEventType_SustainOff, inStartFrame); - break; - case kMidiController_Sostenuto : - if (inValue >= 64) - SendPedalEvent(inChannel, SynthEvent::kEventType_SostenutoOn, inStartFrame); - else - SendPedalEvent(inChannel, SynthEvent::kEventType_SostenutoOff, inStartFrame); - break; - case kMidiController_OmniModeOff: - case kMidiController_OmniModeOn: - case kMidiController_MonoModeOn: - case kMidiController_MonoModeOff: - HandleAllSoundOff(inChannel); - break; - } - return noErr; -} - -OSStatus AUInstrumentBase::HandlePitchWheel( UInt8 inChannel, - UInt8 inPitch1, // LSB - UInt8 inPitch2, // MSB - UInt32 inStartFrame) -{ - SynthGroupElement *gp = GetElForGroupID(inChannel); - if (gp) - { - gp->ChannelMessage(kMidiMessage_PitchWheel, (inPitch2 << 7) | inPitch1); - return noErr; - } - else - return kAudioUnitErr_InvalidElement; -} - - -OSStatus AUInstrumentBase::HandleChannelPressure(UInt8 inChannel, - UInt8 inValue, - UInt32 inStartFrame) -{ - SynthGroupElement *gp = GetElForGroupID(inChannel); - if (gp) - { - gp->ChannelMessage(kMidiMessage_ChannelPressure, inValue); - return noErr; - } - else - return kAudioUnitErr_InvalidElement; -} - - -OSStatus AUInstrumentBase::HandleProgramChange( UInt8 inChannel, - UInt8 inValue) -{ -#if DEBUG_PRINT - printf("AUInstrumentBase::HandleProgramChange %u %u\n", inChannel, inValue); -#endif - SynthGroupElement *gp = GetElForGroupID(inChannel); - if (gp) - { - gp->ChannelMessage(kMidiMessage_ProgramChange, inValue); - return noErr; - } - else - return kAudioUnitErr_InvalidElement; -} - - -OSStatus AUInstrumentBase::HandlePolyPressure( UInt8 inChannel, - UInt8 inKey, - UInt8 inValue, - UInt32 inStartFrame) -{ - SynthGroupElement *gp = GetElForGroupID(inChannel); - if (gp) - { - // Combine key and value into single argument. UGLY! - gp->ChannelMessage(kMidiMessage_PolyPressure, (inKey << 7) | inValue); - return noErr; - } - else - return kAudioUnitErr_InvalidElement; -} - - -OSStatus AUInstrumentBase::HandleResetAllControllers( UInt8 inChannel) -{ - return SendPedalEvent (inChannel, SynthEvent::kEventType_ResetAllControllers, 0); -} - - -OSStatus AUInstrumentBase::HandleAllNotesOff( UInt8 inChannel) -{ - return SendPedalEvent (inChannel, SynthEvent::kEventType_AllNotesOff, 0); -} - - -OSStatus AUInstrumentBase::HandleAllSoundOff( UInt8 inChannel) -{ - return SendPedalEvent (inChannel, SynthEvent::kEventType_AllSoundOff, 0); -} - -SynthNote* AUInstrumentBase::GetAFreeNote(UInt32 inFrame) -{ -#if DEBUG_PRINT_NOTE - printf("AUInstrumentBase::GetAFreeNote: %lu available\n", mFreeNotes.Length()); -#endif - SynthNote *note = mFreeNotes.mHead; - if (note) - { - mFreeNotes.RemoveNote(note); - return note; - } - - return VoiceStealing(inFrame, true); -} - -SynthNote* AUInstrumentBase::VoiceStealing(UInt32 inFrame, bool inKillIt) -{ - -#if DEBUG_PRINT_NOTE - printf("AUInstrumentBase::VoiceStealing\n"); -#endif - // free list was empty so we need to kill a note. - UInt32 startState = inKillIt ? kNoteState_FastReleased : kNoteState_Released; - for (UInt32 i = startState; i <= startState; --i) - { -#if DEBUG_PRINT_NOTE - printf(" checking state %d...\n", i); -#endif - UInt32 numGroups = Groups().GetNumberOfElements(); - for (UInt32 j = 0; j < numGroups; ++j) - { - SynthGroupElement *group = (SynthGroupElement*)Groups().GetElement(j); -#if DEBUG_PRINT_NOTE - printf("\tsteal group %d size %d\n", j, group->mNoteList[i].Length()); -#endif - if (group->mNoteList[i].NotEmpty()) { -#if DEBUG_PRINT_NOTE - printf("\t-- not empty\n"); -#endif - SynthNote *note = group->mNoteList[i].FindMostQuietNote(); - if (inKillIt) { -#if DEBUG_PRINT_NOTE - printf("\t--=== KILL ===---\n"); -#endif - note->Kill(inFrame); - group->mNoteList[i].RemoveNote(note); - if (i != kNoteState_FastReleased) - DecNumActiveNotes(); - return note; - } else { -#if DEBUG_PRINT_NOTE - printf("\t--=== FAST RELEASE ===---\n"); -#endif - group->mNoteList[i].RemoveNote(note); - note->FastRelease(inFrame); - group->mNoteList[kNoteState_FastReleased].AddNote(note); - DecNumActiveNotes(); // kNoteState_FastReleased counts as inactive for voice stealing purposes. - return NULL; - } - } - } - } -#if DEBUG_PRINT_NOTE - printf("no notes to steal????\n"); -#endif - return NULL; // It should be impossible to get here. It means there were no notes to kill in any state. -} - -//////////////////////////////////////////////////////////////////////////////////////////////////////////// - -AUMonotimbralInstrumentBase::AUMonotimbralInstrumentBase( - AudioComponentInstance inInstance, - UInt32 numInputs, - UInt32 numOutputs, - UInt32 numGroups, - UInt32 numParts) - : AUInstrumentBase(inInstance, numInputs, numOutputs, numGroups, numParts) -{ -} - -OSStatus AUMonotimbralInstrumentBase::RealTimeStartNote( - SynthGroupElement *inGroup, - NoteInstanceID inNoteInstanceID, - UInt32 inOffsetSampleFrame, - const MusicDeviceNoteParams &inParams) -{ -#if DEBUG_PRINT_RENDER - printf("AUMonotimbralInstrumentBase::RealTimeStartNote %d\n", inNoteInstanceID); -#endif - - if (NumActiveNotes() + 1 > MaxActiveNotes()) - { - VoiceStealing(inOffsetSampleFrame, false); - } - SynthNote *note = GetAFreeNote(inOffsetSampleFrame); - if (!note) return -1; - - SynthPartElement *part = GetPartElement (0); // Only one part for monotimbral - - IncNumActiveNotes(); - inGroup->NoteOn(note, part, inNoteInstanceID, inOffsetSampleFrame, inParams); - - return noErr; -} - -//////////////////////////////////////////////////////////////////////////////////////////////////////////// - - -OSStatus AUMultitimbralInstrumentBase::GetPropertyInfo(AudioUnitPropertyID inID, - AudioUnitScope inScope, - AudioUnitElement inElement, - UInt32 & outDataSize, - Boolean & outWritable) -{ - OSStatus result = noErr; - - switch (inID) - { -#if !TARGET_OS_IPHONE - case kMusicDeviceProperty_PartGroup: - if (inScope != kAudioUnitScope_Part) return kAudioUnitErr_InvalidScope; - outDataSize = sizeof(UInt32); - outWritable = true; - break; -#endif - default: - result = AUInstrumentBase::GetPropertyInfo (inID, inScope, inElement, outDataSize, outWritable); - } - return result; -} - -OSStatus AUMultitimbralInstrumentBase::GetProperty( AudioUnitPropertyID inID, - AudioUnitScope inScope, - AudioUnitElement inElement, - void * outData) -{ - OSStatus result = noErr; - - switch (inID) - { -#if !TARGET_OS_IPHONE - case kMusicDeviceProperty_PartGroup: - if (inScope != kAudioUnitScope_Group) return kAudioUnitErr_InvalidScope; - // ?? - return -1; //unimpl - break; -#endif - default: - result = AUInstrumentBase::GetProperty (inID, inScope, inElement, outData); - } - - return result; -} - - - -OSStatus AUMultitimbralInstrumentBase::SetProperty( AudioUnitPropertyID inID, - AudioUnitScope inScope, - AudioUnitElement inElement, - const void * inData, - UInt32 inDataSize) -{ - OSStatus result = noErr; - - switch (inID) - { -#if !TARGET_OS_IPHONE - case kMusicDeviceProperty_PartGroup: - if (inScope != kAudioUnitScope_Group) return kAudioUnitErr_InvalidScope; - // ?? - return -1; //unimpl - break; -#endif - default: - result = MusicDeviceBase::SetProperty (inID, inScope, inElement, inData, inDataSize); - } - - return result; -} - -//////////////////////////////////////////////////////////////////////////////////////////////////////////// - diff --git a/src/CoreAudio/CoreAudioComponent/AUPublic/AUInstrumentBase/AUInstrumentBase.h b/src/CoreAudio/CoreAudioComponent/AUPublic/AUInstrumentBase/AUInstrumentBase.h deleted file mode 100644 index 3ad7e03a6..000000000 --- a/src/CoreAudio/CoreAudioComponent/AUPublic/AUInstrumentBase/AUInstrumentBase.h +++ /dev/null @@ -1,269 +0,0 @@ -/* - File: AUInstrumentBase.h - Abstract: Part of CoreAudio Utility Classes - Version: 1.1 - - Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple - Inc. ("Apple") in consideration of your agreement to the following - terms, and your use, installation, modification or redistribution of - this Apple software constitutes acceptance of these terms. If you do - not agree with these terms, please do not use, install, modify or - redistribute this Apple software. - - In consideration of your agreement to abide by the following terms, and - subject to these terms, Apple grants you a personal, non-exclusive - license, under Apple's copyrights in this original Apple software (the - "Apple Software"), to use, reproduce, modify and redistribute the Apple - Software, with or without modifications, in source and/or binary forms; - provided that if you redistribute the Apple Software in its entirety and - without modifications, you must retain this notice and the following - text and disclaimers in all such redistributions of the Apple Software. - Neither the name, trademarks, service marks or logos of Apple Inc. may - be used to endorse or promote products derived from the Apple Software - without specific prior written permission from Apple. Except as - expressly stated in this notice, no other rights or licenses, express or - implied, are granted by Apple herein, including but not limited to any - patent rights that may be infringed by your derivative works or by other - works in which the Apple Software may be incorporated. - - The Apple Software is provided by Apple on an "AS IS" basis. APPLE - MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION - THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS - FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND - OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS. - - IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL - OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, - MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED - AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), - STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE - POSSIBILITY OF SUCH DAMAGE. - - Copyright (C) 2014 Apple Inc. All Rights Reserved. - -*/ -#ifndef __AUInstrumentBase__ -#define __AUInstrumentBase__ - -#include -#include -#include -#include -#include -#include "MusicDeviceBase.h" -#include "LockFreeFIFO.h" -#include "SynthEvent.h" -#include "SynthNote.h" -#include "SynthElement.h" - -//////////////////////////////////////////////////////////////////////////////////////////////////////////// - -typedef LockFreeFIFOWithFree SynthEventQueue; - -class AUInstrumentBase : public MusicDeviceBase -{ -public: - AUInstrumentBase( - AudioComponentInstance inInstance, - UInt32 numInputs, - UInt32 numOutputs, - UInt32 numGroups = 16, - UInt32 numParts = 1); - virtual ~AUInstrumentBase(); - - virtual OSStatus Initialize(); - - /*! @method Parts */ - AUScope & Parts() { return mPartScope; } - - /*! @method GetPart */ - AUElement * GetPart( AudioUnitElement inElement) - { - return mPartScope.SafeGetElement(inElement); - } - - virtual AUScope * GetScopeExtended (AudioUnitScope inScope); - - virtual AUElement * CreateElement( AudioUnitScope inScope, - AudioUnitElement inElement); - - virtual void CreateExtendedElements(); - - virtual void Cleanup(); - - virtual OSStatus Reset( AudioUnitScope inScope, - AudioUnitElement inElement); - - virtual bool ValidFormat( AudioUnitScope inScope, - AudioUnitElement inElement, - const CAStreamBasicDescription & inNewFormat); - - virtual bool StreamFormatWritable( AudioUnitScope scope, - AudioUnitElement element); - - virtual bool CanScheduleParameters() const { return false; } - - virtual OSStatus Render( AudioUnitRenderActionFlags & ioActionFlags, - const AudioTimeStamp & inTimeStamp, - UInt32 inNumberFrames); - - virtual OSStatus StartNote( MusicDeviceInstrumentID inInstrument, - MusicDeviceGroupID inGroupID, - NoteInstanceID * outNoteInstanceID, - UInt32 inOffsetSampleFrame, - const MusicDeviceNoteParams &inParams); - - virtual OSStatus StopNote( MusicDeviceGroupID inGroupID, - NoteInstanceID inNoteInstanceID, - UInt32 inOffsetSampleFrame); - - virtual OSStatus RealTimeStartNote( SynthGroupElement *inGroup, - NoteInstanceID inNoteInstanceID, - UInt32 inOffsetSampleFrame, - const MusicDeviceNoteParams &inParams); - - virtual OSStatus RealTimeStopNote( MusicDeviceGroupID inGroupID, - NoteInstanceID inNoteInstanceID, - UInt32 inOffsetSampleFrame); - - virtual OSStatus HandleControlChange( UInt8 inChannel, - UInt8 inController, - UInt8 inValue, - UInt32 inStartFrame); - - virtual OSStatus HandlePitchWheel( UInt8 inChannel, - UInt8 inPitch1, - UInt8 inPitch2, - UInt32 inStartFrame); - - virtual OSStatus HandleChannelPressure( UInt8 inChannel, - UInt8 inValue, - UInt32 inStartFrame); - - virtual OSStatus HandleProgramChange( UInt8 inChannel, - UInt8 inValue); - - virtual OSStatus HandlePolyPressure( UInt8 inChannel, - UInt8 inKey, - UInt8 inValue, - UInt32 inStartFrame); - - virtual OSStatus HandleResetAllControllers( UInt8 inChannel); - - virtual OSStatus HandleAllNotesOff( UInt8 inChannel); - - virtual OSStatus HandleAllSoundOff( UInt8 inChannel); - - SynthNote* GetNote(UInt32 inIndex) - { - if (!mNotes) - throw std::runtime_error("no notes"); - return (SynthNote*)((char*)mNotes + inIndex * mNoteSize); - } - - SynthNote* GetAFreeNote(UInt32 inFrame); - void AddFreeNote(SynthNote* inNote); - - friend class SynthGroupElement; -protected: - - UInt32 NextNoteID() { return OSAtomicIncrement32((int32_t *)&mNoteIDCounter); } - - - // call SetNotes in your Initialize() method to give the base class your note structures and to set the maximum - // number of active notes. inNoteData should be an array of size inMaxActiveNotes. - void SetNotes(UInt32 inNumNotes, UInt32 inMaxActiveNotes, SynthNote* inNotes, UInt32 inNoteSize); - - void PerformEvents( const AudioTimeStamp & inTimeStamp); - OSStatus SendPedalEvent(MusicDeviceGroupID inGroupID, UInt32 inEventType, UInt32 inOffsetSampleFrame); - virtual SynthNote* VoiceStealing(UInt32 inFrame, bool inKillIt); - UInt32 MaxActiveNotes() const { return mMaxActiveNotes; } - UInt32 NumActiveNotes() const { return mNumActiveNotes; } - void IncNumActiveNotes() { ++mNumActiveNotes; } - void DecNumActiveNotes() { --mNumActiveNotes; } - UInt32 CountActiveNotes(); - - SynthPartElement * GetPartElement (AudioUnitElement inPartElement); - - // this call throws if there's no assigned element for the group ID - virtual SynthGroupElement * GetElForGroupID (MusicDeviceGroupID inGroupID); - virtual SynthGroupElement * GetElForNoteID (NoteInstanceID inNoteID); - - SInt64 mAbsoluteSampleFrame; - - -private: - - SInt32 mNoteIDCounter; - - SynthEventQueue mEventQueue; - - UInt32 mNumNotes; - UInt32 mNumActiveNotes; - UInt32 mMaxActiveNotes; - SynthNote* mNotes; - SynthNoteList mFreeNotes; - UInt32 mNoteSize; - - AUScope mPartScope; - const UInt32 mInitNumPartEls; -}; - -//////////////////////////////////////////////////////////////////////////////////////////////////////////// - -class AUMonotimbralInstrumentBase : public AUInstrumentBase -{ -public: - AUMonotimbralInstrumentBase( - AudioComponentInstance inInstance, - UInt32 numInputs, - UInt32 numOutputs, - UInt32 numGroups = 16, - UInt32 numParts = 1); - - virtual OSStatus RealTimeStartNote( SynthGroupElement *inGroup, - NoteInstanceID inNoteInstanceID, - UInt32 inOffsetSampleFrame, - const MusicDeviceNoteParams &inParams); -}; - -//////////////////////////////////////////////////////////////////////////////////////////////////////////// - -// this is a work in progress! The mono-timbral one is finished though! -class AUMultitimbralInstrumentBase : public AUInstrumentBase -{ -public: - AUMultitimbralInstrumentBase( - AudioComponentInstance inInstance, - UInt32 numInputs, - UInt32 numOutputs, - UInt32 numGroups, - UInt32 numParts); - - virtual OSStatus GetPropertyInfo( AudioUnitPropertyID inID, - AudioUnitScope inScope, - AudioUnitElement inElement, - UInt32 & outDataSize, - Boolean & outWritable); - - virtual OSStatus GetProperty( AudioUnitPropertyID inID, - AudioUnitScope inScope, - AudioUnitElement inElement, - void * outData); - - virtual OSStatus SetProperty( AudioUnitPropertyID inID, - AudioUnitScope inScope, - AudioUnitElement inElement, - const void * inData, - UInt32 inDataSize); - -private: - -}; - -//////////////////////////////////////////////////////////////////////////////////////////////////////////// - -#endif - diff --git a/src/CoreAudio/CoreAudioComponent/AUPublic/AUInstrumentBase/LockFreeFIFO.h b/src/CoreAudio/CoreAudioComponent/AUPublic/AUInstrumentBase/LockFreeFIFO.h deleted file mode 100644 index ea6c4c26e..000000000 --- a/src/CoreAudio/CoreAudioComponent/AUPublic/AUInstrumentBase/LockFreeFIFO.h +++ /dev/null @@ -1,168 +0,0 @@ -/* - File: LockFreeFIFO.h - Abstract: Part of CoreAudio Utility Classes - Version: 1.1 - - Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple - Inc. ("Apple") in consideration of your agreement to the following - terms, and your use, installation, modification or redistribution of - this Apple software constitutes acceptance of these terms. If you do - not agree with these terms, please do not use, install, modify or - redistribute this Apple software. - - In consideration of your agreement to abide by the following terms, and - subject to these terms, Apple grants you a personal, non-exclusive - license, under Apple's copyrights in this original Apple software (the - "Apple Software"), to use, reproduce, modify and redistribute the Apple - Software, with or without modifications, in source and/or binary forms; - provided that if you redistribute the Apple Software in its entirety and - without modifications, you must retain this notice and the following - text and disclaimers in all such redistributions of the Apple Software. - Neither the name, trademarks, service marks or logos of Apple Inc. may - be used to endorse or promote products derived from the Apple Software - without specific prior written permission from Apple. Except as - expressly stated in this notice, no other rights or licenses, express or - implied, are granted by Apple herein, including but not limited to any - patent rights that may be infringed by your derivative works or by other - works in which the Apple Software may be incorporated. - - The Apple Software is provided by Apple on an "AS IS" basis. APPLE - MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION - THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS - FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND - OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS. - - IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL - OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, - MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED - AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), - STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE - POSSIBILITY OF SUCH DAMAGE. - - Copyright (C) 2014 Apple Inc. All Rights Reserved. - -*/ -#include - -template -class LockFreeFIFOWithFree -{ - LockFreeFIFOWithFree(); // private, unimplemented. -public: - LockFreeFIFOWithFree(UInt32 inMaxSize) - : mReadIndex(0), mWriteIndex(0), mFreeIndex(0) - { - //assert(IsPowerOfTwo(inMaxSize)); - mItems = new ITEM[inMaxSize]; - mMask = inMaxSize - 1; - } - - ~LockFreeFIFOWithFree() - { - delete [] mItems; - } - - - void Reset() - { - FreeItems(); - mReadIndex = 0; - mWriteIndex = 0; - mFreeIndex = 0; - } - - ITEM* WriteItem() - { - //printf("WriteItem %d %d\n", mReadIndex, mWriteIndex); - FreeItems(); // free items on the write thread. - int32_t nextWriteIndex = (mWriteIndex + 1) & mMask; - if (nextWriteIndex == mFreeIndex) return NULL; - return &mItems[mWriteIndex]; - } - - ITEM* ReadItem() - { - //printf("ReadItem %d %d\n", mReadIndex, mWriteIndex); - if (mReadIndex == mWriteIndex) return NULL; - return &mItems[mReadIndex]; - } - void AdvanceWritePtr() { OSAtomicCompareAndSwap32(mWriteIndex, (mWriteIndex + 1) & mMask, &mWriteIndex); } - void AdvanceReadPtr() { OSAtomicCompareAndSwap32(mReadIndex, (mReadIndex + 1) & mMask, &mReadIndex); } -private: - ITEM* FreeItem() - { - if (mFreeIndex == mReadIndex) return NULL; - return &mItems[mFreeIndex]; - } - void AdvanceFreePtr() { OSAtomicCompareAndSwap32(mFreeIndex, (mFreeIndex + 1) & mMask, &mFreeIndex); } - - void FreeItems() - { - ITEM* item; - while ((item = FreeItem()) != NULL) - { - item->Free(); - AdvanceFreePtr(); - } - } - - volatile int32_t mReadIndex, mWriteIndex, mFreeIndex; - int32_t mMask; - ITEM *mItems; -}; - - - -// Same as above but no free. - -template -class LockFreeFIFO -{ - LockFreeFIFO(); // private, unimplemented. -public: - LockFreeFIFO(UInt32 inMaxSize) - : mReadIndex(0), mWriteIndex(0) - { - //assert(IsPowerOfTwo(inMaxSize)); - mItems = new ITEM[inMaxSize]; - mMask = inMaxSize - 1; - } - - ~LockFreeFIFO() - { - delete [] mItems; - } - - void Reset() - { - mReadIndex = 0; - mWriteIndex = 0; - } - - ITEM* WriteItem() - { - int32_t nextWriteIndex = (mWriteIndex + 1) & mMask; - if (nextWriteIndex == mReadIndex) return NULL; - return &mItems[mWriteIndex]; - } - - ITEM* ReadItem() - { - if (mReadIndex == mWriteIndex) return NULL; - return &mItems[mReadIndex]; - } - - // the CompareAndSwap will always succeed. We use CompareAndSwap because it calls the PowerPC sync instruction, - // plus any processor bug workarounds for various CPUs. - void AdvanceWritePtr() { OSAtomicCompareAndSwap32(mWriteIndex, (mWriteIndex + 1) & mMask, &mWriteIndex); } - void AdvanceReadPtr() { OSAtomicCompareAndSwap32(mReadIndex, (mReadIndex + 1) & mMask, &mReadIndex); } - -private: - - volatile int32_t mReadIndex, mWriteIndex; - int32_t mMask; - ITEM *mItems; -}; - diff --git a/src/CoreAudio/CoreAudioComponent/AUPublic/AUInstrumentBase/MIDIControlHandler.h b/src/CoreAudio/CoreAudioComponent/AUPublic/AUInstrumentBase/MIDIControlHandler.h deleted file mode 100644 index 0f8003fcd..000000000 --- a/src/CoreAudio/CoreAudioComponent/AUPublic/AUInstrumentBase/MIDIControlHandler.h +++ /dev/null @@ -1,92 +0,0 @@ -/* - File: MIDIControlHandler.h - Abstract: Part of CoreAudio Utility Classes - Version: 1.1 - - Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple - Inc. ("Apple") in consideration of your agreement to the following - terms, and your use, installation, modification or redistribution of - this Apple software constitutes acceptance of these terms. If you do - not agree with these terms, please do not use, install, modify or - redistribute this Apple software. - - In consideration of your agreement to abide by the following terms, and - subject to these terms, Apple grants you a personal, non-exclusive - license, under Apple's copyrights in this original Apple software (the - "Apple Software"), to use, reproduce, modify and redistribute the Apple - Software, with or without modifications, in source and/or binary forms; - provided that if you redistribute the Apple Software in its entirety and - without modifications, you must retain this notice and the following - text and disclaimers in all such redistributions of the Apple Software. - Neither the name, trademarks, service marks or logos of Apple Inc. may - be used to endorse or promote products derived from the Apple Software - without specific prior written permission from Apple. Except as - expressly stated in this notice, no other rights or licenses, express or - implied, are granted by Apple herein, including but not limited to any - patent rights that may be infringed by your derivative works or by other - works in which the Apple Software may be incorporated. - - The Apple Software is provided by Apple on an "AS IS" basis. APPLE - MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION - THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS - FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND - OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS. - - IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL - OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, - MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED - AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), - STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE - POSSIBILITY OF SUCH DAMAGE. - - Copyright (C) 2014 Apple Inc. All Rights Reserved. - -*/ -#ifndef __MIDICONTROLHANDLER_H__ -#define __MIDICONTROLHANDLER_H__ - -#include - -/*! Abstract interface base class for classes which handle all incoming MIDI data */ - -class MIDIControlHandler -{ -public: - virtual ~MIDIControlHandler() {} - virtual void Reset() = 0; //! Restore all state to defaults - virtual bool SetProgramChange(UInt16 inProgram) = 0; - virtual bool SetPitchWheel(UInt16 inValue) = 0; - virtual bool SetChannelPressure(UInt8 inValue) = 0; - virtual bool SetPolyPressure(UInt8 inKey, UInt8 inValue) = 0; - virtual bool SetController(UInt8 inControllerNumber, UInt8 inValue) = 0; - virtual bool SetSysex(void *inSysexMsg) = 0; - - virtual float GetPitchBend() const = 0; - - /*! Default controller values. These represent MSB values unless indicated in the name */ - - enum - { - kDefault_Midpoint = 0x40, //! Used for all center-null-point controllers - kDefault_Volume = 100, - kDefault_Pan = kDefault_Midpoint, - kDefault_ModWheel = 0, - kDefault_Pitch = kDefault_Midpoint, - kDefault_Expression = 0x7f, - kDefault_ChannelPressure = 0, - kDefault_ReverbSend = 40, - kDefault_ChorusSend = 0, - - kDefault_RPN_LSB = 0x7f, - kDefault_RPN_MSB = 0x7f, - kDefault_PitchBendRange = 2, - kDefault_FineTuning = kDefault_Midpoint, - kDefault_CoarseTuning = kDefault_Midpoint, - kDefault_ModDepthRange = 0, - kDefault_ModDepthRangeLSB = kDefault_Midpoint - }; -}; - -#endif // __MIDICONTROLHANDLER_H__ diff --git a/src/CoreAudio/CoreAudioComponent/AUPublic/AUInstrumentBase/SynthElement.cpp b/src/CoreAudio/CoreAudioComponent/AUPublic/AUInstrumentBase/SynthElement.cpp deleted file mode 100644 index fd329f84e..000000000 --- a/src/CoreAudio/CoreAudioComponent/AUPublic/AUInstrumentBase/SynthElement.cpp +++ /dev/null @@ -1,419 +0,0 @@ -/* - File: SynthElement.cpp - Abstract: SynthElement.h - Version: 1.1 - - Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple - Inc. ("Apple") in consideration of your agreement to the following - terms, and your use, installation, modification or redistribution of - this Apple software constitutes acceptance of these terms. If you do - not agree with these terms, please do not use, install, modify or - redistribute this Apple software. - - In consideration of your agreement to abide by the following terms, and - subject to these terms, Apple grants you a personal, non-exclusive - license, under Apple's copyrights in this original Apple software (the - "Apple Software"), to use, reproduce, modify and redistribute the Apple - Software, with or without modifications, in source and/or binary forms; - provided that if you redistribute the Apple Software in its entirety and - without modifications, you must retain this notice and the following - text and disclaimers in all such redistributions of the Apple Software. - Neither the name, trademarks, service marks or logos of Apple Inc. may - be used to endorse or promote products derived from the Apple Software - without specific prior written permission from Apple. Except as - expressly stated in this notice, no other rights or licenses, express or - implied, are granted by Apple herein, including but not limited to any - patent rights that may be infringed by your derivative works or by other - works in which the Apple Software may be incorporated. - - The Apple Software is provided by Apple on an "AS IS" basis. APPLE - MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION - THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS - FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND - OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS. - - IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL - OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, - MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED - AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), - STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE - POSSIBILITY OF SUCH DAMAGE. - - Copyright (C) 2014 Apple Inc. All Rights Reserved. - -*/ -#include "SynthElement.h" -#include "AUInstrumentBase.h" -#include "AUMIDIDefs.h" - -#undef DEBUG_PRINT -#define DEBUG_PRINT 0 -#define DEBUG_PRINT_NOTE 0 -#define DEBUG_PRINT_RENDER 0 - -//////////////////////////////////////////////////////////////////////////////////////////////////////////// -MidiControls::MidiControls() -{ - Reset(); -} - -void MidiControls::Reset() -{ - memset(mControls, 0, sizeof(mControls)); - memset(mPolyPressure, 0, sizeof(mPolyPressure)); - mMonoPressure = 0; - mProgramChange = 0; - mPitchBend = 0; - mActiveRPN = 0; - mActiveNRPN = 0; - mActiveRPValue = 0; - mActiveNRPValue = 0; - mControls[kMidiController_Pan] = 64; - mControls[kMidiController_Expression] = 127; - mPitchBendDepth = 24 << 7; - mFPitchBendDepth = 24.0f; - mFPitchBend = 0.0f; -} - - -SynthElement::SynthElement(AUInstrumentBase *audioUnit, UInt32 inElement) - : AUElement(audioUnit), mIndex(inElement) -{ -} - -SynthElement::~SynthElement() -{ -} - -SynthGroupElement::SynthGroupElement(AUInstrumentBase *audioUnit, UInt32 inElement, MIDIControlHandler *inHandler) - : SynthElement(audioUnit, inElement), - mCurrentAbsoluteFrame(-1), - mMidiControlHandler(inHandler), - mSustainIsOn(false), mSostenutoIsOn(false), mOutputBus(0), mGroupID(kUnassignedGroup) -{ - for (UInt32 i=0; i(kAudioUnitErr_InvalidElement); - mGroupID = inGroup; -} - -void SynthGroupElement::Reset() -{ -#if DEBUG_PRINT - printf("SynthGroupElement::Reset\n"); -#endif - mMidiControlHandler->Reset(); - for (UInt32 i=0; imNoteID != inNoteID) - { -#if DEBUG_PRINT_RENDER - printf(" checking %p id: %d\n", note, note->mNoteID); -#endif - note = note->mNext; - } - if (note) - { -#if DEBUG_PRINT_RENDER - printf(" found %p\n", note); -#endif - break; - } - } - return note; -} - -void SynthGroupElement::NoteOn(SynthNote *note, - SynthPartElement *part, - NoteInstanceID inNoteID, - UInt32 inOffsetSampleFrame, - const MusicDeviceNoteParams &inParams) -{ -#if DEBUG_PRINT_NOTE - printf("SynthGroupElement::NoteOn %d\n", inNoteID); -#endif - // TODO: CONSIDER FIXING this to not need to initialize mCurrentAbsoluteFrame to -1. - UInt64 absoluteFrame = (mCurrentAbsoluteFrame == -1) ? inOffsetSampleFrame : mCurrentAbsoluteFrame + inOffsetSampleFrame; - if (note->AttackNote(part, this, inNoteID, absoluteFrame, inOffsetSampleFrame, inParams)) { - mNoteList[kNoteState_Attacked].AddNote(note); - } -} - -void SynthGroupElement::NoteOff(NoteInstanceID inNoteID, UInt32 inFrame) -{ -#if DEBUG_PRINT_NOTE - printf("SynthGroupElement::NoteOff %d\n", inNoteID); -#endif - UInt32 noteState = kNoteState_Attacked; - SynthNote *note = GetNote(inNoteID, true, ¬eState); // asking for unreleased only - if (note) - { -#if DEBUG_PRINT_NOTE - printf(" old note state: %d\n", note->mState); -#endif - if (noteState == kNoteState_Attacked) - { - mNoteList[noteState].RemoveNote(note); - if (mSustainIsOn) { - mNoteList[kNoteState_ReleasedButSustained].AddNote(note); - } else { - note->Release(inFrame); - mNoteList[kNoteState_Released].AddNote(note); - } -#if DEBUG_PRINT_NOTE - printf(" new note state: %d\n", note->mState); -#endif - } - else /* if (noteState == kNoteState_Sostenutoed) */ - { - mNoteList[kNoteState_Sostenutoed].RemoveNote(note); - mNoteList[kNoteState_ReleasedButSostenutoed].AddNote(note); - } - } -} - -void SynthGroupElement::NoteEnded(SynthNote *inNote, UInt32 inFrame) -{ -#if DEBUG_PRINT_NOTE - printf("SynthGroupElement::NoteEnded: id %d state %d\n", inNote->mNoteID, inNote->mState); -#endif - if (inNote->IsSounding()) { - SynthNoteList *list = &mNoteList[inNote->GetState()]; - list->RemoveNote(inNote); - } - - GetAUInstrument()->AddFreeNote(inNote); -} - -void SynthGroupElement::NoteFastReleased(SynthNote *inNote) -{ -#if DEBUG_PRINT_NOTE - printf("SynthGroupElement::NoteFastReleased id %d state %d\n", inNote->mNoteID, inNote->mState); -#endif - if (inNote->IsActive()) { - mNoteList[inNote->GetState()].RemoveNote(inNote); - GetAUInstrument()->DecNumActiveNotes(); - mNoteList[kNoteState_FastReleased].AddNote(inNote); - } - else { - Assert(true, "ASSERT FAILED: Attempting to fast-release non-active note"); - } -} - -bool SynthGroupElement::ChannelMessage(UInt16 controllerID, UInt16 inValue) -{ - bool handled = true; -#if DEBUG_PRINT - printf("SynthGroupElement::ChannelMessage(0x%x, %u)\n", controllerID, inValue); -#endif - // Sustain and sostenuto are "pedal events", and are handled during render cycle - if (controllerID <= kMidiController_RPN_MSB && controllerID != kMidiController_Sustain && controllerID != kMidiController_Sostenuto) - handled = mMidiControlHandler->SetController(controllerID, UInt8(inValue)); - else - { - switch (controllerID) - { - case kMidiMessage_ProgramChange: - handled = mMidiControlHandler->SetProgramChange(inValue); - break; - case kMidiMessage_PitchWheel: - handled = mMidiControlHandler->SetPitchWheel(inValue); - break; - case kMidiMessage_ChannelPressure: -#if DEBUG_PRINT - printf("SynthGroupElement::ChannelMessage: Channel Pressure %u\n", inValue); -#endif - handled = mMidiControlHandler->SetChannelPressure(UInt8(inValue)); - break; - case kMidiMessage_PolyPressure: - { UInt8 inKey = inValue >> 7; - UInt8 val = inValue & 0x7f; - handled = mMidiControlHandler->SetPolyPressure(inKey, val); - break; - } - default: - handled = false; - break; - } - } - return handled; -} - -void SynthGroupElement::SostenutoOn(UInt32 inFrame) -{ -#if DEBUG_PRINT - printf("SynthGroupElement::SostenutoOn\n"); -#endif - if (!mSostenutoIsOn) { - mMidiControlHandler->SetController(kMidiController_Sostenuto, 127); - mSostenutoIsOn = true; - mNoteList[kNoteState_Sostenutoed].TransferAllFrom(&mNoteList[kNoteState_Attacked], inFrame); - } -} - -void SynthGroupElement::SostenutoOff(UInt32 inFrame) -{ -#if DEBUG_PRINT - printf("SynthGroupElement::SostenutoOff\n"); -#endif - if (mSostenutoIsOn) { - mMidiControlHandler->SetController(kMidiController_Sostenuto, 0); - mSostenutoIsOn = false; - mNoteList[kNoteState_Attacked].TransferAllFrom(&mNoteList[kNoteState_Sostenutoed], inFrame); - if (mSustainIsOn) - mNoteList[kNoteState_ReleasedButSustained].TransferAllFrom(&mNoteList[kNoteState_ReleasedButSostenutoed], inFrame); - else - mNoteList[kNoteState_Released].TransferAllFrom(&mNoteList[kNoteState_ReleasedButSostenutoed], inFrame); - } -} - - -void SynthGroupElement::SustainOn(UInt32 inFrame) -{ -#if DEBUG_PRINT -// printf("SynthGroupElement::SustainOn\n"); -#endif - if (!mSustainIsOn) { - mMidiControlHandler->SetController(kMidiController_Sustain, 127); - mSustainIsOn = true; - } -} - -void SynthGroupElement::SustainOff(UInt32 inFrame) -{ -#if DEBUG_PRINT -// printf("SynthGroupElement::SustainOff\n"); -#endif - if (mSustainIsOn) { - mMidiControlHandler->SetController(kMidiController_Sustain, 0); - mSustainIsOn = false; - - mNoteList[kNoteState_Released].TransferAllFrom(&mNoteList[kNoteState_ReleasedButSustained], inFrame); - } -} - -void SynthGroupElement::AllNotesOff(UInt32 inFrame) -{ -#if DEBUG_PRINT - printf("SynthGroupElement::AllNotesOff\n"); -#endif - SynthNote *note; - for (UInt32 i=0 ; i<=kNoteState_Sostenutoed; ++i) - { - UInt32 newState = (i == kNoteState_Attacked) ? - kNoteState_Released : kNoteState_ReleasedButSostenutoed; - note = mNoteList[i].mHead; - while (note) - { - SynthNote *nextNote = note->mNext; - - mNoteList[i].RemoveNote(note); - note->Release(inFrame); - mNoteList[newState].AddNote(note); - - note = nextNote; - } - } -} - -void SynthGroupElement::AllSoundOff(UInt32 inFrame) -{ -#if DEBUG_PRINT - printf("SynthGroupElement::AllSoundOff\n"); -#endif - SynthNote *note; - - for (UInt32 i=0 ; imNext; - - mNoteList[i].RemoveNote(note); - note->FastRelease(inFrame); - mNoteList[kNoteState_FastReleased].AddNote(note); - GetAUInstrument()->DecNumActiveNotes(); - note = nextNote; - } - } -} - -void SynthGroupElement::ResetAllControllers(UInt32 inFrame) -{ -#if DEBUG_PRINT - printf("SynthGroupElement::ResetAllControllers\n"); -#endif - mMidiControlHandler->Reset(); -} - -OSStatus SynthGroupElement::Render(SInt64 inAbsoluteSampleFrame, UInt32 inNumberFrames, AUScope &outputs) -{ - // Avoid duplicate calls at same sample offset - if (inAbsoluteSampleFrame != mCurrentAbsoluteFrame) - { - mCurrentAbsoluteFrame = inAbsoluteSampleFrame; - AudioBufferList* buffArray[16]; - UInt32 numOutputs = outputs.GetNumberOfElements(); - for (UInt32 outBus = 0; outBus < numOutputs && outBus < 16; ++outBus) - { - buffArray[outBus] = &GetAudioUnit()->GetOutput(outBus)->GetBufferList(); - } - - for (UInt32 i=0 ; imNext; - - OSStatus err = note->Render(inAbsoluteSampleFrame, inNumberFrames, buffArray, numOutputs); - if (err) return err; - - note = nextNote; - } - } - } - return noErr; -} - - diff --git a/src/CoreAudio/CoreAudioComponent/AUPublic/AUInstrumentBase/SynthElement.h b/src/CoreAudio/CoreAudioComponent/AUPublic/AUInstrumentBase/SynthElement.h deleted file mode 100644 index 4ca364310..000000000 --- a/src/CoreAudio/CoreAudioComponent/AUPublic/AUInstrumentBase/SynthElement.h +++ /dev/null @@ -1,227 +0,0 @@ -/* - File: SynthElement.h - Abstract: Part of CoreAudio Utility Classes - Version: 1.1 - - Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple - Inc. ("Apple") in consideration of your agreement to the following - terms, and your use, installation, modification or redistribution of - this Apple software constitutes acceptance of these terms. If you do - not agree with these terms, please do not use, install, modify or - redistribute this Apple software. - - In consideration of your agreement to abide by the following terms, and - subject to these terms, Apple grants you a personal, non-exclusive - license, under Apple's copyrights in this original Apple software (the - "Apple Software"), to use, reproduce, modify and redistribute the Apple - Software, with or without modifications, in source and/or binary forms; - provided that if you redistribute the Apple Software in its entirety and - without modifications, you must retain this notice and the following - text and disclaimers in all such redistributions of the Apple Software. - Neither the name, trademarks, service marks or logos of Apple Inc. may - be used to endorse or promote products derived from the Apple Software - without specific prior written permission from Apple. Except as - expressly stated in this notice, no other rights or licenses, express or - implied, are granted by Apple herein, including but not limited to any - patent rights that may be infringed by your derivative works or by other - works in which the Apple Software may be incorporated. - - The Apple Software is provided by Apple on an "AS IS" basis. APPLE - MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION - THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS - FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND - OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS. - - IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL - OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, - MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED - AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), - STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE - POSSIBILITY OF SUCH DAMAGE. - - Copyright (C) 2014 Apple Inc. All Rights Reserved. - -*/ -#ifndef __SynthElement__ -#define __SynthElement__ - -#include -#include "MusicDeviceBase.h" -#include "SynthNoteList.h" -#include "MIDIControlHandler.h" - -//////////////////////////////////////////////////////////////////////////////////////////////////////////// -class AUInstrumentBase; - -class SynthElement : public AUElement -{ -public: - SynthElement(AUInstrumentBase *audioUnit, UInt32 inElement); - virtual ~SynthElement(); - - UInt32 GetIndex() const { return mIndex; } - - AUInstrumentBase* GetAUInstrument() { return (AUInstrumentBase*)GetAudioUnit(); } - -private: - UInt32 mIndex; -}; - -class MidiControls : public MIDIControlHandler -{ - enum { kMaxControls = 128 }; -public: - MidiControls(); - virtual ~MidiControls() {} - virtual void Reset(); - virtual bool SetProgramChange(UInt16 inProgram) { mProgramChange = inProgram; return true; } - virtual bool SetPitchWheel(UInt16 inValue) { - mPitchBend = inValue; - mFPitchBend = (float)(((SInt16)mPitchBend - 8192) / 8192.); - return true; - } - virtual bool SetChannelPressure(UInt8 inValue) { mMonoPressure = inValue; return true; } - virtual bool SetPolyPressure(UInt8 inKey, UInt8 inValue) { - mPolyPressure[inKey] = inValue; - return true; - } - virtual bool SetController(UInt8 inControllerNumber, UInt8 inValue) { - if (inControllerNumber < kMaxControls) { - mControls[inControllerNumber] = inValue; - return true; - } - return false; - } - virtual bool SetSysex(void *inSysexMsg) { return false; } - - virtual float GetPitchBend() const { return mFPitchBend * mFPitchBendDepth; } - - SInt16 GetHiResControl(UInt32 inIndex) const - { - return ((mControls[inIndex] & 127) << 7) | (mControls[inIndex + 32] & 127); - } - - float GetControl(UInt32 inIndex) const - { - if (inIndex < 32) { - return (float)(mControls[inIndex] + (mControls[inIndex + 32] / 127.)); - } else { - return (float)mControls[inIndex]; - } - } - - -private: - - UInt8 mControls[128]; - UInt8 mPolyPressure[128]; - UInt8 mMonoPressure; - UInt8 mProgramChange; - UInt16 mPitchBend; - UInt16 mActiveRPN; - UInt16 mActiveNRPN; - UInt16 mActiveRPValue; - UInt16 mActiveNRPValue; - - UInt16 mPitchBendDepth; - float mFPitchBendDepth; - float mFPitchBend; - - void SetHiResControl(UInt32 inIndex, UInt8 inMSB, UInt8 inLSB) - { - mControls[inIndex] = inMSB; - mControls[inIndex + 32] = inLSB; - } - -}; - - -class SynthGroupElement : public SynthElement -{ -public: - enum { - kUnassignedGroup = 0xFFFFFFFF - }; - - SynthGroupElement(AUInstrumentBase *audioUnit, UInt32 inElement, MIDIControlHandler *inHandler); - virtual ~SynthGroupElement(); - - virtual void NoteOn(SynthNote *note, SynthPartElement *part, NoteInstanceID inNoteID, UInt32 inOffsetSampleFrame, const MusicDeviceNoteParams &inParams); - virtual void NoteOff(NoteInstanceID inNoteID, UInt32 inOffsetSampleFrame); - void SustainOn(UInt32 inFrame); - void SustainOff(UInt32 inFrame); - void SostenutoOn(UInt32 inFrame); - void SostenutoOff(UInt32 inFrame); - - void NoteEnded(SynthNote *inNote, UInt32 inFrame); - void NoteFastReleased(SynthNote *inNote); - - virtual bool ChannelMessage(UInt16 controlID, UInt16 controlValue); - virtual void AllNotesOff(UInt32 inFrame); - virtual void AllSoundOff(UInt32 inFrame); - void ResetAllControllers(UInt32 inFrame); - - SynthNote * GetNote(NoteInstanceID inNoteID, bool unreleasedOnly=false, UInt32 *outNoteState=NULL); - - void Reset(); - - virtual OSStatus Render(SInt64 inAbsoluteSampleFrame, UInt32 inNumberFrames, AUScope &outputs); - - float GetPitchBend() const { return mMidiControlHandler->GetPitchBend(); } - SInt64 GetCurrentAbsoluteFrame() const { return mCurrentAbsoluteFrame; } - - MusicDeviceGroupID GroupID () const { return mGroupID; } - virtual void SetGroupID (MusicDeviceGroupID inGroup); - - MIDIControlHandler * GetMIDIControlHandler() const { return mMidiControlHandler; } - -protected: - SInt64 mCurrentAbsoluteFrame; - SynthNoteList mNoteList[kNumberOfSoundingNoteStates]; - MIDIControlHandler *mMidiControlHandler; - -private: - friend class AUInstrumentBase; - friend class AUMonotimbralInstrumentBase; - friend class AUMultitimbralInstrumentBase; - - bool mSustainIsOn; - bool mSostenutoIsOn; - UInt32 mOutputBus; - MusicDeviceGroupID mGroupID; -}; - -//////////////////////////////////////////////////////////////////////////////////////////////////////////// -struct SynthKeyZone -{ - UInt8 mLoNote; - UInt8 mHiNote; - UInt8 mLoVelocity; - UInt8 mHiVelocity; -}; - -//////////////////////////////////////////////////////////////////////////////////////////////////////////// - -const UInt32 kUnlimitedPolyphony = 0xFFFFFFFF; - -class SynthPartElement : public SynthElement -{ -public: - SynthPartElement(AUInstrumentBase *audioUnit, UInt32 inElement); - - UInt32 GetGroupIndex() const { return mGroupIndex; } - bool InRange(Float32 inNote, Float32 inVelocity); - - UInt32 GetMaxPolyphony() const { return mMaxPolyphony; } - void SetMaxPolyphony(UInt32 inMaxPolyphony) { mMaxPolyphony = inMaxPolyphony; } - -private: - UInt32 mGroupIndex; - UInt32 mPatchIndex; - UInt32 mMaxPolyphony; - SynthKeyZone mKeyZone; -}; - -#endif diff --git a/src/CoreAudio/CoreAudioComponent/AUPublic/AUInstrumentBase/SynthEvent.h b/src/CoreAudio/CoreAudioComponent/AUPublic/AUInstrumentBase/SynthEvent.h deleted file mode 100644 index 9c27aee04..000000000 --- a/src/CoreAudio/CoreAudioComponent/AUPublic/AUInstrumentBase/SynthEvent.h +++ /dev/null @@ -1,145 +0,0 @@ -/* - File: SynthEvent.h - Abstract: Part of CoreAudio Utility Classes - Version: 1.1 - - Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple - Inc. ("Apple") in consideration of your agreement to the following - terms, and your use, installation, modification or redistribution of - this Apple software constitutes acceptance of these terms. If you do - not agree with these terms, please do not use, install, modify or - redistribute this Apple software. - - In consideration of your agreement to abide by the following terms, and - subject to these terms, Apple grants you a personal, non-exclusive - license, under Apple's copyrights in this original Apple software (the - "Apple Software"), to use, reproduce, modify and redistribute the Apple - Software, with or without modifications, in source and/or binary forms; - provided that if you redistribute the Apple Software in its entirety and - without modifications, you must retain this notice and the following - text and disclaimers in all such redistributions of the Apple Software. - Neither the name, trademarks, service marks or logos of Apple Inc. may - be used to endorse or promote products derived from the Apple Software - without specific prior written permission from Apple. Except as - expressly stated in this notice, no other rights or licenses, express or - implied, are granted by Apple herein, including but not limited to any - patent rights that may be infringed by your derivative works or by other - works in which the Apple Software may be incorporated. - - The Apple Software is provided by Apple on an "AS IS" basis. APPLE - MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION - THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS - FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND - OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS. - - IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL - OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, - MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED - AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), - STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE - POSSIBILITY OF SUCH DAMAGE. - - Copyright (C) 2014 Apple Inc. All Rights Reserved. - -*/ -/* You can either fill in code here or remove this and create or add new files. */ - -#ifndef __SynthEvent__ -#define __SynthEvent__ - -#include -#include -#include "MusicDeviceBase.h" -#include - -//////////////////////////////////////////////////////////////////////////////////////////////////////////// - - -class SynthEvent -{ -public: - enum { - kEventType_NoteOn = 1, - kEventType_NoteOff = 2, - kEventType_SustainOn = 3, - kEventType_SustainOff = 4, - kEventType_SostenutoOn = 5, - kEventType_SostenutoOff = 6, - kEventType_AllNotesOff = 7, - kEventType_AllSoundOff = 8, - kEventType_ResetAllControllers = 9 - }; - - - SynthEvent() {} - ~SynthEvent() {} - - void Set( - UInt32 inEventType, - MusicDeviceGroupID inGroupID, - NoteInstanceID inNoteID, - UInt32 inOffsetSampleFrame, - const MusicDeviceNoteParams* inNoteParams - ) - { - mEventType = inEventType; - mGroupID = inGroupID; - mNoteID = inNoteID; - mOffsetSampleFrame = inOffsetSampleFrame; - - if (inNoteParams) - { - UInt32 paramSize = offsetof(MusicDeviceNoteParams, mControls) + (inNoteParams->argCount-2)*sizeof(NoteParamsControlValue); - mNoteParams = inNoteParams->argCount > 3 - ? (MusicDeviceNoteParams*)malloc(paramSize) - : &mSmallNoteParams; - memcpy(mNoteParams, inNoteParams, paramSize); - } - else - mNoteParams = NULL; - } - - - void Free() - { - if (mNoteParams) - { - if (mNoteParams->argCount > 3) - free(mNoteParams); - mNoteParams = NULL; - } - } - - UInt32 GetEventType() const { return mEventType; } - MusicDeviceGroupID GetGroupID() const { return mGroupID; } - NoteInstanceID GetNoteID() const { return mNoteID; } - UInt32 GetOffsetSampleFrame() const { return mOffsetSampleFrame; } - - MusicDeviceNoteParams* GetParams() const { return mNoteParams; } - - UInt32 GetArgCount() const { return mNoteParams->argCount; } - UInt32 NumberParameters() const { return mNoteParams->argCount - 2; } - - Float32 GetNote() const { return mNoteParams->mPitch; } - Float32 GetVelocity() const { return mNoteParams->mVelocity; } - - NoteParamsControlValue GetParameter(UInt32 inIndex) const - { - if (inIndex >= NumberParameters()) - throw std::runtime_error("index out of range"); - return mNoteParams->mControls[inIndex]; - } - -private: - UInt32 mEventType; - MusicDeviceGroupID mGroupID; - NoteInstanceID mNoteID; - UInt32 mOffsetSampleFrame; - MusicDeviceNoteParams* mNoteParams; - MusicDeviceNoteParams mSmallNoteParams; // inline a small one to eliminate malloc for the simple case. -}; - -//////////////////////////////////////////////////////////////////////////////////////////////////////////// -#endif diff --git a/src/CoreAudio/CoreAudioComponent/AUPublic/AUInstrumentBase/SynthNote.cpp b/src/CoreAudio/CoreAudioComponent/AUPublic/AUInstrumentBase/SynthNote.cpp deleted file mode 100644 index 96a24d33c..000000000 --- a/src/CoreAudio/CoreAudioComponent/AUPublic/AUInstrumentBase/SynthNote.cpp +++ /dev/null @@ -1,140 +0,0 @@ -/* - File: SynthNote.cpp - Abstract: SynthNote.h - Version: 1.1 - - Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple - Inc. ("Apple") in consideration of your agreement to the following - terms, and your use, installation, modification or redistribution of - this Apple software constitutes acceptance of these terms. If you do - not agree with these terms, please do not use, install, modify or - redistribute this Apple software. - - In consideration of your agreement to abide by the following terms, and - subject to these terms, Apple grants you a personal, non-exclusive - license, under Apple's copyrights in this original Apple software (the - "Apple Software"), to use, reproduce, modify and redistribute the Apple - Software, with or without modifications, in source and/or binary forms; - provided that if you redistribute the Apple Software in its entirety and - without modifications, you must retain this notice and the following - text and disclaimers in all such redistributions of the Apple Software. - Neither the name, trademarks, service marks or logos of Apple Inc. may - be used to endorse or promote products derived from the Apple Software - without specific prior written permission from Apple. Except as - expressly stated in this notice, no other rights or licenses, express or - implied, are granted by Apple herein, including but not limited to any - patent rights that may be infringed by your derivative works or by other - works in which the Apple Software may be incorporated. - - The Apple Software is provided by Apple on an "AS IS" basis. APPLE - MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION - THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS - FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND - OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS. - - IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL - OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, - MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED - AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), - STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE - POSSIBILITY OF SUCH DAMAGE. - - Copyright (C) 2014 Apple Inc. All Rights Reserved. - -*/ -#include "SynthNote.h" -#include "SynthElement.h" -#include "AUInstrumentBase.h" - -bool SynthNote::AttackNote( - SynthPartElement * inPart, - SynthGroupElement * inGroup, - NoteInstanceID inNoteID, - UInt64 inAbsoluteSampleFrame, - UInt32 inOffsetSampleFrame, - const MusicDeviceNoteParams &inParams) -{ -#if DEBUG_PRINT - printf("SynthNote::AttackNote %lu %lu abs frame %llu rel frame %lu\n", (UInt32)inGroup->GroupID(), (UInt32)inNoteID, inAbsoluteSampleFrame, inOffsetSampleFrame); -#endif - mPart = inPart; - mGroup = inGroup; - mNoteID = inNoteID; - - mAbsoluteStartFrame = inAbsoluteSampleFrame; - mRelativeStartFrame = inOffsetSampleFrame; - mRelativeReleaseFrame = -1; - mRelativeKillFrame = -1; - - mPitch = inParams.mPitch; - mVelocity = inParams.mVelocity; - - - return Attack(inParams); -} - - -void SynthNote::Reset() -{ - mPart = 0; - mGroup = 0; - mAbsoluteStartFrame = 0; - mRelativeStartFrame = 0; - mRelativeReleaseFrame = 0; - mRelativeKillFrame = 0; -} - -void SynthNote::Kill(UInt32 inFrame) -{ - mRelativeKillFrame = inFrame; -} - -void SynthNote::Release(UInt32 inFrame) -{ - mRelativeReleaseFrame = inFrame; -} - -void SynthNote::FastRelease(UInt32 inFrame) -{ - mRelativeReleaseFrame = inFrame; -} - -double SynthNote::TuningA() const -{ - return 440.0; -} - -double SynthNote::Frequency() -{ - return TuningA() * pow(2., (mPitch - 69. + GetPitchBend()) / 12.); -} - -double SynthNote::SampleRate() -{ - return GetAudioUnit()->GetOutput(0)->GetStreamFormat().mSampleRate; -} - -AUInstrumentBase* SynthNote::GetAudioUnit() const -{ - return (AUInstrumentBase*)mGroup->GetAudioUnit(); -} - -Float32 SynthNote::GetGlobalParameter(AudioUnitParameterID inParamID) const -{ - return mGroup->GetAudioUnit()->Globals()->GetParameter(inParamID); -} - -void SynthNote::NoteEnded(UInt32 inFrame) -{ - mGroup->NoteEnded(this, inFrame); - mNoteID = 0xFFFFFFFF; -} - -float SynthNote::GetPitchBend() const -{ - return mGroup->GetPitchBend(); -} - - diff --git a/src/CoreAudio/CoreAudioComponent/AUPublic/AUInstrumentBase/SynthNote.h b/src/CoreAudio/CoreAudioComponent/AUPublic/AUInstrumentBase/SynthNote.h deleted file mode 100644 index cec637721..000000000 --- a/src/CoreAudio/CoreAudioComponent/AUPublic/AUInstrumentBase/SynthNote.h +++ /dev/null @@ -1,187 +0,0 @@ -/* - File: SynthNote.h - Abstract: Part of CoreAudio Utility Classes - Version: 1.1 - - Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple - Inc. ("Apple") in consideration of your agreement to the following - terms, and your use, installation, modification or redistribution of - this Apple software constitutes acceptance of these terms. If you do - not agree with these terms, please do not use, install, modify or - redistribute this Apple software. - - In consideration of your agreement to abide by the following terms, and - subject to these terms, Apple grants you a personal, non-exclusive - license, under Apple's copyrights in this original Apple software (the - "Apple Software"), to use, reproduce, modify and redistribute the Apple - Software, with or without modifications, in source and/or binary forms; - provided that if you redistribute the Apple Software in its entirety and - without modifications, you must retain this notice and the following - text and disclaimers in all such redistributions of the Apple Software. - Neither the name, trademarks, service marks or logos of Apple Inc. may - be used to endorse or promote products derived from the Apple Software - without specific prior written permission from Apple. Except as - expressly stated in this notice, no other rights or licenses, express or - implied, are granted by Apple herein, including but not limited to any - patent rights that may be infringed by your derivative works or by other - works in which the Apple Software may be incorporated. - - The Apple Software is provided by Apple on an "AS IS" basis. APPLE - MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION - THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS - FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND - OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS. - - IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL - OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, - MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED - AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), - STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE - POSSIBILITY OF SUCH DAMAGE. - - Copyright (C) 2014 Apple Inc. All Rights Reserved. - -*/ -#ifndef __SynthNote__ -#define __SynthNote__ - -#include -#include -#include "MusicDeviceBase.h" - -///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - -enum SynthNoteState { - kNoteState_Attacked = 0, - kNoteState_Sostenutoed = 1, - kNoteState_ReleasedButSostenutoed = 2, - kNoteState_ReleasedButSustained = 3, - kNoteState_Released = 4, - kNoteState_FastReleased = 5, - kNoteState_Free = 6, - kNumberOfActiveNoteStates = 5, - kNumberOfSoundingNoteStates = 6, - kNumberOfNoteStates = 7, - kNoteState_Unset = kNumberOfNoteStates -}; - -/* - This table describes the state transitions for SynthNotes - - EVENT CURRENT STATE NEW STATE - note on free attacked - note off attacked (and sustain on) released but sustained - note off attacked released - note off sostenutoed released but sostenutoed - sustain on -- no changes -- - sustain off released but sustained released - sostenuto on attacked sostenutoed - sostenuto off sostenutoed attacked - sostenuto off released but sostenutoed (and sustain on) released but sustained - sostenuto off released but sostenutoed released - end of note any state free - soft voice stealing any state fast released - hard voice stealing any state free - - soft voice stealing happens when there is a note on event and NumActiveNotes > MaxActiveNotes - hard voice stealing happens when there is a note on event and NumActiveNotes == NumNotes (no free notes) - voice stealing removes the quietest note in the highest numbered state that has sounding notes. -*/ - -class SynthGroupElement; -class SynthPartElement; -class AUInstrumentBase; - -struct SynthNote -{ - SynthNote() : - mPrev(0), mNext(0), mPart(0), mGroup(0), - mNoteID(0xffffffff), - mState(kNoteState_Unset), - mAbsoluteStartFrame(0), - mRelativeStartFrame(0), - mRelativeReleaseFrame(-1), - mRelativeKillFrame(-1), - mPitch(0.0f), - mVelocity(0.0f) - { - } - - virtual ~SynthNote() {} - - virtual void Reset(); - //! Returns true if active note resulted from this call, otherwise false - virtual bool AttackNote( - SynthPartElement * inPart, - SynthGroupElement * inGroup, - NoteInstanceID inNoteID, - UInt64 inAbsoluteSampleFrame, - UInt32 inOffsetSampleFrame, - const MusicDeviceNoteParams &inParams - ); - - virtual OSStatus Render(UInt64 inAbsoluteSampleFrame, UInt32 inNumFrames, AudioBufferList** inBufferList, UInt32 inOutBusCount) = 0; - //! Returns true if active note resulted from this call, otherwise false - virtual bool Attack(const MusicDeviceNoteParams &inParams) = 0; - virtual void Kill(UInt32 inFrame); // voice is being stolen. - virtual void Release(UInt32 inFrame); - virtual void FastRelease(UInt32 inFrame); - virtual Float32 Amplitude() = 0; // used for finding quietest note for voice stealing. - - virtual void NoteEnded(UInt32 inFrame); - - SynthGroupElement* GetGroup() const { return mGroup; } - SynthPartElement* GetPart() const { return mPart; } - - AUInstrumentBase* GetAudioUnit() const; - - Float32 GetGlobalParameter(AudioUnitParameterID inParamID) const; - - NoteInstanceID GetNoteID() const { return mNoteID; } - SynthNoteState GetState() const { return mState; } - UInt8 GetMidiKey() const { return (UInt8) mPitch; } - UInt8 GetMidiVelocity() const { return (UInt8) mVelocity; } - - Boolean IsSounding() const { return mState < kNumberOfSoundingNoteStates; } - Boolean IsActive() const { return mState < kNumberOfActiveNoteStates; } - UInt64 GetAbsoluteStartFrame() const { return mAbsoluteStartFrame; } - SInt32 GetRelativeStartFrame() const { return mRelativeStartFrame; } - SInt32 GetRelativeReleaseFrame() const { return mRelativeReleaseFrame; } - SInt32 GetRelativeKillFrame() const { return mRelativeKillFrame; } - - void ListRemove() { mPrev = mNext = 0; } // only use when lists will be reset. - - float GetPitchBend() const; - double TuningA() const; - - Float32 GetPitch() const { return mPitch; } // returns raw pitch from MusicDeviceNoteParams - virtual double Frequency(); // returns the frequency of note + pitch bend. - virtual double SampleRate(); - - // linked list pointers - SynthNote *mPrev; - SynthNote *mNext; - - friend class SynthGroupElement; - friend struct SynthNoteList; -protected: - void SetState(SynthNoteState inState) { mState = inState; } -private: - SynthPartElement* mPart; - SynthGroupElement* mGroup; - - NoteInstanceID mNoteID; - SynthNoteState mState; - UInt64 mAbsoluteStartFrame; - SInt32 mRelativeStartFrame; - SInt32 mRelativeReleaseFrame; - SInt32 mRelativeKillFrame; - - Float32 mPitch; - Float32 mVelocity; -}; - -#endif - diff --git a/src/CoreAudio/CoreAudioComponent/AUPublic/AUInstrumentBase/SynthNoteList.cpp b/src/CoreAudio/CoreAudioComponent/AUPublic/AUInstrumentBase/SynthNoteList.cpp deleted file mode 100644 index 849abd266..000000000 --- a/src/CoreAudio/CoreAudioComponent/AUPublic/AUInstrumentBase/SynthNoteList.cpp +++ /dev/null @@ -1,93 +0,0 @@ -/* - File: SynthNoteList.cpp - Abstract: SynthNoteList.h - Version: 1.1 - - Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple - Inc. ("Apple") in consideration of your agreement to the following - terms, and your use, installation, modification or redistribution of - this Apple software constitutes acceptance of these terms. If you do - not agree with these terms, please do not use, install, modify or - redistribute this Apple software. - - In consideration of your agreement to abide by the following terms, and - subject to these terms, Apple grants you a personal, non-exclusive - license, under Apple's copyrights in this original Apple software (the - "Apple Software"), to use, reproduce, modify and redistribute the Apple - Software, with or without modifications, in source and/or binary forms; - provided that if you redistribute the Apple Software in its entirety and - without modifications, you must retain this notice and the following - text and disclaimers in all such redistributions of the Apple Software. - Neither the name, trademarks, service marks or logos of Apple Inc. may - be used to endorse or promote products derived from the Apple Software - without specific prior written permission from Apple. Except as - expressly stated in this notice, no other rights or licenses, express or - implied, are granted by Apple herein, including but not limited to any - patent rights that may be infringed by your derivative works or by other - works in which the Apple Software may be incorporated. - - The Apple Software is provided by Apple on an "AS IS" basis. APPLE - MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION - THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS - FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND - OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS. - - IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL - OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, - MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED - AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), - STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE - POSSIBILITY OF SUCH DAMAGE. - - Copyright (C) 2014 Apple Inc. All Rights Reserved. - -*/ -#include "SynthNoteList.h" -#include - -void SynthNoteList::SanityCheck() const -{ - if (mState >= kNoteState_Unset) { - throw std::runtime_error("SanityCheck: mState is bad"); - } - - if (mHead == NULL) { - if (mTail != NULL) - throw std::runtime_error("SanityCheck: mHead is NULL but not mTail"); - return; - } - if (mTail == NULL) { - throw std::runtime_error("SanityCheck: mTail is NULL but not mHead"); - } - - if (mHead->mPrev) { - throw std::runtime_error("SanityCheck: mHead has a mPrev"); - } - if (mTail->mNext) { - throw std::runtime_error("SanityCheck: mTail has a mNext"); - } - - SynthNote *note = mHead; - while (note) - { - if (note->mState != mState) - throw std::runtime_error("SanityCheck: note in wrong state"); - if (note->mNext) { - if (note->mNext->mPrev != note) - throw std::runtime_error("SanityCheck: bad link 1"); - } else { - if (mTail != note) - throw std::runtime_error("SanityCheck: note->mNext is nil, but mTail != note"); - } - if (note->mPrev) { - if (note->mPrev->mNext != note) - throw std::runtime_error("SanityCheck: bad link 2"); - } else { - if (mHead != note) - throw std::runtime_error("SanityCheck: note->mPrev is nil, but mHead != note"); - } - note = note->mNext; - } -} diff --git a/src/CoreAudio/CoreAudioComponent/AUPublic/AUInstrumentBase/SynthNoteList.h b/src/CoreAudio/CoreAudioComponent/AUPublic/AUInstrumentBase/SynthNoteList.h deleted file mode 100644 index 47a359301..000000000 --- a/src/CoreAudio/CoreAudioComponent/AUPublic/AUInstrumentBase/SynthNoteList.h +++ /dev/null @@ -1,232 +0,0 @@ -/* - File: SynthNoteList.h - Abstract: Part of CoreAudio Utility Classes - Version: 1.1 - - Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple - Inc. ("Apple") in consideration of your agreement to the following - terms, and your use, installation, modification or redistribution of - this Apple software constitutes acceptance of these terms. If you do - not agree with these terms, please do not use, install, modify or - redistribute this Apple software. - - In consideration of your agreement to abide by the following terms, and - subject to these terms, Apple grants you a personal, non-exclusive - license, under Apple's copyrights in this original Apple software (the - "Apple Software"), to use, reproduce, modify and redistribute the Apple - Software, with or without modifications, in source and/or binary forms; - provided that if you redistribute the Apple Software in its entirety and - without modifications, you must retain this notice and the following - text and disclaimers in all such redistributions of the Apple Software. - Neither the name, trademarks, service marks or logos of Apple Inc. may - be used to endorse or promote products derived from the Apple Software - without specific prior written permission from Apple. Except as - expressly stated in this notice, no other rights or licenses, express or - implied, are granted by Apple herein, including but not limited to any - patent rights that may be infringed by your derivative works or by other - works in which the Apple Software may be incorporated. - - The Apple Software is provided by Apple on an "AS IS" basis. APPLE - MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION - THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS - FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND - OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS. - - IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL - OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, - MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED - AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), - STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE - POSSIBILITY OF SUCH DAMAGE. - - Copyright (C) 2014 Apple Inc. All Rights Reserved. - -*/ -#ifndef __SynthNoteList__ -#define __SynthNoteList__ - -#include "SynthNote.h" - -#if DEBUG -#ifndef DEBUG_PRINT - #define DEBUG_PRINT 0 -#endif - #define USE_SANITY_CHECK 0 -#endif - -///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - -struct SynthNoteList -{ - SynthNoteList() : mState(kNoteState_Unset), mHead(0), mTail(0) {} - - bool NotEmpty() const { return mHead != NULL; } - bool IsEmpty() const { return mHead == NULL; } - void Empty() { -#if USE_SANITY_CHECK - SanityCheck(); -#endif - mHead = mTail = NULL; - } - - UInt32 Length() const { -#if USE_SANITY_CHECK - SanityCheck(); -#endif - UInt32 length = 0; - for (SynthNote* note = mHead; note; note = note->mNext) - length++; - return length; - }; - - void AddNote(SynthNote *inNote) - { -#if DEBUG_PRINT - printf("AddNote(inNote=%p) to state: %lu\n", inNote, mState); -#endif -#if USE_SANITY_CHECK - SanityCheck(); -#endif - inNote->SetState(mState); - inNote->mNext = mHead; - inNote->mPrev = NULL; - - if (mHead) { mHead->mPrev = inNote; mHead = inNote; } - else mHead = mTail = inNote; -#if USE_SANITY_CHECK - SanityCheck(); -#endif - } - - void RemoveNote(SynthNote *inNote) - { -#if DEBUG_PRINT - printf("RemoveNote(inNote=%p) from state: %lu\n", inNote, mState); -#endif -#if USE_SANITY_CHECK - SanityCheck(); -#endif - if (inNote->mPrev) inNote->mPrev->mNext = inNote->mNext; - else mHead = inNote->mNext; - - if (inNote->mNext) inNote->mNext->mPrev = inNote->mPrev; - else mTail = inNote->mPrev; - - inNote->mPrev = 0; - inNote->mNext = 0; -#if USE_SANITY_CHECK - SanityCheck(); -#endif - } - - void TransferAllFrom(SynthNoteList *inNoteList, UInt32 inFrame) - { -#if DEBUG_PRINT - printf("TransferAllFrom: from state %lu into state %lu\n", inNoteList->mState, mState); -#endif -#if USE_SANITY_CHECK - SanityCheck(); - inNoteList->SanityCheck(); -#endif - if (!inNoteList->mTail) return; - - if (mState == kNoteState_Released) - { - for (SynthNote* note = inNoteList->mHead; note; note = note->mNext) - { -#if DEBUG_PRINT - printf("TransferAllFrom: releasing note %p\n", note); -#endif - note->Release(inFrame); - note->SetState(mState); - } - } - else - { - for (SynthNote* note = inNoteList->mHead; note; note = note->mNext) - { - note->SetState(mState); - } - } - - inNoteList->mTail->mNext = mHead; - - if (mHead) mHead->mPrev = inNoteList->mTail; - else mTail = inNoteList->mTail; - - mHead = inNoteList->mHead; - - inNoteList->mHead = NULL; - inNoteList->mTail = NULL; -#if USE_SANITY_CHECK - SanityCheck(); - inNoteList->SanityCheck(); -#endif - } - - SynthNote* FindOldestNote() - { -#if DEBUG_PRINT - printf("FindOldestNote\n"); -#endif -#if USE_SANITY_CHECK - SanityCheck(); -#endif - UInt64 minStartFrame = -1; - SynthNote* oldestNote = NULL; - for (SynthNote* note = mHead; note; note = note->mNext) - { - if (note->mAbsoluteStartFrame < minStartFrame) - { - oldestNote = note; - minStartFrame = note->mAbsoluteStartFrame; - } - } - return oldestNote; - } - - SynthNote* FindMostQuietNote() - { -#if DEBUG_PRINT - printf("FindMostQuietNote\n"); -#endif - Float32 minAmplitude = 1e9f; - UInt64 minStartFrame = -1; - SynthNote* mostQuietNote = NULL; - for (SynthNote* note = mHead; note; note = note->mNext) - { - Float32 amp = note->Amplitude(); -#if DEBUG_PRINT - printf(" amp %g minAmplitude %g\n", amp, minAmplitude); -#endif - if (amp < minAmplitude) - { - mostQuietNote = note; - minAmplitude = amp; - minStartFrame = note->mAbsoluteStartFrame; - } - else if (amp == minAmplitude && note->mAbsoluteStartFrame < minStartFrame) - { - // use earliest start time as a tie breaker - mostQuietNote = note; - minStartFrame = note->mAbsoluteStartFrame; - } - } -#if USE_SANITY_CHECK - SanityCheck(); -#endif - return mostQuietNote; - } - - void SanityCheck() const; - - SynthNoteState mState; - SynthNote * mHead; - SynthNote * mTail; -}; - -///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - -#endif diff --git a/src/CoreAudio/CoreAudioComponent/AUPublic/OtherBases/AUEffectBase.cpp b/src/CoreAudio/CoreAudioComponent/AUPublic/OtherBases/AUEffectBase.cpp deleted file mode 100644 index 010082fc3..000000000 --- a/src/CoreAudio/CoreAudioComponent/AUPublic/OtherBases/AUEffectBase.cpp +++ /dev/null @@ -1,466 +0,0 @@ -/* - File: AUEffectBase.cpp - Abstract: AUEffectBase.h - Version: 1.1 - - Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple - Inc. ("Apple") in consideration of your agreement to the following - terms, and your use, installation, modification or redistribution of - this Apple software constitutes acceptance of these terms. If you do - not agree with these terms, please do not use, install, modify or - redistribute this Apple software. - - In consideration of your agreement to abide by the following terms, and - subject to these terms, Apple grants you a personal, non-exclusive - license, under Apple's copyrights in this original Apple software (the - "Apple Software"), to use, reproduce, modify and redistribute the Apple - Software, with or without modifications, in source and/or binary forms; - provided that if you redistribute the Apple Software in its entirety and - without modifications, you must retain this notice and the following - text and disclaimers in all such redistributions of the Apple Software. - Neither the name, trademarks, service marks or logos of Apple Inc. may - be used to endorse or promote products derived from the Apple Software - without specific prior written permission from Apple. Except as - expressly stated in this notice, no other rights or licenses, express or - implied, are granted by Apple herein, including but not limited to any - patent rights that may be infringed by your derivative works or by other - works in which the Apple Software may be incorporated. - - The Apple Software is provided by Apple on an "AS IS" basis. APPLE - MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION - THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS - FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND - OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS. - - IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL - OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, - MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED - AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), - STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE - POSSIBILITY OF SUCH DAMAGE. - - Copyright (C) 2014 Apple Inc. All Rights Reserved. - -*/ -#include "AUEffectBase.h" - -/* - This class does not deal as well as it should with N-M effects... - - The problem areas are (if the channels don't match): - ProcessInPlace if the channels don't match - there will be problems if InputChan != OutputChan - Bypass - its just passing the buffers through when not processing them - - This will be fixed in a future update... -*/ - -//_____________________________________________________________________________ -// -AUEffectBase::AUEffectBase( AudioComponentInstance audioUnit, - bool inProcessesInPlace ) : - AUBase(audioUnit, 1, 1), // 1 in bus, 1 out bus - mBypassEffect(false), - mParamSRDep (false), - mProcessesInPlace(inProcessesInPlace), - mMainOutput(NULL), mMainInput(NULL) -#if TARGET_OS_IPHONE - , mOnlyOneKernel(false) -#endif -{ -} - -//_____________________________________________________________________________ -// -AUEffectBase::~AUEffectBase() -{ - Cleanup(); -} - -//_____________________________________________________________________________ -// -void AUEffectBase::Cleanup() -{ - for (KernelList::iterator it = mKernelList.begin(); it != mKernelList.end(); ++it) - delete *it; - - mKernelList.clear(); - mMainOutput = NULL; - mMainInput = NULL; -} - - -//_____________________________________________________________________________ -// -OSStatus AUEffectBase::Initialize() -{ - // get our current numChannels for input and output - SInt16 auNumInputs = (SInt16) GetInput(0)->GetStreamFormat().mChannelsPerFrame; - SInt16 auNumOutputs = (SInt16) GetOutput(0)->GetStreamFormat().mChannelsPerFrame; - - // does the unit publish specific information about channel configurations? - const AUChannelInfo *auChannelConfigs = NULL; - UInt32 numIOconfigs = SupportedNumChannels(&auChannelConfigs); - - if ((numIOconfigs > 0) && (auChannelConfigs != NULL)) - { - bool foundMatch = false; - for (UInt32 i = 0; (i < numIOconfigs) && !foundMatch; ++i) - { - SInt16 configNumInputs = auChannelConfigs[i].inChannels; - SInt16 configNumOutputs = auChannelConfigs[i].outChannels; - if ((configNumInputs < 0) && (configNumOutputs < 0)) - { - // unit accepts any number of channels on input and output - if (((configNumInputs == -1) && (configNumOutputs == -2)) - || ((configNumInputs == -2) && (configNumOutputs == -1))) - { - foundMatch = true; - // unit accepts any number of channels on input and output IFF they are the same number on both scopes - } - else if (((configNumInputs == -1) && (configNumOutputs == -1)) && (auNumInputs == auNumOutputs)) - { - foundMatch = true; - // unit has specified a particular number of channels on both scopes - } - else - continue; - } - else - { - // the -1 case on either scope is saying that the unit doesn't care about the - // number of channels on that scope - bool inputMatch = (auNumInputs == configNumInputs) || (configNumInputs == -1); - bool outputMatch = (auNumOutputs == configNumOutputs) || (configNumOutputs == -1); - if (inputMatch && outputMatch) - foundMatch = true; - } - } - if (!foundMatch) - return kAudioUnitErr_FormatNotSupported; - } - else - { - // there is no specifically published channel info - // so for those kinds of effects, the assumption is that the channels (whatever their number) - // should match on both scopes - if ((auNumOutputs != auNumInputs) || (auNumOutputs == 0)) - { - return kAudioUnitErr_FormatNotSupported; - } - } - - MaintainKernels(); - - mMainOutput = GetOutput(0); - mMainInput = GetInput(0); - - const CAStreamBasicDescription& format = GetStreamFormat(kAudioUnitScope_Output, 0); - format.IdentifyCommonPCMFormat(mCommonPCMFormat, NULL); - mBytesPerFrame = format.mBytesPerFrame; - - return noErr; -} - -OSStatus AUEffectBase::Reset( AudioUnitScope inScope, - AudioUnitElement inElement) -{ - for (KernelList::iterator it = mKernelList.begin(); it != mKernelList.end(); ++it) { - AUKernelBase *kernel = *it; - if (kernel != NULL) - kernel->Reset(); - } - - return AUBase::Reset(inScope, inElement); -} - -OSStatus AUEffectBase::GetPropertyInfo (AudioUnitPropertyID inID, - AudioUnitScope inScope, - AudioUnitElement inElement, - UInt32 & outDataSize, - Boolean & outWritable) -{ - if (inScope == kAudioUnitScope_Global) { - switch (inID) { - case kAudioUnitProperty_BypassEffect: - outWritable = true; - outDataSize = sizeof (UInt32); - return noErr; - case kAudioUnitProperty_InPlaceProcessing: - outWritable = true; - outDataSize = sizeof (UInt32); - return noErr; - } - } - return AUBase::GetPropertyInfo (inID, inScope, inElement, outDataSize, outWritable); -} - - -OSStatus AUEffectBase::GetProperty (AudioUnitPropertyID inID, - AudioUnitScope inScope, - AudioUnitElement inElement, - void * outData) -{ - if (inScope == kAudioUnitScope_Global) { - switch (inID) { - case kAudioUnitProperty_BypassEffect: - *((UInt32*)outData) = (IsBypassEffect() ? 1 : 0); - return noErr; - case kAudioUnitProperty_InPlaceProcessing: - *((UInt32*)outData) = (mProcessesInPlace ? 1 : 0); - return noErr; - } - } - return AUBase::GetProperty (inID, inScope, inElement, outData); -} - - -OSStatus AUEffectBase::SetProperty( AudioUnitPropertyID inID, - AudioUnitScope inScope, - AudioUnitElement inElement, - const void * inData, - UInt32 inDataSize) -{ - if (inScope == kAudioUnitScope_Global) { - switch (inID) { - case kAudioUnitProperty_BypassEffect: - { - if (inDataSize < sizeof(UInt32)) - return kAudioUnitErr_InvalidPropertyValue; - - bool tempNewSetting = *((UInt32*)inData) != 0; - // we're changing the state of bypass - if (tempNewSetting != IsBypassEffect()) - { - if (!tempNewSetting && IsBypassEffect() && IsInitialized()) // turning bypass off and we're initialized - Reset(0, 0); - SetBypassEffect (tempNewSetting); - } - return noErr; - } - case kAudioUnitProperty_InPlaceProcessing: - mProcessesInPlace = (*((UInt32*)inData) != 0); - return noErr; - } - } - return AUBase::SetProperty (inID, inScope, inElement, inData, inDataSize); -} - - -void AUEffectBase::MaintainKernels() -{ -#if TARGET_OS_IPHONE - UInt32 nKernels = mOnlyOneKernel ? 1 : GetNumberOfChannels(); -#else - UInt32 nKernels = GetNumberOfChannels(); -#endif - - if (mKernelList.size() < nKernels) { - mKernelList.reserve(nKernels); - for (UInt32 i = (UInt32)mKernelList.size(); i < nKernels; ++i) - mKernelList.push_back(NewKernel()); - } else { - while (mKernelList.size() > nKernels) { - AUKernelBase *kernel = mKernelList.back(); - delete kernel; - mKernelList.pop_back(); - } - } - - for(unsigned int i = 0; i < nKernels; i++ ) - { - if(mKernelList[i]) { - mKernelList[i]->SetChannelNum (i); - } - } -} - -bool AUEffectBase::StreamFormatWritable( AudioUnitScope scope, - AudioUnitElement element) -{ - return IsInitialized() ? false : true; -} - -OSStatus AUEffectBase::ChangeStreamFormat( AudioUnitScope inScope, - AudioUnitElement inElement, - const CAStreamBasicDescription & inPrevFormat, - const CAStreamBasicDescription & inNewFormat) -{ - OSStatus result = AUBase::ChangeStreamFormat(inScope, inElement, inPrevFormat, inNewFormat); - if (result == noErr) - { - // for the moment this only dependency we know about - // where a parameter's range may change is with the sample rate - // and effects are only publishing parameters in the global scope! - if (GetParamHasSampleRateDependency() && fnotequal(inPrevFormat.mSampleRate, inNewFormat.mSampleRate)) - PropertyChanged(kAudioUnitProperty_ParameterList, kAudioUnitScope_Global, 0); - } - - return result; -} - - -// ____________________________________________________________________________ -// -// This method is called (potentially repeatedly) by ProcessForScheduledParams() -// in order to perform the actual DSP required for this portion of the entire buffer -// being processed. The entire buffer can be divided up into smaller "slices" -// according to the timestamps on the scheduled parameters... -// -OSStatus AUEffectBase::ProcessScheduledSlice( void *inUserData, - UInt32 inStartFrameInBuffer, - UInt32 inSliceFramesToProcess, - UInt32 inTotalBufferFrames ) -{ - ScheduledProcessParams &sliceParams = *((ScheduledProcessParams*)inUserData); - - AudioUnitRenderActionFlags &actionFlags = *sliceParams.actionFlags; - AudioBufferList &inputBufferList = *sliceParams.inputBufferList; - AudioBufferList &outputBufferList = *sliceParams.outputBufferList; - - UInt32 channelSize = inSliceFramesToProcess * mBytesPerFrame; - // fix the size of the buffer we're operating on before we render this slice of time - for(unsigned int i = 0; i < inputBufferList.mNumberBuffers; i++ ) { - inputBufferList.mBuffers[i].mDataByteSize = inputBufferList.mBuffers[i].mNumberChannels * channelSize; - } - - for(unsigned int i = 0; i < outputBufferList.mNumberBuffers; i++ ) { - outputBufferList.mBuffers[i].mDataByteSize = outputBufferList.mBuffers[i].mNumberChannels * channelSize; - } - // process the buffer - OSStatus result = ProcessBufferLists(actionFlags, inputBufferList, outputBufferList, inSliceFramesToProcess ); - - // we just partially processed the buffers, so increment the data pointers to the next part of the buffer to process - for(unsigned int i = 0; i < inputBufferList.mNumberBuffers; i++ ) { - inputBufferList.mBuffers[i].mData = - (char *)inputBufferList.mBuffers[i].mData + inputBufferList.mBuffers[i].mNumberChannels * channelSize; - } - - for(unsigned int i = 0; i < outputBufferList.mNumberBuffers; i++ ) { - outputBufferList.mBuffers[i].mData = - (char *)outputBufferList.mBuffers[i].mData + outputBufferList.mBuffers[i].mNumberChannels * channelSize; - } - - return result; -} - -// ____________________________________________________________________________ -// - -OSStatus AUEffectBase::Render( AudioUnitRenderActionFlags &ioActionFlags, - const AudioTimeStamp & inTimeStamp, - UInt32 nFrames) -{ - if (!HasInput(0)) - return kAudioUnitErr_NoConnection; - - OSStatus result = noErr; - - result = mMainInput->PullInput(ioActionFlags, inTimeStamp, 0 /* element */, nFrames); - - if (result == noErr) - { - if(ProcessesInPlace() && mMainOutput->WillAllocateBuffer()) - { - mMainOutput->SetBufferList(mMainInput->GetBufferList() ); - } - - if (ShouldBypassEffect()) - { - // leave silence bit alone - - if(!ProcessesInPlace() ) - { - mMainInput->CopyBufferContentsTo (mMainOutput->GetBufferList()); - } - } - else - { - if(mParamList.size() == 0 ) - { - // this will read/write silence bit - result = ProcessBufferLists(ioActionFlags, mMainInput->GetBufferList(), mMainOutput->GetBufferList(), nFrames); - } - else - { - // deal with scheduled parameters... - - AudioBufferList &inputBufferList = mMainInput->GetBufferList(); - AudioBufferList &outputBufferList = mMainOutput->GetBufferList(); - - ScheduledProcessParams processParams; - processParams.actionFlags = &ioActionFlags; - processParams.inputBufferList = &inputBufferList; - processParams.outputBufferList = &outputBufferList; - - // divide up the buffer into slices according to scheduled params then - // do the DSP for each slice (ProcessScheduledSlice() called for each slice) - result = ProcessForScheduledParams( mParamList, - nFrames, - &processParams ); - - - // fixup the buffer pointers to how they were before we started - UInt32 channelSize = nFrames * mBytesPerFrame; - for(unsigned int i = 0; i < inputBufferList.mNumberBuffers; i++ ) { - UInt32 size = inputBufferList.mBuffers[i].mNumberChannels * channelSize; - inputBufferList.mBuffers[i].mData = (char *)inputBufferList.mBuffers[i].mData - size; - inputBufferList.mBuffers[i].mDataByteSize = size; - } - - for(unsigned int i = 0; i < outputBufferList.mNumberBuffers; i++ ) { - UInt32 size = outputBufferList.mBuffers[i].mNumberChannels * channelSize; - outputBufferList.mBuffers[i].mData = (char *)outputBufferList.mBuffers[i].mData - size; - outputBufferList.mBuffers[i].mDataByteSize = size; - } - } - } - - if ( (ioActionFlags & kAudioUnitRenderAction_OutputIsSilence) && !ProcessesInPlace() ) - { - AUBufferList::ZeroBuffer(mMainOutput->GetBufferList() ); - } - } - - return result; -} - - -OSStatus AUEffectBase::ProcessBufferLists( - AudioUnitRenderActionFlags & ioActionFlags, - const AudioBufferList & inBuffer, - AudioBufferList & outBuffer, - UInt32 inFramesToProcess ) -{ - if (ShouldBypassEffect()) - return noErr; - - // interleaved (or mono) - switch (mCommonPCMFormat) { - case CAStreamBasicDescription::kPCMFormatFloat32 : - ProcessBufferListsT(ioActionFlags, inBuffer, outBuffer, inFramesToProcess); - break; - case CAStreamBasicDescription::kPCMFormatFixed824 : - ProcessBufferListsT(ioActionFlags, inBuffer, outBuffer, inFramesToProcess); - break; - case CAStreamBasicDescription::kPCMFormatInt16 : - ProcessBufferListsT(ioActionFlags, inBuffer, outBuffer, inFramesToProcess); - break; - default : - throw CAException(kAudio_UnimplementedError); - } - - return noErr; -} - -Float64 AUEffectBase::GetSampleRate() -{ - return GetOutput(0)->GetStreamFormat().mSampleRate; -} - -UInt32 AUEffectBase::GetNumberOfChannels() -{ - return GetOutput(0)->GetStreamFormat().mChannelsPerFrame; -} - diff --git a/src/CoreAudio/CoreAudioComponent/AUPublic/OtherBases/AUEffectBase.h b/src/CoreAudio/CoreAudioComponent/AUPublic/OtherBases/AUEffectBase.h deleted file mode 100644 index 13ba96b39..000000000 --- a/src/CoreAudio/CoreAudioComponent/AUPublic/OtherBases/AUEffectBase.h +++ /dev/null @@ -1,377 +0,0 @@ -/* - File: AUEffectBase.h - Abstract: Part of CoreAudio Utility Classes - Version: 1.1 - - Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple - Inc. ("Apple") in consideration of your agreement to the following - terms, and your use, installation, modification or redistribution of - this Apple software constitutes acceptance of these terms. If you do - not agree with these terms, please do not use, install, modify or - redistribute this Apple software. - - In consideration of your agreement to abide by the following terms, and - subject to these terms, Apple grants you a personal, non-exclusive - license, under Apple's copyrights in this original Apple software (the - "Apple Software"), to use, reproduce, modify and redistribute the Apple - Software, with or without modifications, in source and/or binary forms; - provided that if you redistribute the Apple Software in its entirety and - without modifications, you must retain this notice and the following - text and disclaimers in all such redistributions of the Apple Software. - Neither the name, trademarks, service marks or logos of Apple Inc. may - be used to endorse or promote products derived from the Apple Software - without specific prior written permission from Apple. Except as - expressly stated in this notice, no other rights or licenses, express or - implied, are granted by Apple herein, including but not limited to any - patent rights that may be infringed by your derivative works or by other - works in which the Apple Software may be incorporated. - - The Apple Software is provided by Apple on an "AS IS" basis. APPLE - MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION - THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS - FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND - OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS. - - IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL - OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, - MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED - AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), - STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE - POSSIBILITY OF SUCH DAMAGE. - - Copyright (C) 2014 Apple Inc. All Rights Reserved. - -*/ -#ifndef __AUEffectBase_h__ -#define __AUEffectBase_h__ - -#include "AUBase.h" -#include "AUSilentTimeout.h" -#include "CAException.h" - -class AUKernelBase; - -// Base class for an effect with one input stream, one output stream, -// any number of channels. - /*! @class AUEffectBase */ -class AUEffectBase : public AUBase { -public: - /*! @ctor AUEffectBase */ - AUEffectBase( AudioComponentInstance audioUnit, - bool inProcessesInPlace = true ); - /*! @dtor ~AUEffectBase */ - ~AUEffectBase(); - - /*! @method Initialize */ - virtual OSStatus Initialize(); - - /*! @method Cleanup */ - virtual void Cleanup(); - - - /*! @method Reset */ - virtual OSStatus Reset( AudioUnitScope inScope, - AudioUnitElement inElement); - - /*! @method GetPropertyInfo */ - virtual OSStatus GetPropertyInfo (AudioUnitPropertyID inID, - AudioUnitScope inScope, - AudioUnitElement inElement, - UInt32 & outDataSize, - Boolean & outWritable); - - /*! @method GetProperty */ - virtual OSStatus GetProperty (AudioUnitPropertyID inID, - AudioUnitScope inScope, - AudioUnitElement inElement, - void * outData); - - /*! @method SetProperty */ - virtual OSStatus SetProperty(AudioUnitPropertyID inID, - AudioUnitScope inScope, - AudioUnitElement inElement, - const void * inData, - UInt32 inDataSize); - - /*! @method StreamFormatWritable */ - virtual bool StreamFormatWritable (AudioUnitScope scope, - AudioUnitElement element); - - /*! @method ChangeStreamFormat */ - virtual OSStatus ChangeStreamFormat ( - AudioUnitScope inScope, - AudioUnitElement inElement, - const CAStreamBasicDescription & inPrevFormat, - const CAStreamBasicDescription & inNewFormat); - - /*! @method Render */ - virtual OSStatus Render(AudioUnitRenderActionFlags & ioActionFlags, - const AudioTimeStamp & inTimeStamp, - UInt32 inNumberFrames); - - // our virtual methods - - // If your unit processes N to N channels, and there are no interactions between channels, - // it can override NewKernel to create a mono processing object per channel. Otherwise, - // don't override NewKernel, and instead, override ProcessBufferLists. - /*! @method NewKernel */ - virtual AUKernelBase * NewKernel() { return NULL; } - - /*! @method ProcessBufferLists */ - virtual OSStatus ProcessBufferLists( - AudioUnitRenderActionFlags & ioActionFlags, - const AudioBufferList & inBuffer, - AudioBufferList & outBuffer, - UInt32 inFramesToProcess ); - - // convenience format accessors (use output 0's format) - /*! @method GetSampleRate */ - Float64 GetSampleRate(); - - /*! @method GetNumberOfChannels */ - UInt32 GetNumberOfChannels(); - - // convenience wrappers for accessing parameters in the global scope - /*! @method SetParameter */ - using AUBase::SetParameter; - void SetParameter( AudioUnitParameterID paramID, - AudioUnitParameterValue value) - { - Globals()->SetParameter(paramID, value); - } - - /*! @method GetParameter */ - using AUBase::GetParameter; - AudioUnitParameterValue GetParameter( AudioUnitParameterID paramID ) - { - return Globals()->GetParameter(paramID ); - } - - /*! @method CanScheduleParameters */ - virtual bool CanScheduleParameters() const { return true; } - - /*! @method IsBypassEffect */ - // This is used for the property value - to reflect to the UI if an effect is bypassed - bool IsBypassEffect () { return mBypassEffect; } - -protected: - - /*! @method MaintainKernels */ - void MaintainKernels(); - - /*! @method ShouldBypassEffect */ - // This is used in the render call to see if an effect is bypassed - // It can return a different status than IsBypassEffect (though it MUST take that into account) - virtual bool ShouldBypassEffect () { return IsBypassEffect(); } - -public: - /*! @method SetBypassEffect */ - virtual void SetBypassEffect (bool inFlag) { mBypassEffect = inFlag; } - - /*! @method SetParamHasSampleRateDependency */ - void SetParamHasSampleRateDependency (bool inFlag) - { - mParamSRDep = inFlag; - } - - /*! @method GetParamHasSampleRateDependency */ - bool GetParamHasSampleRateDependency () const { return mParamSRDep; } - - struct ScheduledProcessParams // pointer passed in as void* userData param for ProcessScheduledSlice() - { - AudioUnitRenderActionFlags *actionFlags; - AudioBufferList *inputBufferList; - AudioBufferList *outputBufferList; - }; - - virtual OSStatus ProcessScheduledSlice( void *inUserData, - UInt32 inStartFrameInBuffer, - UInt32 inSliceFramesToProcess, - UInt32 inTotalBufferFrames ); - - - bool ProcessesInPlace() const {return mProcessesInPlace;}; - void SetProcessesInPlace(bool inProcessesInPlace) {mProcessesInPlace = inProcessesInPlace;}; - - typedef std::vector KernelList; - - - -protected: - /*! @var mKernelList */ - KernelList mKernelList; - - AUKernelBase* GetKernel(UInt32 index) { return mKernelList[index]; } - - /*! @method IsInputSilent */ - bool IsInputSilent (AudioUnitRenderActionFlags inActionFlags, UInt32 inFramesToProcess) - { - bool inputSilent = (inActionFlags & kAudioUnitRenderAction_OutputIsSilence) != 0; - - // take latency and tail time into account when propagating the silent bit - UInt32 silentTimeoutFrames = UInt32(GetSampleRate() * (GetLatency() + GetTailTime())); - mSilentTimeout.Process (inFramesToProcess, silentTimeoutFrames, inputSilent); - return inputSilent; - } - -#if TARGET_OS_IPHONE - void SetOnlyOneKernel(bool inUseOnlyOneKernel) { mOnlyOneKernel = inUseOnlyOneKernel; } // set in ctor of subclass that wants it. -#endif - - template - void ProcessBufferListsT( - AudioUnitRenderActionFlags & ioActionFlags, - const AudioBufferList & inBuffer, - AudioBufferList & outBuffer, - UInt32 inFramesToProcess ); - - CAStreamBasicDescription::CommonPCMFormat GetCommonPCMFormat() const { return mCommonPCMFormat; } - - -private: - /*! @var mBypassEffect */ - bool mBypassEffect; - /*! @var mParamSRDep */ - bool mParamSRDep; - - /*! @var mProcessesInplace */ - bool mProcessesInPlace; - - /*! @var mSilentTimeout */ - AUSilentTimeout mSilentTimeout; - - /*! @var mMainOutput */ - AUOutputElement * mMainOutput; - - /*! @var mMainInput */ - AUInputElement * mMainInput; - -#if TARGET_OS_IPHONE - /*! @var mOnlyOneKernel */ - bool mOnlyOneKernel; -#endif - - /*! @var mCommonPCMFormat */ - CAStreamBasicDescription::CommonPCMFormat mCommonPCMFormat; - UInt32 mBytesPerFrame; -}; - - -// Base class for a "kernel", an object that performs DSP on one channel of an interleaved stream. - /*! @class AUKernelBase */ -class AUKernelBase { -public: - /*! @ctor AUKernelBase */ - AUKernelBase(AUEffectBase *inAudioUnit ) : - mAudioUnit(inAudioUnit) { } - - /*! @dtor ~AUKernelBase */ - virtual ~AUKernelBase() { } - - /*! @method Reset */ - virtual void Reset() { } - - /*! @method Process */ - virtual void Process( const Float32 * inSourceP, - Float32 * inDestP, - UInt32 inFramesToProcess, - UInt32 inNumChannels, - bool & ioSilence) { throw CAException(kAudio_UnimplementedError ); } - - /*! @method Process */ - virtual void Process( const SInt32 * inSourceP, - SInt32 * inDestP, - UInt32 inFramesToProcess, - UInt32 inNumChannels, - bool & ioSilence) { throw CAException(kAudio_UnimplementedError ); } - - /*! @method Process */ - virtual void Process( const SInt16 * inSourceP, - SInt16 * inDestP, - UInt32 inFramesToProcess, - UInt32 inNumChannels, - bool & ioSilence) { throw CAException(kAudio_UnimplementedError ); } - - /*! @method GetSampleRate */ - Float64 GetSampleRate() - { - return mAudioUnit->GetSampleRate(); - } - - /*! @method GetParameter */ - AudioUnitParameterValue GetParameter (AudioUnitParameterID paramID) - { - return mAudioUnit->GetParameter(paramID); - } - - void SetChannelNum (UInt32 inChan) { mChannelNum = inChan; } - UInt32 GetChannelNum () { return mChannelNum; } - -protected: - /*! @var mAudioUnit */ - AUEffectBase * mAudioUnit; - UInt32 mChannelNum; - -}; - -template -void AUEffectBase::ProcessBufferListsT( - AudioUnitRenderActionFlags & ioActionFlags, - const AudioBufferList & inBuffer, - AudioBufferList & outBuffer, - UInt32 inFramesToProcess ) -{ - bool ioSilence; - - bool silentInput = IsInputSilent (ioActionFlags, inFramesToProcess); - ioActionFlags |= kAudioUnitRenderAction_OutputIsSilence; - - // call the kernels to handle either interleaved or deinterleaved - if (inBuffer.mNumberBuffers == 1) { - if (inBuffer.mBuffers[0].mNumberChannels == 0) - throw CAException(kAudio_ParamError); - - for (UInt32 channel = 0; channel < mKernelList.size(); ++channel) { - AUKernelBase *kernel = mKernelList[channel]; - - if (kernel == NULL) continue; - ioSilence = silentInput; - - // process each interleaved channel individually - kernel->Process( - (const T *)inBuffer.mBuffers[0].mData + channel, - (T *)outBuffer.mBuffers[0].mData + channel, - inFramesToProcess, - inBuffer.mBuffers[0].mNumberChannels, - ioSilence); - - if (!ioSilence) - ioActionFlags &= ~kAudioUnitRenderAction_OutputIsSilence; - } - } else { - for (UInt32 channel = 0; channel < mKernelList.size(); ++channel) { - AUKernelBase *kernel = mKernelList[channel]; - - if (kernel == NULL) continue; - - ioSilence = silentInput; - const AudioBuffer *srcBuffer = &inBuffer.mBuffers[channel]; - AudioBuffer *destBuffer = &outBuffer.mBuffers[channel]; - - kernel->Process( - (const T *)srcBuffer->mData, - (T *)destBuffer->mData, - inFramesToProcess, - 1, - ioSilence); - - if (!ioSilence) - ioActionFlags &= ~kAudioUnitRenderAction_OutputIsSilence; - } - } -} - - -#endif // __AUEffectBase_h__ diff --git a/src/CoreAudio/CoreAudioComponent/AUPublic/OtherBases/AUMIDIBase.cpp b/src/CoreAudio/CoreAudioComponent/AUPublic/OtherBases/AUMIDIBase.cpp deleted file mode 100644 index e5e358d68..000000000 --- a/src/CoreAudio/CoreAudioComponent/AUPublic/OtherBases/AUMIDIBase.cpp +++ /dev/null @@ -1,495 +0,0 @@ -/* - File: AUMIDIBase.cpp - Abstract: AUMIDIBase.h - Version: 1.1 - - Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple - Inc. ("Apple") in consideration of your agreement to the following - terms, and your use, installation, modification or redistribution of - this Apple software constitutes acceptance of these terms. If you do - not agree with these terms, please do not use, install, modify or - redistribute this Apple software. - - In consideration of your agreement to abide by the following terms, and - subject to these terms, Apple grants you a personal, non-exclusive - license, under Apple's copyrights in this original Apple software (the - "Apple Software"), to use, reproduce, modify and redistribute the Apple - Software, with or without modifications, in source and/or binary forms; - provided that if you redistribute the Apple Software in its entirety and - without modifications, you must retain this notice and the following - text and disclaimers in all such redistributions of the Apple Software. - Neither the name, trademarks, service marks or logos of Apple Inc. may - be used to endorse or promote products derived from the Apple Software - without specific prior written permission from Apple. Except as - expressly stated in this notice, no other rights or licenses, express or - implied, are granted by Apple herein, including but not limited to any - patent rights that may be infringed by your derivative works or by other - works in which the Apple Software may be incorporated. - - The Apple Software is provided by Apple on an "AS IS" basis. APPLE - MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION - THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS - FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND - OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS. - - IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL - OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, - MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED - AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), - STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE - POSSIBILITY OF SUCH DAMAGE. - - Copyright (C) 2014 Apple Inc. All Rights Reserved. - -*/ -#include "AUMIDIBase.h" -#include -#include "CAXException.h" - -//temporaray location -enum -{ - kMidiMessage_NoteOff = 0x80, - kMidiMessage_NoteOn = 0x90, - kMidiMessage_PolyPressure = 0xA0, - kMidiMessage_ControlChange = 0xB0, - kMidiMessage_ProgramChange = 0xC0, - kMidiMessage_ChannelPressure = 0xD0, - kMidiMessage_PitchWheel = 0xE0, - - kMidiController_AllSoundOff = 120, - kMidiController_ResetAllControllers = 121, - kMidiController_AllNotesOff = 123 -}; - -AUMIDIBase::AUMIDIBase(AUBase* inBase) - : mAUBaseInstance (*inBase) -{ -#if CA_AUTO_MIDI_MAP - mMapManager = new CAAUMIDIMapManager(); -#endif -} - -AUMIDIBase::~AUMIDIBase() -{ -#if CA_AUTO_MIDI_MAP - if (mMapManager) - delete mMapManager; -#endif -} - -#if TARGET_API_MAC_OSX -OSStatus AUMIDIBase::DelegateGetPropertyInfo(AudioUnitPropertyID inID, - AudioUnitScope inScope, - AudioUnitElement inElement, - UInt32 & outDataSize, - Boolean & outWritable) -{ - OSStatus result = noErr; - - switch (inID) { -#if !TARGET_OS_IPHONE - case kMusicDeviceProperty_MIDIXMLNames: - ca_require(inScope == kAudioUnitScope_Global, InvalidScope); - ca_require(inElement == 0, InvalidElement); - if (GetXMLNames(NULL) == noErr) { - outDataSize = sizeof(CFURLRef); - outWritable = false; - } else - result = kAudioUnitErr_InvalidProperty; - break; -#endif -#if CA_AUTO_MIDI_MAP - case kAudioUnitProperty_AllParameterMIDIMappings: - ca_require(inScope == kAudioUnitScope_Global, InvalidScope); - ca_require(inElement == 0, InvalidElement); - outWritable = true; - outDataSize = sizeof (AUParameterMIDIMapping)*mMapManager->NumMaps(); - result = noErr; - break; - - case kAudioUnitProperty_HotMapParameterMIDIMapping: - ca_require(inScope == kAudioUnitScope_Global, InvalidScope); - ca_require(inElement == 0, InvalidElement); - outWritable = true; - outDataSize = sizeof (AUParameterMIDIMapping); - result = noErr; - break; - - case kAudioUnitProperty_AddParameterMIDIMapping: - ca_require(inScope == kAudioUnitScope_Global, InvalidScope); - ca_require(inElement == 0, InvalidElement); - outWritable = true; - outDataSize = sizeof (AUParameterMIDIMapping); - result = noErr; - break; - - case kAudioUnitProperty_RemoveParameterMIDIMapping: - ca_require(inScope == kAudioUnitScope_Global, InvalidScope); - ca_require(inElement == 0, InvalidElement); - outWritable = true; - outDataSize = sizeof (AUParameterMIDIMapping); - result = noErr; - break; -#endif - - default: - result = kAudioUnitErr_InvalidProperty; - break; - } - return result; - -#if CA_AUTO_MIDI_MAP || (!TARGET_OS_IPHONE) -InvalidScope: - return kAudioUnitErr_InvalidScope; -InvalidElement: - return kAudioUnitErr_InvalidElement; -#endif -} - -OSStatus AUMIDIBase::DelegateGetProperty( AudioUnitPropertyID inID, - AudioUnitScope inScope, - AudioUnitElement inElement, - void * outData) -{ - OSStatus result; - - switch (inID) { -#if !TARGET_OS_IPHONE - case kMusicDeviceProperty_MIDIXMLNames: - ca_require(inScope == kAudioUnitScope_Global, InvalidScope); - ca_require(inElement == 0, InvalidElement); - result = GetXMLNames((CFURLRef *)outData); - break; -#endif -#if CA_AUTO_MIDI_MAP - case kAudioUnitProperty_AllParameterMIDIMappings:{ - ca_require(inScope == kAudioUnitScope_Global, InvalidScope); - ca_require(inElement == 0, InvalidElement); - AUParameterMIDIMapping* maps = (static_cast(outData)); - mMapManager->GetMaps(maps); -// printf ("GETTING MAPS\n"); -// mMapManager->Print(); - result = noErr; - break; - } - - case kAudioUnitProperty_HotMapParameterMIDIMapping:{ - ca_require(inScope == kAudioUnitScope_Global, InvalidScope); - ca_require(inElement == 0, InvalidElement); - AUParameterMIDIMapping * map = (static_cast(outData)); - mMapManager->GetHotParameterMap (*map); - result = noErr; - break; - } -#endif - - default: - result = kAudioUnitErr_InvalidProperty; - break; - } - return result; - -#if CA_AUTO_MIDI_MAP || (!TARGET_OS_IPHONE) -InvalidScope: - return kAudioUnitErr_InvalidScope; -InvalidElement: - return kAudioUnitErr_InvalidElement; -#endif -} - -OSStatus AUMIDIBase::DelegateSetProperty( AudioUnitPropertyID inID, - AudioUnitScope inScope, - AudioUnitElement inElement, - const void * inData, - UInt32 inDataSize) -{ - OSStatus result; - - switch (inID) { -#if CA_AUTO_MIDI_MAP - case kAudioUnitProperty_AddParameterMIDIMapping:{ - ca_require(inScope == kAudioUnitScope_Global, InvalidScope); - ca_require(inElement == 0, InvalidElement); - AUParameterMIDIMapping * maps = (AUParameterMIDIMapping*)inData; - mMapManager->SortedInsertToParamaterMaps (maps, (inDataSize / sizeof(AUParameterMIDIMapping)), mAUBaseInstance); - mAUBaseInstance.PropertyChanged (kAudioUnitProperty_AllParameterMIDIMappings, kAudioUnitScope_Global, 0); - result = noErr; - break; - } - - case kAudioUnitProperty_RemoveParameterMIDIMapping:{ - ca_require(inScope == kAudioUnitScope_Global, InvalidScope); - ca_require(inElement == 0, InvalidElement); - AUParameterMIDIMapping * maps = (AUParameterMIDIMapping*)inData; - bool didChange; - mMapManager->SortedRemoveFromParameterMaps(maps, (inDataSize / sizeof(AUParameterMIDIMapping)), didChange); - if (didChange) - mAUBaseInstance.PropertyChanged (kAudioUnitProperty_AllParameterMIDIMappings, kAudioUnitScope_Global, 0); - result = noErr; - break; - } - - case kAudioUnitProperty_HotMapParameterMIDIMapping:{ - ca_require(inScope == kAudioUnitScope_Global, InvalidScope); - ca_require(inElement == 0, InvalidElement); - AUParameterMIDIMapping & map = *((AUParameterMIDIMapping*)inData); - mMapManager->SetHotMapping (map); - result = noErr; - break; - } - case kAudioUnitProperty_AllParameterMIDIMappings:{ - ca_require(inScope == kAudioUnitScope_Global, InvalidScope); - ca_require(inElement == 0, InvalidElement); - AUParameterMIDIMapping * mappings = (AUParameterMIDIMapping*)inData; - mMapManager->ReplaceAllMaps (mappings, (inDataSize / sizeof(AUParameterMIDIMapping)), mAUBaseInstance); - result = noErr; - break; - } -#endif - - default: - result = kAudioUnitErr_InvalidProperty; - break; - } - return result; -#if CA_AUTO_MIDI_MAP - InvalidScope: - return kAudioUnitErr_InvalidScope; - InvalidElement: - return kAudioUnitErr_InvalidElement; -#endif -} - - - -#endif //TARGET_API_MAC_OSX - - -//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -#pragma mark ____MidiDispatch - - -inline const Byte * NextMIDIEvent(const Byte *event, const Byte *end) -{ - Byte c = *event; - switch (c >> 4) { - default: // data byte -- assume in sysex - while ((*++event & 0x80) == 0 && event < end) - ; - break; - case 0x8: - case 0x9: - case 0xA: - case 0xB: - case 0xE: - event += 3; - break; - case 0xC: - case 0xD: - event += 2; - break; - case 0xF: - switch (c) { - case 0xF0: - while ((*++event & 0x80) == 0 && event < end) - ; - break; - case 0xF1: - case 0xF3: - event += 2; - break; - case 0xF2: - event += 3; - break; - default: - ++event; - break; - } - } - return (event >= end) ? end : event; -} - -//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -// AUMIDIBase::HandleMIDIPacketList -// -//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -OSStatus AUMIDIBase::HandleMIDIPacketList(const MIDIPacketList *pktlist) -{ - if (!mAUBaseInstance.IsInitialized()) return kAudioUnitErr_Uninitialized; - - int nPackets = pktlist->numPackets; - const MIDIPacket *pkt = pktlist->packet; - - while (nPackets-- > 0) { - const Byte *event = pkt->data, *packetEnd = event + pkt->length; - long startFrame = (long)pkt->timeStamp; - while (event < packetEnd) { - Byte status = event[0]; - if (status & 0x80) { - // really a status byte (not sysex continuation) - HandleMidiEvent(status & 0xF0, status & 0x0F, event[1], event[2], static_cast(startFrame)); - // note that we're generating a bogus channel number for system messages (0xF0-FF) - } - event = NextMIDIEvent(event, packetEnd); - } - pkt = reinterpret_cast(packetEnd); - } - return noErr; -} - -//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -// AUMIDIBase::HandleMidiEvent -// -//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -OSStatus AUMIDIBase::HandleMidiEvent(UInt8 status, UInt8 channel, UInt8 data1, UInt8 data2, UInt32 inStartFrame) -{ - if (!mAUBaseInstance.IsInitialized()) return kAudioUnitErr_Uninitialized; - -#if CA_AUTO_MIDI_MAP -// you potentially have a choice to make here - if a param mapping matches, do you still want to process the -// MIDI event or not. The default behaviour is to continue on with the MIDI event. - if (mMapManager->HandleHotMapping (status, channel, data1, mAUBaseInstance)) { - mAUBaseInstance.PropertyChanged (kAudioUnitProperty_HotMapParameterMIDIMapping, kAudioUnitScope_Global, 0); - } - else { - mMapManager->FindParameterMapEventMatch(status, channel, data1, data2, inStartFrame, mAUBaseInstance); - } -#endif - - OSStatus result = noErr; - - switch(status) - { - case kMidiMessage_NoteOn: - if(data2) - { - result = HandleNoteOn(channel, data1, data2, inStartFrame); - } - else - { - // zero velocity translates to note off - result = HandleNoteOff(channel, data1, data2, inStartFrame); - } - break; - - case kMidiMessage_NoteOff: - result = HandleNoteOff(channel, data1, data2, inStartFrame); - break; - - default: - result = HandleNonNoteEvent (status, channel, data1, data2, inStartFrame); - break; - } - - return result; -} - -OSStatus AUMIDIBase::HandleNonNoteEvent (UInt8 status, UInt8 channel, UInt8 data1, UInt8 data2, UInt32 inStartFrame) -{ - OSStatus result = noErr; - - switch (status) - { - case kMidiMessage_PitchWheel: - result = HandlePitchWheel(channel, data1, data2, inStartFrame); - break; - - case kMidiMessage_ProgramChange: - result = HandleProgramChange(channel, data1); - break; - - case kMidiMessage_ChannelPressure: - result = HandleChannelPressure(channel, data1, inStartFrame); - break; - - case kMidiMessage_ControlChange: - { - switch (data1) { - case kMidiController_AllNotesOff: - result = HandleAllNotesOff(channel); - break; - - case kMidiController_ResetAllControllers: - result = HandleResetAllControllers(channel); - break; - - case kMidiController_AllSoundOff: - result = HandleAllSoundOff(channel); - break; - - default: - result = HandleControlChange(channel, data1, data2, inStartFrame); - break; - } - break; - } - case kMidiMessage_PolyPressure: - result = HandlePolyPressure (channel, data1, data2, inStartFrame); - break; - } - return result; -} - -OSStatus AUMIDIBase::SysEx (const UInt8 * inData, - UInt32 inLength) -{ - if (!mAUBaseInstance.IsInitialized()) return kAudioUnitErr_Uninitialized; - - return HandleSysEx(inData, inLength ); -} - - - -#if TARGET_OS_MAC - #if __LP64__ - // comp instance, parameters in forward order - #define PARAM(_typ, _name, _index, _nparams) \ - _typ _name = *(_typ *)¶ms->params[_index + 1]; - #else - // parameters in reverse order, then comp instance - #define PARAM(_typ, _name, _index, _nparams) \ - _typ _name = *(_typ *)¶ms->params[_nparams - 1 - _index]; - #endif -#elif TARGET_OS_WIN32 - // (no comp instance), parameters in forward order - #define PARAM(_typ, _name, _index, _nparams) \ - _typ _name = *(_typ *)¶ms->params[_index]; -#endif - -#if !CA_USE_AUDIO_PLUGIN_ONLY -OSStatus AUMIDIBase::ComponentEntryDispatch( ComponentParameters * params, - AUMIDIBase * This) -{ - if (This == NULL) return kAudio_ParamError; - - OSStatus result; - - switch (params->what) { - case kMusicDeviceMIDIEventSelect: - { - PARAM(UInt32, pbinStatus, 0, 4); - PARAM(UInt32, pbinData1, 1, 4); - PARAM(UInt32, pbinData2, 2, 4); - PARAM(UInt32, pbinOffsetSampleFrame, 3, 4); - result = This->MIDIEvent(pbinStatus, pbinData1, pbinData2, pbinOffsetSampleFrame); - } - break; - case kMusicDeviceSysExSelect: - { - PARAM(const UInt8 *, pbinData, 0, 2); - PARAM(UInt32, pbinLength, 1, 2); - result = This->SysEx(pbinData, pbinLength); - } - break; - - default: - result = badComponentSelector; - break; - } - - return result; -} -#endif diff --git a/src/CoreAudio/CoreAudioComponent/AUPublic/OtherBases/AUMIDIBase.h b/src/CoreAudio/CoreAudioComponent/AUPublic/OtherBases/AUMIDIBase.h deleted file mode 100644 index 40c6a7769..000000000 --- a/src/CoreAudio/CoreAudioComponent/AUPublic/OtherBases/AUMIDIBase.h +++ /dev/null @@ -1,213 +0,0 @@ -/* - File: AUMIDIBase.h - Abstract: Part of CoreAudio Utility Classes - Version: 1.1 - - Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple - Inc. ("Apple") in consideration of your agreement to the following - terms, and your use, installation, modification or redistribution of - this Apple software constitutes acceptance of these terms. If you do - not agree with these terms, please do not use, install, modify or - redistribute this Apple software. - - In consideration of your agreement to abide by the following terms, and - subject to these terms, Apple grants you a personal, non-exclusive - license, under Apple's copyrights in this original Apple software (the - "Apple Software"), to use, reproduce, modify and redistribute the Apple - Software, with or without modifications, in source and/or binary forms; - provided that if you redistribute the Apple Software in its entirety and - without modifications, you must retain this notice and the following - text and disclaimers in all such redistributions of the Apple Software. - Neither the name, trademarks, service marks or logos of Apple Inc. may - be used to endorse or promote products derived from the Apple Software - without specific prior written permission from Apple. Except as - expressly stated in this notice, no other rights or licenses, express or - implied, are granted by Apple herein, including but not limited to any - patent rights that may be infringed by your derivative works or by other - works in which the Apple Software may be incorporated. - - The Apple Software is provided by Apple on an "AS IS" basis. APPLE - MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION - THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS - FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND - OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS. - - IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL - OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, - MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED - AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), - STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE - POSSIBILITY OF SUCH DAMAGE. - - Copyright (C) 2014 Apple Inc. All Rights Reserved. - -*/ -#ifndef __AUMIDIBase_h__ -#define __AUMIDIBase_h__ - -#include "AUBase.h" - -#if CA_AUTO_MIDI_MAP - #include "CAAUMIDIMapManager.h" -#endif - -struct MIDIPacketList; - -// ________________________________________________________________________ -// MusicDeviceBase -// - /*! @class AUMIDIBase */ -class AUMIDIBase { -public: - // this is NOT a copy constructor! - /*! @ctor AUMIDIBase */ - AUMIDIBase(AUBase* inBase); - /*! @dtor ~AUMIDIBase */ - virtual ~AUMIDIBase(); - - /*! @method MIDIEvent */ - virtual OSStatus MIDIEvent( UInt32 inStatus, - UInt32 inData1, - UInt32 inData2, - UInt32 inOffsetSampleFrame) - { - UInt32 strippedStatus = inStatus & 0xf0; - UInt32 channel = inStatus & 0x0f; - - return HandleMidiEvent(strippedStatus, channel, inData1, inData2, inOffsetSampleFrame); - } - - /*! @method HandleMIDIPacketList */ - OSStatus HandleMIDIPacketList(const MIDIPacketList *pktlist); - - /*! @method SysEx */ - virtual OSStatus SysEx( const UInt8 * inData, - UInt32 inLength); - -#if TARGET_API_MAC_OSX - /*! @method DelegateGetPropertyInfo */ - virtual OSStatus DelegateGetPropertyInfo(AudioUnitPropertyID inID, - AudioUnitScope inScope, - AudioUnitElement inElement, - UInt32 & outDataSize, - Boolean & outWritable); - - /*! @method DelegateGetProperty */ - virtual OSStatus DelegateGetProperty( AudioUnitPropertyID inID, - AudioUnitScope inScope, - AudioUnitElement inElement, - void * outData); - - /*! @method DelegateSetProperty */ - virtual OSStatus DelegateSetProperty( AudioUnitPropertyID inID, - AudioUnitScope inScope, - AudioUnitElement inElement, - const void * inData, - UInt32 inDataSize); -#endif - -protected: - // MIDI dispatch - /*! @method HandleMidiEvent */ - virtual OSStatus HandleMidiEvent( UInt8 inStatus, - UInt8 inChannel, - UInt8 inData1, - UInt8 inData2, - UInt32 inStartFrame); - - /*! @method HandleNonNoteEvent */ - virtual OSStatus HandleNonNoteEvent ( UInt8 status, - UInt8 channel, - UInt8 data1, - UInt8 data2, - UInt32 inStartFrame); - -#if TARGET_API_MAC_OSX - /*! @method GetXMLNames */ - virtual OSStatus GetXMLNames(CFURLRef *outNameDocument) - { return kAudioUnitErr_InvalidProperty; } // if not overridden, it's unsupported -#endif - -// channel messages - /*! @method HandleNoteOn */ - virtual OSStatus HandleNoteOn( UInt8 inChannel, - UInt8 inNoteNumber, - UInt8 inVelocity, - UInt32 inStartFrame) { return noErr; } - - /*! @method HandleNoteOff */ - virtual OSStatus HandleNoteOff( UInt8 inChannel, - UInt8 inNoteNumber, - UInt8 inVelocity, - UInt32 inStartFrame) { return noErr; } - - /*! @method HandleControlChange */ - virtual OSStatus HandleControlChange( UInt8 inChannel, - UInt8 inController, - UInt8 inValue, - UInt32 inStartFrame) { return noErr; } - - /*! @method HandlePitchWheel */ - virtual OSStatus HandlePitchWheel( UInt8 inChannel, - UInt8 inPitch1, - UInt8 inPitch2, - UInt32 inStartFrame) { return noErr; } - - /*! @method HandleChannelPressure */ - virtual OSStatus HandleChannelPressure( UInt8 inChannel, - UInt8 inValue, - UInt32 inStartFrame) { return noErr; } - - /*! @method HandleProgramChange */ - virtual OSStatus HandleProgramChange( UInt8 inChannel, - UInt8 inValue) { return noErr; } - - /*! @method HandlePolyPressure */ - virtual OSStatus HandlePolyPressure( UInt8 inChannel, - UInt8 inKey, - UInt8 inValue, - UInt32 inStartFrame) { return noErr; } - - /*! @method HandleResetAllControllers */ - virtual OSStatus HandleResetAllControllers(UInt8 inChannel) { return noErr; } - - /*! @method HandleAllNotesOff */ - virtual OSStatus HandleAllNotesOff( UInt8 inChannel) { return noErr; } - - /*! @method HandleAllSoundOff */ - virtual OSStatus HandleAllSoundOff( UInt8 inChannel) { return noErr; } - - -//System messages - /*! @method HandleSysEx */ - virtual OSStatus HandleSysEx( const UInt8 * inData, - UInt32 inLength ) { return noErr; } - -#if CA_AUTO_MIDI_MAP - /* map manager */ - CAAUMIDIMapManager *GetMIDIMapManager() {return mMapManager;}; - -#endif - - -private: - /*! @var mAUBaseInstance */ - AUBase & mAUBaseInstance; - -#if CA_AUTO_MIDI_MAP - /* map manager */ - CAAUMIDIMapManager * mMapManager; -#endif - -public: -#if !CA_USE_AUDIO_PLUGIN_ONLY - // component dispatcher - /*! @method ComponentEntryDispatch */ - static OSStatus ComponentEntryDispatch( ComponentParameters *params, - AUMIDIBase *This); -#endif -}; - -#endif // __AUMIDIBase_h__ diff --git a/src/CoreAudio/CoreAudioComponent/AUPublic/OtherBases/AUMIDIEffectBase.cpp b/src/CoreAudio/CoreAudioComponent/AUPublic/OtherBases/AUMIDIEffectBase.cpp deleted file mode 100644 index dfe307c9e..000000000 --- a/src/CoreAudio/CoreAudioComponent/AUPublic/OtherBases/AUMIDIEffectBase.cpp +++ /dev/null @@ -1,164 +0,0 @@ -/* - File: AUMIDIEffectBase.cpp - Abstract: AUMIDIEffectBase.h - Version: 1.1 - - Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple - Inc. ("Apple") in consideration of your agreement to the following - terms, and your use, installation, modification or redistribution of - this Apple software constitutes acceptance of these terms. If you do - not agree with these terms, please do not use, install, modify or - redistribute this Apple software. - - In consideration of your agreement to abide by the following terms, and - subject to these terms, Apple grants you a personal, non-exclusive - license, under Apple's copyrights in this original Apple software (the - "Apple Software"), to use, reproduce, modify and redistribute the Apple - Software, with or without modifications, in source and/or binary forms; - provided that if you redistribute the Apple Software in its entirety and - without modifications, you must retain this notice and the following - text and disclaimers in all such redistributions of the Apple Software. - Neither the name, trademarks, service marks or logos of Apple Inc. may - be used to endorse or promote products derived from the Apple Software - without specific prior written permission from Apple. Except as - expressly stated in this notice, no other rights or licenses, express or - implied, are granted by Apple herein, including but not limited to any - patent rights that may be infringed by your derivative works or by other - works in which the Apple Software may be incorporated. - - The Apple Software is provided by Apple on an "AS IS" basis. APPLE - MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION - THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS - FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND - OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS. - - IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL - OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, - MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED - AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), - STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE - POSSIBILITY OF SUCH DAMAGE. - - Copyright (C) 2014 Apple Inc. All Rights Reserved. - -*/ -#include "AUMIDIEffectBase.h" - -// compatibility with older OS SDK releases -typedef OSStatus -(*TEMP_MusicDeviceMIDIEventProc)( void * inComponentStorage, - UInt32 inStatus, - UInt32 inData1, - UInt32 inData2, - UInt32 inOffsetSampleFrame); - -static OSStatus AUMIDIEffectBaseMIDIEvent(void * inComponentStorage, - UInt32 inStatus, - UInt32 inData1, - UInt32 inData2, - UInt32 inOffsetSampleFrame); - -AUMIDIEffectBase::AUMIDIEffectBase( AudioComponentInstance inInstance, - bool inProcessesInPlace ) - : AUEffectBase(inInstance, inProcessesInPlace), - AUMIDIBase(this) -{ -} - -OSStatus AUMIDIEffectBase::GetPropertyInfo(AudioUnitPropertyID inID, - AudioUnitScope inScope, - AudioUnitElement inElement, - UInt32 & outDataSize, - Boolean & outWritable) -{ - OSStatus result; - - result = AUEffectBase::GetPropertyInfo (inID, inScope, inElement, outDataSize, outWritable); - - if (result == kAudioUnitErr_InvalidProperty) - result = AUMIDIBase::DelegateGetPropertyInfo (inID, inScope, inElement, outDataSize, outWritable); - - return result; -} - -OSStatus AUMIDIEffectBase::GetProperty( AudioUnitPropertyID inID, - AudioUnitScope inScope, - AudioUnitElement inElement, - void * outData) -{ - OSStatus result; - -#if !CA_USE_AUDIO_PLUGIN_ONLY - if (inID == kAudioUnitProperty_FastDispatch) { - if (inElement == kMusicDeviceMIDIEventSelect) { - *(TEMP_MusicDeviceMIDIEventProc *)outData = AUMIDIEffectBaseMIDIEvent; - return noErr; - } - return kAudioUnitErr_InvalidElement; - } -#endif - - result = AUEffectBase::GetProperty (inID, inScope, inElement, outData); - - if (result == kAudioUnitErr_InvalidProperty) - result = AUMIDIBase::DelegateGetProperty (inID, inScope, inElement, outData); - - return result; -} - -OSStatus AUMIDIEffectBase::SetProperty( AudioUnitPropertyID inID, - AudioUnitScope inScope, - AudioUnitElement inElement, - const void * inData, - UInt32 inDataSize) -{ - - OSStatus result = AUEffectBase::SetProperty (inID, inScope, inElement, inData, inDataSize); - - if (result == kAudioUnitErr_InvalidProperty) - result = AUMIDIBase::DelegateSetProperty (inID, inScope, inElement, inData, inDataSize); - - return result; -} - - -#if !TARGET_OS_IPHONE -OSStatus AUMIDIEffectBase::ComponentEntryDispatch(ComponentParameters * params, - AUMIDIEffectBase * This) -{ - if (This == NULL) return paramErr; - - OSStatus result; - - switch (params->what) { - case kMusicDeviceMIDIEventSelect: - case kMusicDeviceSysExSelect: - result = AUMIDIBase::ComponentEntryDispatch (params, This); - break; - default: - result = AUEffectBase::ComponentEntryDispatch(params, This); - break; - } - - return result; -} -#endif - -// fast dispatch -static OSStatus AUMIDIEffectBaseMIDIEvent(void * inComponentStorage, - UInt32 inStatus, - UInt32 inData1, - UInt32 inData2, - UInt32 inOffsetSampleFrame) -{ - OSStatus result = noErr; - try { - AUMIDIEffectBase *This = static_cast(inComponentStorage); - if (This == NULL) return paramErr; - result = This->AUMIDIBase::MIDIEvent(inStatus, inData1, inData2, inOffsetSampleFrame); - } - COMPONENT_CATCH - return result; -} diff --git a/src/CoreAudio/CoreAudioComponent/AUPublic/OtherBases/AUMIDIEffectBase.h b/src/CoreAudio/CoreAudioComponent/AUPublic/OtherBases/AUMIDIEffectBase.h deleted file mode 100644 index b38f506d6..000000000 --- a/src/CoreAudio/CoreAudioComponent/AUPublic/OtherBases/AUMIDIEffectBase.h +++ /dev/null @@ -1,104 +0,0 @@ -/* - File: AUMIDIEffectBase.h - Abstract: Part of CoreAudio Utility Classes - Version: 1.1 - - Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple - Inc. ("Apple") in consideration of your agreement to the following - terms, and your use, installation, modification or redistribution of - this Apple software constitutes acceptance of these terms. If you do - not agree with these terms, please do not use, install, modify or - redistribute this Apple software. - - In consideration of your agreement to abide by the following terms, and - subject to these terms, Apple grants you a personal, non-exclusive - license, under Apple's copyrights in this original Apple software (the - "Apple Software"), to use, reproduce, modify and redistribute the Apple - Software, with or without modifications, in source and/or binary forms; - provided that if you redistribute the Apple Software in its entirety and - without modifications, you must retain this notice and the following - text and disclaimers in all such redistributions of the Apple Software. - Neither the name, trademarks, service marks or logos of Apple Inc. may - be used to endorse or promote products derived from the Apple Software - without specific prior written permission from Apple. Except as - expressly stated in this notice, no other rights or licenses, express or - implied, are granted by Apple herein, including but not limited to any - patent rights that may be infringed by your derivative works or by other - works in which the Apple Software may be incorporated. - - The Apple Software is provided by Apple on an "AS IS" basis. APPLE - MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION - THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS - FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND - OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS. - - IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL - OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, - MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED - AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), - STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE - POSSIBILITY OF SUCH DAMAGE. - - Copyright (C) 2014 Apple Inc. All Rights Reserved. - -*/ -#ifndef __AUMIDIEffectBase_h__ -#define __AUMIDIEffectBase_h__ - -#include "AUMIDIBase.h" -#include "AUEffectBase.h" - -// ________________________________________________________________________ -// AUMIDIEffectBase -// - /*! @class AUMIDIEffectBase */ -class AUMIDIEffectBase : public AUEffectBase, public AUMIDIBase { -public: - /*! @ctor AUMIDIEffectBase */ - AUMIDIEffectBase( AudioComponentInstance inInstance, - bool inProcessesInPlace = false ); - /*! @method MIDIEvent */ - virtual OSStatus MIDIEvent(UInt32 inStatus, - UInt32 inData1, - UInt32 inData2, - UInt32 inOffsetSampleFrame) - { - return AUMIDIBase::MIDIEvent (inStatus, inData1, inData2, inOffsetSampleFrame); - } - - /*! @method SysEx */ - virtual OSStatus SysEx(const UInt8 * inData, - UInt32 inLength) - { - return AUMIDIBase::SysEx (inData, inLength); - } - - /*! @method GetPropertyInfo */ - virtual OSStatus GetPropertyInfo(AudioUnitPropertyID inID, - AudioUnitScope inScope, - AudioUnitElement inElement, - UInt32 & outDataSize, - Boolean & outWritable); - - /*! @method GetProperty */ - virtual OSStatus GetProperty( AudioUnitPropertyID inID, - AudioUnitScope inScope, - AudioUnitElement inElement, - void * outData); - /*! @method SetProperty */ - virtual OSStatus SetProperty( AudioUnitPropertyID inID, - AudioUnitScope inScope, - AudioUnitElement inElement, - const void * inData, - UInt32 inDataSize); -#if !TARGET_OS_IPHONE - // component dispatcher - /*! @method ComponentEntryDispatch */ - static OSStatus ComponentEntryDispatch( ComponentParameters * params, - AUMIDIEffectBase * This); -#endif -}; - -#endif // __AUMIDIEffectBase_h__ diff --git a/src/CoreAudio/CoreAudioComponent/AUPublic/OtherBases/MusicDeviceBase.cpp b/src/CoreAudio/CoreAudioComponent/AUPublic/OtherBases/MusicDeviceBase.cpp deleted file mode 100644 index 28e4d366b..000000000 --- a/src/CoreAudio/CoreAudioComponent/AUPublic/OtherBases/MusicDeviceBase.cpp +++ /dev/null @@ -1,354 +0,0 @@ -/* - File: MusicDeviceBase.cpp - Abstract: MusicDeviceBase.h - Version: 1.1 - - Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple - Inc. ("Apple") in consideration of your agreement to the following - terms, and your use, installation, modification or redistribution of - this Apple software constitutes acceptance of these terms. If you do - not agree with these terms, please do not use, install, modify or - redistribute this Apple software. - - In consideration of your agreement to abide by the following terms, and - subject to these terms, Apple grants you a personal, non-exclusive - license, under Apple's copyrights in this original Apple software (the - "Apple Software"), to use, reproduce, modify and redistribute the Apple - Software, with or without modifications, in source and/or binary forms; - provided that if you redistribute the Apple Software in its entirety and - without modifications, you must retain this notice and the following - text and disclaimers in all such redistributions of the Apple Software. - Neither the name, trademarks, service marks or logos of Apple Inc. may - be used to endorse or promote products derived from the Apple Software - without specific prior written permission from Apple. Except as - expressly stated in this notice, no other rights or licenses, express or - implied, are granted by Apple herein, including but not limited to any - patent rights that may be infringed by your derivative works or by other - works in which the Apple Software may be incorporated. - - The Apple Software is provided by Apple on an "AS IS" basis. APPLE - MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION - THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS - FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND - OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS. - - IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL - OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, - MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED - AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), - STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE - POSSIBILITY OF SUCH DAMAGE. - - Copyright (C) 2014 Apple Inc. All Rights Reserved. - -*/ -#include "MusicDeviceBase.h" - -// compatibility with older OS SDK releases -typedef OSStatus -(*TEMP_MusicDeviceMIDIEventProc)( void * inComponentStorage, - UInt32 inStatus, - UInt32 inData1, - UInt32 inData2, - UInt32 inOffsetSampleFrame); - -typedef OSStatus -(*TEMP_MusicDeviceStartNoteProc)( void * inComponentStorage, - MusicDeviceInstrumentID inInstrument, - MusicDeviceGroupID inGroupID, - NoteInstanceID * outNoteInstanceID, - UInt32 inOffsetSampleFrame, - const MusicDeviceNoteParams * inParams); - -typedef OSStatus -(*TEMP_MusicDeviceStopNoteProc)(void * inComponentStorage, - MusicDeviceGroupID inGroupID, - NoteInstanceID inNoteInstanceID, - UInt32 inOffsetSampleFrame); - -#if !CA_USE_AUDIO_PLUGIN_ONLY - -static OSStatus MusicDeviceBaseMIDIEvent(void * inComponentStorage, - UInt32 inStatus, - UInt32 inData1, - UInt32 inData2, - UInt32 inOffsetSampleFrame); - -static OSStatus MusicDeviceBaseStartNote( void * inComponentStorage, - MusicDeviceInstrumentID inInstrument, - MusicDeviceGroupID inGroupID, - NoteInstanceID * outNoteInstanceID, - UInt32 inOffsetSampleFrame, - const MusicDeviceNoteParams * inParams); - -static OSStatus MusicDeviceBaseStopNote(void * inComponentStorage, - MusicDeviceGroupID inGroupID, - NoteInstanceID inNoteInstanceID, - UInt32 inOffsetSampleFrame); - -#endif - -MusicDeviceBase::MusicDeviceBase(AudioComponentInstance inInstance, - UInt32 numInputs, - UInt32 numOutputs, - UInt32 numGroups) - : AUBase(inInstance, numInputs, numOutputs, numGroups), - AUMIDIBase(this) -{ -} - -OSStatus MusicDeviceBase::GetPropertyInfo(AudioUnitPropertyID inID, - AudioUnitScope inScope, - AudioUnitElement inElement, - UInt32 & outDataSize, - Boolean & outWritable) -{ - OSStatus result; - - switch (inID) - { -#if !TARGET_OS_IPHONE - case kMusicDeviceProperty_InstrumentCount: - if (inScope != kAudioUnitScope_Global) return kAudioUnitErr_InvalidScope; - outDataSize = sizeof(UInt32); - outWritable = false; - result = noErr; - break; -#endif - default: - result = AUBase::GetPropertyInfo (inID, inScope, inElement, outDataSize, outWritable); - - if (result == kAudioUnitErr_InvalidProperty) - result = AUMIDIBase::DelegateGetPropertyInfo (inID, inScope, inElement, outDataSize, outWritable); - break; - } - return result; -} - -OSStatus MusicDeviceBase::GetProperty( AudioUnitPropertyID inID, - AudioUnitScope inScope, - AudioUnitElement inElement, - void * outData) -{ - OSStatus result; - - switch (inID) - { -#if !CA_USE_AUDIO_PLUGIN_ONLY - case kAudioUnitProperty_FastDispatch: - if (!IsCMgrObject()) return kAudioUnitErr_InvalidProperty; - if (inElement == kMusicDeviceMIDIEventSelect) { - *(TEMP_MusicDeviceMIDIEventProc *)outData = MusicDeviceBaseMIDIEvent; - return noErr; - } - else if (inElement == kMusicDeviceStartNoteSelect) { - *(TEMP_MusicDeviceStartNoteProc *)outData = MusicDeviceBaseStartNote; - return noErr; - } - else if (inElement == kMusicDeviceStopNoteSelect) { - *(TEMP_MusicDeviceStopNoteProc *)outData = MusicDeviceBaseStopNote; - return noErr; - } - return kAudioUnitErr_InvalidElement; -#endif - -#if !TARGET_OS_IPHONE - case kMusicDeviceProperty_InstrumentCount: - if (inScope != kAudioUnitScope_Global) return kAudioUnitErr_InvalidScope; - return GetInstrumentCount (*(UInt32*)outData); -#endif - default: - result = AUBase::GetProperty (inID, inScope, inElement, outData); - - if (result == kAudioUnitErr_InvalidProperty) - result = AUMIDIBase::DelegateGetProperty (inID, inScope, inElement, outData); - } - - return result; -} - - -OSStatus MusicDeviceBase::SetProperty( AudioUnitPropertyID inID, - AudioUnitScope inScope, - AudioUnitElement inElement, - const void * inData, - UInt32 inDataSize) - -{ - - OSStatus result = AUBase::SetProperty (inID, inScope, inElement, inData, inDataSize); - - if (result == kAudioUnitErr_InvalidProperty) - result = AUMIDIBase::DelegateSetProperty (inID, inScope, inElement, inData, inDataSize); - - return result; -} - -// For a MusicDevice that doesn't support separate instruments (ie. is mono-timbral) -// then this call should return an instrument count of zero and noErr -OSStatus MusicDeviceBase::GetInstrumentCount (UInt32 &outInstCount) const -{ - outInstCount = 0; - return noErr; -} - -OSStatus MusicDeviceBase::HandleNoteOn( UInt8 inChannel, - UInt8 inNoteNumber, - UInt8 inVelocity, - UInt32 inStartFrame) -{ - MusicDeviceNoteParams params; - params.argCount = 2; - params.mPitch = inNoteNumber; - params.mVelocity = inVelocity; - return StartNote (kMusicNoteEvent_UseGroupInstrument, inChannel, NULL, inStartFrame, params); -} - -OSStatus MusicDeviceBase::HandleNoteOff( UInt8 inChannel, - UInt8 inNoteNumber, - UInt8 inVelocity, - UInt32 inStartFrame) -{ - return StopNote (inChannel, inNoteNumber, inStartFrame); -} - -OSStatus -MusicDeviceBase::HandleStartNoteMessage (MusicDeviceInstrumentID inInstrument, - MusicDeviceGroupID inGroupID, - NoteInstanceID * outNoteInstanceID, - UInt32 inOffsetSampleFrame, - const MusicDeviceNoteParams * inParams) -{ - if (inParams == NULL || outNoteInstanceID == NULL) return kAudio_ParamError; - - if (!IsInitialized()) return kAudioUnitErr_Uninitialized; - - return StartNote (inInstrument, inGroupID, outNoteInstanceID, inOffsetSampleFrame, *inParams); -} - -#if TARGET_OS_MAC - #if __LP64__ - // comp instance, parameters in forward order - #define PARAM(_typ, _name, _index, _nparams) \ - _typ _name = *(_typ *)¶ms->params[_index + 1]; - #else - // parameters in reverse order, then comp instance - #define PARAM(_typ, _name, _index, _nparams) \ - _typ _name = *(_typ *)¶ms->params[_nparams - 1 - _index]; - #endif -#elif TARGET_OS_WIN32 - // (no comp instance), parameters in forward order - #define PARAM(_typ, _name, _index, _nparams) \ - _typ _name = *(_typ *)¶ms->params[_index]; -#endif - -#if !CA_USE_AUDIO_PLUGIN_ONLY -OSStatus MusicDeviceBase::ComponentEntryDispatch( ComponentParameters * params, - MusicDeviceBase * This) -{ - if (This == NULL) return kAudio_ParamError; - - OSStatus result; - - switch (params->what) { - case kMusicDeviceMIDIEventSelect: - case kMusicDeviceSysExSelect: - { - result = AUMIDIBase::ComponentEntryDispatch (params, This); - } - break; - case kMusicDevicePrepareInstrumentSelect: - { - PARAM(MusicDeviceInstrumentID, inInstrument, 0, 1); - result = This->PrepareInstrument(inInstrument); - } - break; - case kMusicDeviceReleaseInstrumentSelect: - { - PARAM(MusicDeviceInstrumentID, inInstrument, 0, 1); - result = This->ReleaseInstrument(inInstrument); - } - break; - case kMusicDeviceStartNoteSelect: - { - PARAM(MusicDeviceInstrumentID, pbinInstrument, 0, 5); - PARAM(MusicDeviceGroupID, pbinGroupID, 1, 5); - PARAM(NoteInstanceID *, pboutNoteInstanceID, 2, 5); - PARAM(UInt32, pbinOffsetSampleFrame, 3, 5); - PARAM(const MusicDeviceNoteParams *, pbinParams, 4, 5); - result = This->HandleStartNoteMessage(pbinInstrument, pbinGroupID, pboutNoteInstanceID, pbinOffsetSampleFrame, pbinParams); - } - break; - case kMusicDeviceStopNoteSelect: - { - PARAM(MusicDeviceGroupID, pbinGroupID, 0, 3); - PARAM(NoteInstanceID, pbinNoteInstanceID, 1, 3); - PARAM(UInt32, pbinOffsetSampleFrame, 2, 3); - result = This->StopNote(pbinGroupID, pbinNoteInstanceID, pbinOffsetSampleFrame); - } - break; - - default: - result = AUBase::ComponentEntryDispatch(params, This); - break; - } - - return result; -} -#endif - -#if !CA_USE_AUDIO_PLUGIN_ONLY - -// fast dispatch -static OSStatus MusicDeviceBaseMIDIEvent(void * inComponentStorage, - UInt32 inStatus, - UInt32 inData1, - UInt32 inData2, - UInt32 inOffsetSampleFrame) -{ - OSStatus result = noErr; - try { - MusicDeviceBase *This = static_cast(inComponentStorage); - if (This == NULL) return kAudio_ParamError; - result = This->MIDIEvent(inStatus, inData1, inData2, inOffsetSampleFrame); - } - COMPONENT_CATCH - return result; -} - -OSStatus MusicDeviceBaseStartNote( void * inComponentStorage, - MusicDeviceInstrumentID inInstrument, - MusicDeviceGroupID inGroupID, - NoteInstanceID * outNoteInstanceID, - UInt32 inOffsetSampleFrame, - const MusicDeviceNoteParams * inParams) -{ - OSStatus result = noErr; - try { - if (inParams == NULL || outNoteInstanceID == NULL) return kAudio_ParamError; - MusicDeviceBase *This = static_cast(inComponentStorage); - if (This == NULL) return kAudio_ParamError; - result = This->StartNote(inInstrument, inGroupID, outNoteInstanceID, inOffsetSampleFrame, *inParams); - } - COMPONENT_CATCH - return result; -} - -OSStatus MusicDeviceBaseStopNote(void * inComponentStorage, - MusicDeviceGroupID inGroupID, - NoteInstanceID inNoteInstanceID, - UInt32 inOffsetSampleFrame) -{ - OSStatus result = noErr; - try { - MusicDeviceBase *This = static_cast(inComponentStorage); - if (This == NULL) return kAudio_ParamError; - result = This->StopNote(inGroupID, inNoteInstanceID, inOffsetSampleFrame); - } - COMPONENT_CATCH - return result; -} - -#endif diff --git a/src/CoreAudio/CoreAudioComponent/AUPublic/OtherBases/MusicDeviceBase.h b/src/CoreAudio/CoreAudioComponent/AUPublic/OtherBases/MusicDeviceBase.h deleted file mode 100644 index 4850b8f0c..000000000 --- a/src/CoreAudio/CoreAudioComponent/AUPublic/OtherBases/MusicDeviceBase.h +++ /dev/null @@ -1,126 +0,0 @@ -/* - File: MusicDeviceBase.h - Abstract: Part of CoreAudio Utility Classes - Version: 1.1 - - Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple - Inc. ("Apple") in consideration of your agreement to the following - terms, and your use, installation, modification or redistribution of - this Apple software constitutes acceptance of these terms. If you do - not agree with these terms, please do not use, install, modify or - redistribute this Apple software. - - In consideration of your agreement to abide by the following terms, and - subject to these terms, Apple grants you a personal, non-exclusive - license, under Apple's copyrights in this original Apple software (the - "Apple Software"), to use, reproduce, modify and redistribute the Apple - Software, with or without modifications, in source and/or binary forms; - provided that if you redistribute the Apple Software in its entirety and - without modifications, you must retain this notice and the following - text and disclaimers in all such redistributions of the Apple Software. - Neither the name, trademarks, service marks or logos of Apple Inc. may - be used to endorse or promote products derived from the Apple Software - without specific prior written permission from Apple. Except as - expressly stated in this notice, no other rights or licenses, express or - implied, are granted by Apple herein, including but not limited to any - patent rights that may be infringed by your derivative works or by other - works in which the Apple Software may be incorporated. - - The Apple Software is provided by Apple on an "AS IS" basis. APPLE - MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION - THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS - FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND - OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS. - - IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL - OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, - MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED - AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), - STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE - POSSIBILITY OF SUCH DAMAGE. - - Copyright (C) 2014 Apple Inc. All Rights Reserved. - -*/ -#ifndef __MusicDeviceBase_h__ -#define __MusicDeviceBase_h__ - -#include "AUMIDIBase.h" - -// ________________________________________________________________________ -// MusicDeviceBase -// - -/*! @class MusicDeviceBase */ -class MusicDeviceBase : public AUBase, public AUMIDIBase { -public: - /*! @ctor MusicDeviceBase */ - MusicDeviceBase( AudioComponentInstance inInstance, - UInt32 numInputs, - UInt32 numOutputs, - UInt32 numGroups = 0); - - - virtual OSStatus MIDIEvent( UInt32 inStatus, - UInt32 inData1, - UInt32 inData2, - UInt32 inOffsetSampleFrame) - { - return AUMIDIBase::MIDIEvent (inStatus, inData1, inData2, inOffsetSampleFrame); - } - - /*! @method SysEx */ - virtual OSStatus SysEx( const UInt8 * inData, - UInt32 inLength) - { - return AUMIDIBase::SysEx (inData, inLength); - } - - /*! @method GetPropertyInfo */ - virtual OSStatus GetPropertyInfo(AudioUnitPropertyID inID, - AudioUnitScope inScope, - AudioUnitElement inElement, - UInt32 & outDataSize, - Boolean & outWritable); - - /*! @method GetProperty */ - virtual OSStatus GetProperty( AudioUnitPropertyID inID, - AudioUnitScope inScope, - AudioUnitElement inElement, - void * outData); - - /*! @method SetProperty */ - virtual OSStatus SetProperty( AudioUnitPropertyID inID, - AudioUnitScope inScope, - AudioUnitElement inElement, - const void * inData, - UInt32 inDataSize); - - /*! @method HandleNoteOn */ - virtual OSStatus HandleNoteOn( UInt8 inChannel, - UInt8 inNoteNumber, - UInt8 inVelocity, - UInt32 inStartFrame); - - /*! @method HandleNoteOff */ - virtual OSStatus HandleNoteOff( UInt8 inChannel, - UInt8 inNoteNumber, - UInt8 inVelocity, - UInt32 inStartFrame); - - /*! @method GetInstrumentCount */ - virtual OSStatus GetInstrumentCount ( UInt32 &outInstCount) const; - -#if !CA_USE_AUDIO_PLUGIN_ONLY - // component dispatcher - /*! @method ComponentEntryDispatch */ - static OSStatus ComponentEntryDispatch( ComponentParameters * params, - MusicDeviceBase * This); -#endif -private: - OSStatus HandleStartNoteMessage (MusicDeviceInstrumentID inInstrument, MusicDeviceGroupID inGroupID, NoteInstanceID *outNoteInstanceID, UInt32 inOffsetSampleFrame, const MusicDeviceNoteParams *inParams); -}; - -#endif // __MusicDeviceBase_h__ diff --git a/src/CoreAudio/CoreAudioComponent/AUPublic/Utility/AUBaseHelper.cpp b/src/CoreAudio/CoreAudioComponent/AUPublic/Utility/AUBaseHelper.cpp deleted file mode 100644 index 231680713..000000000 --- a/src/CoreAudio/CoreAudioComponent/AUPublic/Utility/AUBaseHelper.cpp +++ /dev/null @@ -1,125 +0,0 @@ -/* - File: AUBaseHelper.cpp - Abstract: AUBaseHelper.h - Version: 1.1 - - Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple - Inc. ("Apple") in consideration of your agreement to the following - terms, and your use, installation, modification or redistribution of - this Apple software constitutes acceptance of these terms. If you do - not agree with these terms, please do not use, install, modify or - redistribute this Apple software. - - In consideration of your agreement to abide by the following terms, and - subject to these terms, Apple grants you a personal, non-exclusive - license, under Apple's copyrights in this original Apple software (the - "Apple Software"), to use, reproduce, modify and redistribute the Apple - Software, with or without modifications, in source and/or binary forms; - provided that if you redistribute the Apple Software in its entirety and - without modifications, you must retain this notice and the following - text and disclaimers in all such redistributions of the Apple Software. - Neither the name, trademarks, service marks or logos of Apple Inc. may - be used to endorse or promote products derived from the Apple Software - without specific prior written permission from Apple. Except as - expressly stated in this notice, no other rights or licenses, express or - implied, are granted by Apple herein, including but not limited to any - patent rights that may be infringed by your derivative works or by other - works in which the Apple Software may be incorporated. - - The Apple Software is provided by Apple on an "AS IS" basis. APPLE - MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION - THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS - FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND - OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS. - - IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL - OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, - MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED - AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), - STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE - POSSIBILITY OF SUCH DAMAGE. - - Copyright (C) 2014 Apple Inc. All Rights Reserved. - -*/ -#include "AUBaseHelper.h" - -#if !defined(__COREAUDIO_USE_FLAT_INCLUDES__) - #include -#else - #include -#endif - -OSStatus GetFileRefPath (CFDictionaryRef parent, CFStringRef frKey, CFStringRef * fPath) -{ - static CFStringRef kFRString = CFSTR (kAUPresetExternalFileRefs); - - const void* frVal = CFDictionaryGetValue(parent, kFRString); - if (!frVal) return kAudioUnitErr_InvalidPropertyValue; - - const void* frString = CFDictionaryGetValue ((CFDictionaryRef)frVal, frKey); - if (!frString) return kAudioUnitErr_InvalidPropertyValue; - - if (fPath) - *fPath = (CFStringRef)frString; - - return noErr; -} - -CFMutableDictionaryRef CreateFileRefDict (CFStringRef fKey, CFStringRef fPath, CFMutableDictionaryRef fileRefDict) -{ - if (!fileRefDict) - fileRefDict = CFDictionaryCreateMutable (NULL, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); - - CFDictionarySetValue (fileRefDict, fKey, fPath); - - return fileRefDict; -} - -#if TARGET_OS_MAC -// check if the URL can be accessed for reading/writing. Returns 0 if yes, or the error value. -int AccessURLAsset(const CFURLRef inURL, int mode) -{ - char path[PATH_MAX]; - if (CFURLGetFileSystemRepresentation(inURL, TRUE, (UInt8 *)path, PATH_MAX) == FALSE) - return kAudio_FileNotFoundError; - // check whether we have access - int ret = access(path, mode); -// syslog(LOG_CRIT, "access() error is %d for \"%s\".\n", ret, path); - if (ret == 0) return 0; - switch (errno) { - case EACCES: - case EPERM: - return -54; /*permission denied error*/ - case ENOENT: - case ENOTDIR: - case ELOOP: - return kAudio_FileNotFoundError; - default: - return errno; - } -} -#endif - -#if DEBUG -//_____________________________________________________________________________ -// -void PrintAUParamEvent (AudioUnitParameterEvent& event, FILE* f) -{ - bool isRamp = event.eventType == kParameterEvent_Ramped; - fprintf (f, "\tParamID=%ld,Scope=%ld,Element=%ld\n", (long)event.parameter, (long)event.scope, (long)event.element); - fprintf (f, "\tEvent Type:%s,", (isRamp ? "ramp" : "immediate")); - if (isRamp) - fprintf (f, "start=%ld,dur=%ld,startValue=%f,endValue=%f\n", - (long)event.eventValues.ramp.startBufferOffset, (long)event.eventValues.ramp.durationInFrames, - event.eventValues.ramp.startValue, event.eventValues.ramp.endValue); - else - fprintf (f, "start=%ld,value=%f\n", - (long)event.eventValues.immediate.bufferOffset, - event.eventValues.immediate.value); - fprintf (f, "- - - - - - - - - - - - - - - -\n"); -} -#endif - diff --git a/src/CoreAudio/CoreAudioComponent/AUPublic/Utility/AUBaseHelper.h b/src/CoreAudio/CoreAudioComponent/AUPublic/Utility/AUBaseHelper.h deleted file mode 100644 index 310a8df62..000000000 --- a/src/CoreAudio/CoreAudioComponent/AUPublic/Utility/AUBaseHelper.h +++ /dev/null @@ -1,75 +0,0 @@ -/* - File: AUBaseHelper.h - Abstract: Part of CoreAudio Utility Classes - Version: 1.1 - - Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple - Inc. ("Apple") in consideration of your agreement to the following - terms, and your use, installation, modification or redistribution of - this Apple software constitutes acceptance of these terms. If you do - not agree with these terms, please do not use, install, modify or - redistribute this Apple software. - - In consideration of your agreement to abide by the following terms, and - subject to these terms, Apple grants you a personal, non-exclusive - license, under Apple's copyrights in this original Apple software (the - "Apple Software"), to use, reproduce, modify and redistribute the Apple - Software, with or without modifications, in source and/or binary forms; - provided that if you redistribute the Apple Software in its entirety and - without modifications, you must retain this notice and the following - text and disclaimers in all such redistributions of the Apple Software. - Neither the name, trademarks, service marks or logos of Apple Inc. may - be used to endorse or promote products derived from the Apple Software - without specific prior written permission from Apple. Except as - expressly stated in this notice, no other rights or licenses, express or - implied, are granted by Apple herein, including but not limited to any - patent rights that may be infringed by your derivative works or by other - works in which the Apple Software may be incorporated. - - The Apple Software is provided by Apple on an "AS IS" basis. APPLE - MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION - THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS - FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND - OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS. - - IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL - OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, - MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED - AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), - STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE - POSSIBILITY OF SUCH DAMAGE. - - Copyright (C) 2014 Apple Inc. All Rights Reserved. - -*/ -#ifndef __AUBaseHelper_h__ -#define __AUBaseHelper_h__ - -#if !defined(__COREAUDIO_USE_FLAT_INCLUDES__) - #include - #include -#else - #include - #include -#endif - -#include "AUBase.h" - -// helpers for dealing with the file-references dictionary in an AUPreset -OSStatus GetFileRefPath (CFDictionaryRef parent, CFStringRef frKey, CFStringRef * fPath); - -// if fileRefDict is NULL, this call creates one -// if not NULL, then the key value is added to it -CFMutableDictionaryRef CreateFileRefDict (CFStringRef fKey, CFStringRef fPath, CFMutableDictionaryRef fileRefDict); - -int AccessURLAsset(const CFURLRef inURL, int mode); - -#if DEBUG - void PrintAUParamEvent (AudioUnitParameterEvent& event, FILE* f); -#endif - - - -#endif // __AUBaseHelper_h__ \ No newline at end of file diff --git a/src/CoreAudio/CoreAudioComponent/AUPublic/Utility/AUBuffer.cpp b/src/CoreAudio/CoreAudioComponent/AUPublic/Utility/AUBuffer.cpp deleted file mode 100644 index 36bb41fa5..000000000 --- a/src/CoreAudio/CoreAudioComponent/AUPublic/Utility/AUBuffer.cpp +++ /dev/null @@ -1,219 +0,0 @@ -/* - File: AUBuffer.cpp - Abstract: AUBuffer.h - Version: 1.1 - - Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple - Inc. ("Apple") in consideration of your agreement to the following - terms, and your use, installation, modification or redistribution of - this Apple software constitutes acceptance of these terms. If you do - not agree with these terms, please do not use, install, modify or - redistribute this Apple software. - - In consideration of your agreement to abide by the following terms, and - subject to these terms, Apple grants you a personal, non-exclusive - license, under Apple's copyrights in this original Apple software (the - "Apple Software"), to use, reproduce, modify and redistribute the Apple - Software, with or without modifications, in source and/or binary forms; - provided that if you redistribute the Apple Software in its entirety and - without modifications, you must retain this notice and the following - text and disclaimers in all such redistributions of the Apple Software. - Neither the name, trademarks, service marks or logos of Apple Inc. may - be used to endorse or promote products derived from the Apple Software - without specific prior written permission from Apple. Except as - expressly stated in this notice, no other rights or licenses, express or - implied, are granted by Apple herein, including but not limited to any - patent rights that may be infringed by your derivative works or by other - works in which the Apple Software may be incorporated. - - The Apple Software is provided by Apple on an "AS IS" basis. APPLE - MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION - THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS - FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND - OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS. - - IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL - OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, - MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED - AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), - STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE - POSSIBILITY OF SUCH DAMAGE. - - Copyright (C) 2014 Apple Inc. All Rights Reserved. - -*/ -#include "AUBuffer.h" -#include - -AUBufferList::~AUBufferList() -{ - Deallocate(); - if (mPtrs) - free(mPtrs); -} - -// a * b + c -static UInt32 SafeMultiplyAddUInt32(UInt32 a, UInt32 b, UInt32 c) -{ - if (a == 0 || b == 0) return c; // prevent zero divide - - if (a > (0xFFFFFFFF - c) / b) - throw std::bad_alloc(); - - return a * b + c; -} - -void AUBufferList::Allocate(const CAStreamBasicDescription &format, UInt32 nFrames) -{ - UInt32 nStreams; - if (format.IsInterleaved()) { - nStreams = 1; - } else { - nStreams = format.mChannelsPerFrame; - } - - // careful -- the I/O thread could be running! - if (nStreams > mAllocatedStreams) { - size_t theHeaderSize = sizeof(AudioBufferList) - sizeof(AudioBuffer); - mPtrs = (AudioBufferList *)CA_realloc(mPtrs, - SafeMultiplyAddUInt32(nStreams, sizeof(AudioBuffer), theHeaderSize)); - mAllocatedStreams = nStreams; - } - UInt32 bytesPerStream = SafeMultiplyAddUInt32(nFrames, format.mBytesPerFrame, 0xF) & ~0xF; - UInt32 nBytes = SafeMultiplyAddUInt32(nStreams, bytesPerStream, 0); - if (nBytes > mAllocatedBytes) { - if (mExternalMemory) { - mExternalMemory = false; - mMemory = NULL; - } - mMemory = (Byte *)CA_realloc(mMemory, nBytes); - mAllocatedBytes = nBytes; - } - mAllocatedFrames = nFrames; - mPtrState = kPtrsInvalid; -} - -void AUBufferList::Deallocate() -{ - mAllocatedStreams = 0; - mAllocatedFrames = 0; - mAllocatedBytes = 0; -// this causes a world of hurt if someone upstream disconnects during I/O (SysSoundGraph) -/* if (mPtrs) { - printf("deallocating bufferlist %08X\n", int(mPtrs)); - free(mPtrs); - mPtrs = NULL; - } */ - if (mMemory) { - if (mExternalMemory) - mExternalMemory = false; - else - free(mMemory); - mMemory = NULL; - } - mPtrState = kPtrsInvalid; -} - -AudioBufferList & AUBufferList::PrepareBuffer(const CAStreamBasicDescription &format, UInt32 nFrames) -{ - if (nFrames > mAllocatedFrames) - COMPONENT_THROW(kAudioUnitErr_TooManyFramesToProcess); - - UInt32 nStreams; - UInt32 channelsPerStream; - if (format.IsInterleaved()) { - nStreams = 1; - channelsPerStream = format.mChannelsPerFrame; - } else { - nStreams = format.mChannelsPerFrame; - channelsPerStream = 1; - if (nStreams > mAllocatedStreams) - COMPONENT_THROW(kAudioUnitErr_FormatNotSupported); - } - - AudioBufferList *abl = mPtrs; - abl->mNumberBuffers = nStreams; - AudioBuffer *buf = abl->mBuffers; - Byte *mem = mMemory; - UInt32 streamInterval = (mAllocatedFrames * format.mBytesPerFrame + 0xF) & ~0xF; - UInt32 bytesPerBuffer = nFrames * format.mBytesPerFrame; - for ( ; nStreams--; ++buf) { - buf->mNumberChannels = channelsPerStream; - buf->mData = mem; - buf->mDataByteSize = bytesPerBuffer; - mem += streamInterval; - } - if (UInt32(mem - mMemory) > mAllocatedBytes) - COMPONENT_THROW(kAudioUnitErr_TooManyFramesToProcess); - mPtrState = kPtrsToMyMemory; - return *mPtrs; -} - -AudioBufferList & AUBufferList::PrepareNullBuffer(const CAStreamBasicDescription &format, UInt32 nFrames) -{ - UInt32 nStreams; - UInt32 channelsPerStream; - if (format.IsInterleaved()) { - nStreams = 1; - channelsPerStream = format.mChannelsPerFrame; - } else { - nStreams = format.mChannelsPerFrame; - channelsPerStream = 1; - if (nStreams > mAllocatedStreams) - COMPONENT_THROW(kAudioUnitErr_FormatNotSupported); - } - AudioBufferList *abl = mPtrs; - abl->mNumberBuffers = nStreams; - AudioBuffer *buf = abl->mBuffers; - UInt32 bytesPerBuffer = nFrames * format.mBytesPerFrame; - for ( ; nStreams--; ++buf) { - buf->mNumberChannels = channelsPerStream; - buf->mData = NULL; - buf->mDataByteSize = bytesPerBuffer; - } - mPtrState = kPtrsToExternalMemory; - return *mPtrs; -} - -// this should NOT be called while I/O is in process -void AUBufferList::UseExternalBuffer(const CAStreamBasicDescription &format, const AudioUnitExternalBuffer &buf) -{ - UInt32 alignedSize = buf.size & ~0xF; - if (mMemory != NULL && alignedSize >= mAllocatedBytes) { - // don't accept the buffer if we already have one and it's big enough - // if we don't already have one, we don't need one - Byte *oldMemory = mMemory; - mMemory = buf.buffer; - mAllocatedBytes = alignedSize; - // from Allocate(): nBytes = nStreams * nFrames * format.mBytesPerFrame; - // thus: nFrames = nBytes / (nStreams * format.mBytesPerFrame) - mAllocatedFrames = mAllocatedBytes / (format.NumberChannelStreams() * format.mBytesPerFrame); - mExternalMemory = true; - free(oldMemory); - } -} - -#if DEBUG -void AUBufferList::PrintBuffer(const char *label, int subscript, const AudioBufferList &abl, UInt32 nFrames, bool asFloats) -{ - printf(" %s [%d] 0x%08lX:\n", label, subscript, long(&abl)); - const AudioBuffer *buf = abl.mBuffers; - for (UInt32 i = 0; i < abl.mNumberBuffers; ++buf, ++i) { - printf(" [%2d] %5dbytes %dch @ %p: ", (int)i, (int)buf->mDataByteSize, (int)buf->mNumberChannels, buf->mData); - if (buf->mData != NULL) { - UInt32 nSamples = nFrames * buf->mNumberChannels; - for (UInt32 j = 0; j < nSamples; ++j) { - if (nSamples > 16 && (j % 16) == 0) - printf("\n\t"); - if (asFloats) - printf(" %6.3f", ((float *)buf->mData)[j]); - else - printf(" %08X", (unsigned)((UInt32 *)buf->mData)[j]); - } - } - printf("\n"); - } -} -#endif diff --git a/src/CoreAudio/CoreAudioComponent/AUPublic/Utility/AUBuffer.h b/src/CoreAudio/CoreAudioComponent/AUPublic/Utility/AUBuffer.h deleted file mode 100644 index 64ea4c397..000000000 --- a/src/CoreAudio/CoreAudioComponent/AUPublic/Utility/AUBuffer.h +++ /dev/null @@ -1,267 +0,0 @@ -/* - File: AUBuffer.h - Abstract: Part of CoreAudio Utility Classes - Version: 1.1 - - Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple - Inc. ("Apple") in consideration of your agreement to the following - terms, and your use, installation, modification or redistribution of - this Apple software constitutes acceptance of these terms. If you do - not agree with these terms, please do not use, install, modify or - redistribute this Apple software. - - In consideration of your agreement to abide by the following terms, and - subject to these terms, Apple grants you a personal, non-exclusive - license, under Apple's copyrights in this original Apple software (the - "Apple Software"), to use, reproduce, modify and redistribute the Apple - Software, with or without modifications, in source and/or binary forms; - provided that if you redistribute the Apple Software in its entirety and - without modifications, you must retain this notice and the following - text and disclaimers in all such redistributions of the Apple Software. - Neither the name, trademarks, service marks or logos of Apple Inc. may - be used to endorse or promote products derived from the Apple Software - without specific prior written permission from Apple. Except as - expressly stated in this notice, no other rights or licenses, express or - implied, are granted by Apple herein, including but not limited to any - patent rights that may be infringed by your derivative works or by other - works in which the Apple Software may be incorporated. - - The Apple Software is provided by Apple on an "AS IS" basis. APPLE - MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION - THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS - FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND - OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS. - - IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL - OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, - MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED - AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), - STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE - POSSIBILITY OF SUCH DAMAGE. - - Copyright (C) 2014 Apple Inc. All Rights Reserved. - -*/ -#ifndef __AUBuffer_h__ -#define __AUBuffer_h__ - -#include -#if !defined(__COREAUDIO_USE_FLAT_INCLUDES__) - #include -#else - #include -#endif - -#include -#include "CAStreamBasicDescription.h" -#include "CAAutoDisposer.h" -#include "CADebugMacros.h" - -// make this usable outside the stricter context of AudiUnits -#ifndef COMPONENT_THROW - #define COMPONENT_THROW(err) \ - do { DebugMessage(#err); throw static_cast(err); } while (0) -#endif - - - /*! @class AUBufferList */ -class AUBufferList { - enum EPtrState { - kPtrsInvalid, - kPtrsToMyMemory, - kPtrsToExternalMemory - }; -public: - /*! @ctor AUBufferList */ - AUBufferList() : mPtrState(kPtrsInvalid), mExternalMemory(false), mPtrs(NULL), mMemory(NULL), - mAllocatedStreams(0), mAllocatedFrames(0), mAllocatedBytes(0) { } - /*! @dtor ~AUBufferList */ - ~AUBufferList(); - - /*! @method PrepareBuffer */ - AudioBufferList & PrepareBuffer(const CAStreamBasicDescription &format, UInt32 nFrames); - /*! @method PrepareNullBuffer */ - AudioBufferList & PrepareNullBuffer(const CAStreamBasicDescription &format, UInt32 nFrames); - - /*! @method SetBufferList */ - AudioBufferList & SetBufferList(const AudioBufferList &abl) { - if (mAllocatedStreams < abl.mNumberBuffers) - COMPONENT_THROW(-1); - mPtrState = kPtrsToExternalMemory; - memcpy(mPtrs, &abl, (char *)&abl.mBuffers[abl.mNumberBuffers] - (char *)&abl); - return *mPtrs; - } - - /*! @method SetBuffer */ - void SetBuffer(UInt32 index, const AudioBuffer &ab) { - if (mPtrState == kPtrsInvalid || index >= mPtrs->mNumberBuffers) - COMPONENT_THROW(-1); - mPtrState = kPtrsToExternalMemory; - mPtrs->mBuffers[index] = ab; - } - - /*! @method InvalidateBufferList */ - void InvalidateBufferList() { mPtrState = kPtrsInvalid; } - - /*! @method GetBufferList */ - AudioBufferList & GetBufferList() const { - if (mPtrState == kPtrsInvalid) - COMPONENT_THROW(-1); - return *mPtrs; - } - - /*! @method CopyBufferListTo */ - void CopyBufferListTo(AudioBufferList &abl) const { - if (mPtrState == kPtrsInvalid) - COMPONENT_THROW(-1); - memcpy(&abl, mPtrs, (char *)&abl.mBuffers[abl.mNumberBuffers] - (char *)&abl); - } - - /*! @method CopyBufferContentsTo */ - void CopyBufferContentsTo(AudioBufferList &abl) const { - if (mPtrState == kPtrsInvalid) - COMPONENT_THROW(-1); - const AudioBuffer *srcbuf = mPtrs->mBuffers; - AudioBuffer *destbuf = abl.mBuffers; - - for (UInt32 i = 0; i < abl.mNumberBuffers; ++i, ++srcbuf, ++destbuf) { - if (i >= mPtrs->mNumberBuffers) // duplicate last source to additional outputs [4341137] - --srcbuf; - if (destbuf->mData != srcbuf->mData) - memmove(destbuf->mData, srcbuf->mData, srcbuf->mDataByteSize); - destbuf->mDataByteSize = srcbuf->mDataByteSize; - } - } - - /*! @method Allocate */ - void Allocate(const CAStreamBasicDescription &format, UInt32 nFrames); - /*! @method Deallocate */ - void Deallocate(); - - /*! @method UseExternalBuffer */ - void UseExternalBuffer(const CAStreamBasicDescription &format, const AudioUnitExternalBuffer &buf); - - // AudioBufferList utilities - /*! @method ZeroBuffer */ - static void ZeroBuffer(AudioBufferList &abl) { - AudioBuffer *buf = abl.mBuffers; - for (UInt32 i = abl.mNumberBuffers ; i--; ++buf) - memset(buf->mData, 0, buf->mDataByteSize); - } -#if DEBUG - /*! @method PrintBuffer */ - static void PrintBuffer(const char *label, int subscript, const AudioBufferList &abl, UInt32 nFrames = 8, bool asFloats = true); -#endif - - /*! @method GetAllocatedFrames */ - UInt32 GetAllocatedFrames() const { return mAllocatedFrames; } - -private: - /*! @ctor AUBufferList */ - AUBufferList(AUBufferList &) { } // prohibit copy constructor - - /*! @var mPtrState */ - EPtrState mPtrState; - /*! @var mExternalMemory */ - bool mExternalMemory; - /*! @var mPtrs */ - AudioBufferList * mPtrs; - /*! @var mMemory */ - Byte * mMemory; - /*! @var mAllocatedStreams */ - UInt32 mAllocatedStreams; - /*! @var mAllocatedFrames */ - UInt32 mAllocatedFrames; - /*! @var mAllocatedBytes */ - UInt32 mAllocatedBytes; -}; - - -// Allocates an array of samples (type T), to be optimally aligned for the processor - /*! @class TAUBuffer */ -template -class TAUBuffer { -public: - enum { - kAlignInterval = 0x10, - kAlignMask = kAlignInterval - 1 - }; - - /*! @ctor TAUBuffer.0 */ - TAUBuffer() : mMemObject(NULL), mAlignedBuffer(NULL), mBufferSizeBytes(0) - { - } - - /*! @ctor TAUBuffer.1 */ - TAUBuffer(UInt32 numElems, UInt32 numChannels) : mMemObject(NULL), mAlignedBuffer(NULL), - mBufferSizeBytes(0) - { - Allocate(numElems, numChannels); - } - - /*! @dtor ~TAUBuffer */ - ~TAUBuffer() - { - Deallocate(); - } - - /*! @method Allocate */ - void Allocate(UInt32 numElems) // can also re-allocate - { - UInt32 reqSize = numElems * sizeof(T); - - if (mMemObject != NULL && reqSize == mBufferSizeBytes) - return; // already allocated - - mBufferSizeBytes = reqSize; - mMemObject = CA_realloc(mMemObject, reqSize); - UInt32 misalign = (uintptr_t)mMemObject & kAlignMask; - if (misalign) { - mMemObject = CA_realloc(mMemObject, reqSize + kAlignMask); - mAlignedBuffer = (T *)((char *)mMemObject + kAlignInterval - misalign); - } else - mAlignedBuffer = (T *)mMemObject; - } - - /*! @method Deallocate */ - void Deallocate() - { - if (mMemObject == NULL) return; // so this method has no effect if we're using - // an external buffer - - free(mMemObject); - mMemObject = NULL; - mAlignedBuffer = NULL; - mBufferSizeBytes = 0; - } - - /*! @method AllocateClear */ - void AllocateClear(UInt32 numElems) // can also re-allocate - { - Allocate(numElems); - Clear(); - } - - /*! @method Clear */ - void Clear() - { - memset(mAlignedBuffer, 0, mBufferSizeBytes); - } - - // accessors - - /*! @method operator T *()@ */ - operator T *() { return mAlignedBuffer; } - -private: - /*! @var mMemObject */ - void * mMemObject; // null when using an external buffer - /*! @var mAlignedBuffer */ - T * mAlignedBuffer; // always valid once allocated - /*! @var mBufferSizeBytes */ - UInt32 mBufferSizeBytes; -}; - -#endif // __AUBuffer_h__ diff --git a/src/CoreAudio/CoreAudioComponent/AUPublic/Utility/AUMIDIDefs.h b/src/CoreAudio/CoreAudioComponent/AUPublic/Utility/AUMIDIDefs.h deleted file mode 100644 index e83c0e7e8..000000000 --- a/src/CoreAudio/CoreAudioComponent/AUPublic/Utility/AUMIDIDefs.h +++ /dev/null @@ -1,138 +0,0 @@ -/* - File: AUMIDIDefs.h - Abstract: Part of CoreAudio Utility Classes - Version: 1.1 - - Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple - Inc. ("Apple") in consideration of your agreement to the following - terms, and your use, installation, modification or redistribution of - this Apple software constitutes acceptance of these terms. If you do - not agree with these terms, please do not use, install, modify or - redistribute this Apple software. - - In consideration of your agreement to abide by the following terms, and - subject to these terms, Apple grants you a personal, non-exclusive - license, under Apple's copyrights in this original Apple software (the - "Apple Software"), to use, reproduce, modify and redistribute the Apple - Software, with or without modifications, in source and/or binary forms; - provided that if you redistribute the Apple Software in its entirety and - without modifications, you must retain this notice and the following - text and disclaimers in all such redistributions of the Apple Software. - Neither the name, trademarks, service marks or logos of Apple Inc. may - be used to endorse or promote products derived from the Apple Software - without specific prior written permission from Apple. Except as - expressly stated in this notice, no other rights or licenses, express or - implied, are granted by Apple herein, including but not limited to any - patent rights that may be infringed by your derivative works or by other - works in which the Apple Software may be incorporated. - - The Apple Software is provided by Apple on an "AS IS" basis. APPLE - MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION - THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS - FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND - OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS. - - IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL - OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, - MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED - AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), - STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE - POSSIBILITY OF SUCH DAMAGE. - - Copyright (C) 2014 Apple Inc. All Rights Reserved. - -*/ -#ifndef __AUMIDIDefs_h__ -#define __AUMIDIDefs_h__ - -#if !defined(__TMidiMessage) /* DAS HACK */ -enum -{ - kMidiMessage_NoteOff = 0x80, - kMidiMessage_NoteOn = 0x90, - kMidiMessage_PolyPressure = 0xA0, - kMidiMessage_ControlChange = 0xB0, - kMidiMessage_ProgramChange = 0xC0, - kMidiMessage_ChannelPressure = 0xD0, - kMidiMessage_PitchWheel = 0xE0, - kMidiMessage_SysEx = 0xF0, - kMidiMessage_SysEx_End = 0xF7, - kMidiMessage_MetaEvent = 0xFF -}; -#endif - -enum -{ - kMidiController_BankSelect = 0, - kMidiController_ModWheel = 1, - kMidiController_Breath = 2, - kMidiController_Foot = 4, - kMidiController_PortamentoTime = 5, - kMidiController_DataEntry = 6, - kMidiController_Volume = 7, - kMidiController_Balance = 8, - kMidiController_Pan = 10, - kMidiController_Expression = 11, - - // these controls have a (0-63) == off, (64-127) == on - kMidiController_Sustain = 64, //hold1 - kMidiController_Portamento = 65, - kMidiController_Sostenuto = 66, - kMidiController_Soft = 67, - kMidiController_LegatoPedal = 68, - kMidiController_Hold2Pedal = 69, - kMidiController_FilterResonance = 71, - kMidiController_ReleaseTime = 72, - kMidiController_AttackTime = 73, - kMidiController_Brightness = 74, - kMidiController_DecayTime = 75, - kMidiController_VibratoRate = 76, - kMidiController_VibratoDepth = 77, - kMidiController_VibratoDelay = 78, - - // these controls have a 0-127 range and in MIDI they have no LSB (so fractional values are lost in MIDI) - kMidiController_ReverbLevel = 91, - kMidiController_ChorusLevel = 93, - - kMidiController_RPN_LSB = 100, - kMidiController_RPN_MSB = 101, - - kMidiController_AllSoundOff = 120, - kMidiController_ResetAllControllers = 121, - kMidiController_AllNotesOff = 123, - kMidiController_OmniModeOff = 124, - kMidiController_OmniModeOn = 125, - kMidiController_MonoModeOn = 126, - kMidiController_MonoModeOff = 127 -}; - -// RPN values -enum -{ - kMidiControllerValue_RPNPitchBendSensitivity = 0, - kMidiControllerValue_RPNChannelFineTuning = 1, - kMidiControllerValue_RPNChannelCoarseTuning = 2, - kMidiControllerValue_RPNModDepthRange = 5, - kMidiControllerValue_RPNNull = 0x3fff //! 0x7f/0x7f -}; - -// GM2 Sound Bank Constants -enum -{ - kGM2MelodicBank = 0x7900, - kGM2PercussionBank = 0x7800, - kGSPercussionBank = 0x7f00, - kXGSFXBank = 0x7E00, - kXGPercussionBank = kGSPercussionBank, - kBankMSBMask = 0xff00 -}; - -enum -{ - kMSBController_MidPoint = 0x40 -}; - -#endif // __AUMIDIDefs_h__ - diff --git a/src/CoreAudio/CoreAudioComponent/AUPublic/Utility/AUSilentTimeout.h b/src/CoreAudio/CoreAudioComponent/AUPublic/Utility/AUSilentTimeout.h deleted file mode 100644 index 9fbd3e1f2..000000000 --- a/src/CoreAudio/CoreAudioComponent/AUPublic/Utility/AUSilentTimeout.h +++ /dev/null @@ -1,93 +0,0 @@ -/* - File: AUSilentTimeout.h - Abstract: Part of CoreAudio Utility Classes - Version: 1.1 - - Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple - Inc. ("Apple") in consideration of your agreement to the following - terms, and your use, installation, modification or redistribution of - this Apple software constitutes acceptance of these terms. If you do - not agree with these terms, please do not use, install, modify or - redistribute this Apple software. - - In consideration of your agreement to abide by the following terms, and - subject to these terms, Apple grants you a personal, non-exclusive - license, under Apple's copyrights in this original Apple software (the - "Apple Software"), to use, reproduce, modify and redistribute the Apple - Software, with or without modifications, in source and/or binary forms; - provided that if you redistribute the Apple Software in its entirety and - without modifications, you must retain this notice and the following - text and disclaimers in all such redistributions of the Apple Software. - Neither the name, trademarks, service marks or logos of Apple Inc. may - be used to endorse or promote products derived from the Apple Software - without specific prior written permission from Apple. Except as - expressly stated in this notice, no other rights or licenses, express or - implied, are granted by Apple herein, including but not limited to any - patent rights that may be infringed by your derivative works or by other - works in which the Apple Software may be incorporated. - - The Apple Software is provided by Apple on an "AS IS" basis. APPLE - MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION - THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS - FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND - OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS. - - IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL - OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, - MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED - AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), - STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE - POSSIBILITY OF SUCH DAMAGE. - - Copyright (C) 2014 Apple Inc. All Rights Reserved. - -*/ -#ifndef __AUSilentTimeout -#define __AUSilentTimeout - -class AUSilentTimeout -{ -public: - AUSilentTimeout() - : mTimeoutCounter(0), - mResetTimer(true) - {}; - - void Process(UInt32 inFramesToProcess, UInt32 inTimeoutLimit, bool &ioSilence ) - { - if(ioSilence ) - { - if(mResetTimer ) - { - mTimeoutCounter = inTimeoutLimit; - mResetTimer = false; - } - - if(mTimeoutCounter > 0 ) - { - mTimeoutCounter -= inFramesToProcess; - ioSilence = false; - } - } - else - { - // signal to reset the next time we receive silence - mResetTimer = true; - } - } - - void Reset() - { - mResetTimer = true; - }; - - - -private: - SInt32 mTimeoutCounter; - bool mResetTimer; -}; - -#endif // __AUSilentTimeout diff --git a/src/CoreAudio/CoreAudioComponent/PublicUtility b/src/CoreAudio/CoreAudioComponent/PublicUtility new file mode 120000 index 000000000..4b70d76ff --- /dev/null +++ b/src/CoreAudio/CoreAudioComponent/PublicUtility @@ -0,0 +1 @@ +../CoreAudioUtilityClasses/CoreAudio/PublicUtility \ No newline at end of file diff --git a/src/CoreAudio/CoreAudioComponent/PublicUtility/CAAUMIDIMap.cpp b/src/CoreAudio/CoreAudioComponent/PublicUtility/CAAUMIDIMap.cpp deleted file mode 100644 index 4e72b2285..000000000 --- a/src/CoreAudio/CoreAudioComponent/PublicUtility/CAAUMIDIMap.cpp +++ /dev/null @@ -1,227 +0,0 @@ -/* - File: CAAUMIDIMap.cpp - Abstract: CAAUMIDIMap.h - Version: 1.1 - - Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple - Inc. ("Apple") in consideration of your agreement to the following - terms, and your use, installation, modification or redistribution of - this Apple software constitutes acceptance of these terms. If you do - not agree with these terms, please do not use, install, modify or - redistribute this Apple software. - - In consideration of your agreement to abide by the following terms, and - subject to these terms, Apple grants you a personal, non-exclusive - license, under Apple's copyrights in this original Apple software (the - "Apple Software"), to use, reproduce, modify and redistribute the Apple - Software, with or without modifications, in source and/or binary forms; - provided that if you redistribute the Apple Software in its entirety and - without modifications, you must retain this notice and the following - text and disclaimers in all such redistributions of the Apple Software. - Neither the name, trademarks, service marks or logos of Apple Inc. may - be used to endorse or promote products derived from the Apple Software - without specific prior written permission from Apple. Except as - expressly stated in this notice, no other rights or licenses, express or - implied, are granted by Apple herein, including but not limited to any - patent rights that may be infringed by your derivative works or by other - works in which the Apple Software may be incorporated. - - The Apple Software is provided by Apple on an "AS IS" basis. APPLE - MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION - THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS - FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND - OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS. - - IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL - OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, - MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED - AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), - STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE - POSSIBILITY OF SUCH DAMAGE. - - Copyright (C) 2014 Apple Inc. All Rights Reserved. - -*/ -#include "CAAUMIDIMap.h" -#include - -struct AllMidiTransformers -{ - MIDILinearTransformer linearTrans; - MIDILogTransformer logTrans; - MIDIExpTransformer expTrans; - MIDISqrtTransformer sqrtTrans; - MIDISquareTransformer squareTrans; - MIDICubeRtTransformer cubeRtTrans; - MIDICubeTransformer cubeTrans; -}; - -AllMidiTransformers* gAllMidiTransformers = NULL; - -#if TARGET_OS_MAC -static pthread_once_t sOnce = PTHREAD_ONCE_INIT; - -static void InitAllMidiTransformers() -{ - gAllMidiTransformers = new AllMidiTransformers(); -} - -static void CheckInitAllMidiTransformers() -{ - pthread_once(&sOnce, InitAllMidiTransformers); -} -#endif - -MIDIValueTransformer * CAAUMIDIMap::GetTransformer (UInt32 inFlags) -{ -#if TARGET_OS_MAC - if (gAllMidiTransformers == NULL) - CheckInitAllMidiTransformers(); -#else - if (gAllMidiTransformers == NULL) - gAllMidiTransformers = new AllMidiTransformers(); -#endif - - if (AudioUnitDisplayTypeIsLogarithmic(inFlags)) - return &gAllMidiTransformers->logTrans; - else if (AudioUnitDisplayTypeIsExponential(inFlags)) - return &gAllMidiTransformers->expTrans; - else if (AudioUnitDisplayTypeIsSquareRoot(inFlags)) - return &gAllMidiTransformers->sqrtTrans; - else if (AudioUnitDisplayTypeIsSquared(inFlags)) - return &gAllMidiTransformers->squareTrans; - else if (AudioUnitDisplayTypeIsCubed(inFlags)) - return &gAllMidiTransformers->cubeTrans; - else if (AudioUnitDisplayTypeIsCubeRoot(inFlags)) - return &gAllMidiTransformers->cubeRtTrans; - else - return &gAllMidiTransformers->linearTrans; -} - -// The CALLER of this method must ensure that the status byte's MIDI Command matches!!! -bool CAAUMIDIMap::MIDI_Matches (UInt8 inChannel, UInt8 inData1, UInt8 inData2, Float32 &outLinear) const -{ - // see if the channels match first - SInt8 chan = Channel(); - // channel matches (if chan is less than zero, "Any Channel" flag is set) - if (chan >= 0 && chan != inChannel) - return false; - - // match the special cases first - if (IsKeyEvent()) { - // we're using this key event as an on/off type switch - if (IsBipolar()) { - if (IsKeyPressure()){ - if (IsBipolar_OnValue()) { - if (inData2 > 63) { - outLinear = 1; - return true; - } - } else { - if (inData2 < 64) { - outLinear = 0; - return true; - } - } - return false; - } - else { - if (IsBipolar_OnValue()) { - if (inData1 > 63) { - outLinear = 1; - return true; - } - } else { - if (inData1 < 64) { - outLinear = 0; - return true; - } - } - return false; - } - } - if (IsAnyNote()) { -// not quite sure how to interpret this... - if (IsKeyPressure()) - outLinear = inData2 / 127.0; - else - outLinear = inData1 / 127.0; - return true; - } - if (mData1 == inData1) { - if (IsKeyPressure()) - outLinear = inData2 / 127.0; - else - outLinear = 1; - return true; - } - return false; - } - else if (IsControlChange()) { - // controller ID matches - if (mData1 == inData1) { - if (IsBipolar()) { - if (IsBipolar_OnValue()) { - if (inData2 > 63) { - outLinear = 1; - return true; - } - } else { - if (inData2 < 64) { - outLinear = 0; - return true; - } - } - return false; - } - //printf("this in midi matches %X with ", this); - outLinear = inData2 / 127.; - return true; - } - return false; - } - - // this just matches on the patch change value itself... - if (IsPatchChange()) { - if (mData1 == inData1) { - outLinear = 1; - return true; - } - return false; - } - - // finally, for the other two, just check the bi-polar matching conditions - // pitch bend and after touch - if (IsBipolar()) { - if (IsBipolar_OnValue()) { - if (inData1 > 63) { - outLinear = 1; - return true; - } - } else { - if (inData1 < 64) { - outLinear = 0; - return true; - } - } - return false; - } - - if (IsPitchBend()) { - UInt16 value = (inData2 << 7) | inData1; - outLinear = value / 16383.; - } - else if (IsChannelPressure()) { - outLinear = inData1 / 127.0; - } - - return true; -} - - -void CAAUMIDIMap::Print () const -{ - printf ("CAAUMIDIMap:%p, (%u/%u), mParamID %d, IsValid:%c, Status:0x%X, mData1 %d, Flags:0x%X\n", this, (unsigned int)mScope, (unsigned int)mElement, (int)mParameterID, (IsValid() ? 'T' : 'F'), mStatus, mData1, (int)mFlags); -} diff --git a/src/CoreAudio/CoreAudioComponent/PublicUtility/CAAUMIDIMap.h b/src/CoreAudio/CoreAudioComponent/PublicUtility/CAAUMIDIMap.h deleted file mode 100644 index a53fdf70d..000000000 --- a/src/CoreAudio/CoreAudioComponent/PublicUtility/CAAUMIDIMap.h +++ /dev/null @@ -1,541 +0,0 @@ -/* - File: CAAUMIDIMap.h - Abstract: Part of CoreAudio Utility Classes - Version: 1.1 - - Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple - Inc. ("Apple") in consideration of your agreement to the following - terms, and your use, installation, modification or redistribution of - this Apple software constitutes acceptance of these terms. If you do - not agree with these terms, please do not use, install, modify or - redistribute this Apple software. - - In consideration of your agreement to abide by the following terms, and - subject to these terms, Apple grants you a personal, non-exclusive - license, under Apple's copyrights in this original Apple software (the - "Apple Software"), to use, reproduce, modify and redistribute the Apple - Software, with or without modifications, in source and/or binary forms; - provided that if you redistribute the Apple Software in its entirety and - without modifications, you must retain this notice and the following - text and disclaimers in all such redistributions of the Apple Software. - Neither the name, trademarks, service marks or logos of Apple Inc. may - be used to endorse or promote products derived from the Apple Software - without specific prior written permission from Apple. Except as - expressly stated in this notice, no other rights or licenses, express or - implied, are granted by Apple herein, including but not limited to any - patent rights that may be infringed by your derivative works or by other - works in which the Apple Software may be incorporated. - - The Apple Software is provided by Apple on an "AS IS" basis. APPLE - MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION - THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS - FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND - OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS. - - IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL - OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, - MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED - AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), - STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE - POSSIBILITY OF SUCH DAMAGE. - - Copyright (C) 2014 Apple Inc. All Rights Reserved. - -*/ -#ifndef __CAAUMIDIMap_h_ -#define __CAAUMIDIMap_h_ - -#include -#include - -/* -enum { - kAUParameterMIDIMapping_AnyChannelFlag = (1L << 0), - // If this flag is set and mStatus is a MIDI channel message, then the MIDI channel number - // in the status byte is ignored; the mapping is from the specified MIDI message on ANY channel. - - kAUParameterMIDIMapping_AnyNoteFlag = (1L << 1), - // If this flag is set and mStatus is a Note On, Note Off, or Polyphonic Pressure message, - // the message's note number is ignored; the mapping is from ANY note number. - - kAUParameterMIDIMapping_SubRange = (1L << 2), - // set this flag if the midi control should map only to a sub-range of the parameter's value - // then specify that range in the mSubRangeMin and mSubRangeMax members - - kAUParameterMIDIMapping_Toggle = (1L << 3), - // this is only useful for boolean typed parameters. When set, it means that the parameter's - // value should be toggled (if true, become false and vice versa) when the represented MIDI message - // is received - - kAUParameterMIDIMapping_Bipolar = (1L << 4), - // this can be set to when mapping a MIDI Controller to indicate that the parameter (typically a boolean - // style parameter) will only have its value changed to either the on or off state of a MIDI controller message - // (0 < 64 is off, 64 < 127 is on) such as the sustain pedal. The seeting of the next flag - // (kAUParameterMIDIMapping_Bipolar_On) determine whether the parameter is mapped to the on or off - // state of the controller - kAUParameterMIDIMapping_Bipolar_On = (1L << 5) - // only a valid flag if kAUParameterMIDIMapping_Bipolar is set -}; - -// The reserved fields here are being used to reserve space (as well as align to 64 bit size) for future use -// When/If these fields are used, the names of the fields will be changed to reflect their functionality -// so, apps should NOT refer to these reserved fields directly by name -typedef struct AUParameterMIDIMapping -{ - AudioUnitScope mScope; - AudioUnitElement mElement; - AudioUnitParameterID mParameterID; - UInt32 mFlags; - Float32 mSubRangeMin; - Float32 mSubRangeMax; - UInt8 mStatus; - UInt8 mData1; - UInt8 reserved1; // MUST be set to zero - UInt8 reserved2; // MUST be set to zero - UInt32 reserved3; // MUST be set to zero -} AUParameterMIDIMapping; -*/ - -/* -Parameter To MIDI Mapping Properties -These properties are used to: -Describe a current set of mappings between MIDI messages and Parameter value setting -Create a mapping between a parameter and a MIDI message through either: -- explicitly adding (or removing) the mapping -- telling the AU to hot-map the next MIDI message to a specified Parameter - The same MIDI Message can map to one or more parameters - One Parameter can be mapped from multiple MIDI messages - - In general usage, these properties only apply to AU's that implement the MIDI API - AU Instruments (type=='aumu') and Music Effects (type == 'aumf') - - These properties are used in the Global scope. The scope and element members of the structure describe - the scope and element of the parameter. In all usages, mScope, mElement and mParameterID must be - correctly specified. - - - * The AUParameterMIDIMapping Structure - - Command mStatus mData1 - Note Off 0x8n Note Num - Note On 0x9n Note Num - Key Pressure 0xAn Note Num - Control Change 0xBn ControllerID - Patch Change 0xCn Patch Num - Channel Pressure DxDn 0 (Unused) - Pitch Bend 0xEn 0 (Unused) - - (where n is 0-0xF to correspond to MIDI channels 1-16) - - Details: - - In general MIDI Commands can be mapped to either a specific channel as specified in the mStatus bit. - If the kAUParameterMIDIMapping_AnyChannelFlag bit is set mStatus is a MIDI channel message, then the - MIDI channel number in the status byte is ignored; the mapping is from the specified MIDI message on ANY channel. - - For note commands (note on, note off, key pressure), the MIDI message can trigger either with just a specific - note number, or any note number if the kAUParameterMIDIMapping_AnyNoteFlag bit is set. In these instances, the - note number is used as the trigger value (for instance, a note message could be used to set the - cut off frequency of a filter). - - The Properties: - - kAudioUnitProperty_AllParameterMIDIMappings array of AUParameterMIDIMapping (read/write) - This property is used to both retreive and set the current mapping state between (some/many/all of) its parameters - and MIDI messages. When set, it should replace any previous mapped settings the AU had. - - If this property is implemented by a non-MIDI capable AU (such as an 'aufx' type), then the property is - read only, and recommends a suggested set of mappings for the host to perform. In this case, it is the - host's responsibility to map MIDI message to the AU parameters. As described previously, there are a set - of default mappings (see AudioToolbox/AUMIDIController.h) that the host can recommend to the user - in this circumstance. - - This property's size will be very dynamic, depending on the number of mappings currently in affect, so the - caller should always get the size of the property first before retrieving it. The AU should return an error - if the caller doesn't provide enough space to return all of the current mappings. - - kAudioUnitProperty_AddParameterMIDIMapping array of AUParameterMIDIMapping (write only) - This property is used to Add mappings to the existing set of mappings the AU possesses. It does NOT replace - any existing mappings. - - kAudioUnitProperty_RemoveParameterMIDIMapping array of AUParameterMIDIMapping (write only) - This property is used to remove the specified mappings from the AU. If a mapping is specified that does not - currently exist in the AU, then it should just be ignored. - - kAudioUnitProperty_HotMapParameterMIDIMapping AUParameterMIDIMapping (read/write) - This property is used in two ways, determined by the value supplied by the caller. - (1) If a mapping struct is provided, then that struct provides *all* of the information that the AU should - use to map the parameter, *except* for the MIDI message. The AU should then listen for the next MIDI message - and associate that MIDI message with the supplied AUParameter mapping. When this MIDI message is received and - the mapping made, the AU should also issue a notification on this property - (kAudioUnitProperty_HotMapParameterMIDIMapping) to indicate to the host that the mapping has been made. The host - can then retrieve the mapping that was made by getting the value of this property. - - To avoid possible confusion, it is recommended that once the host has retrieved this mapping (if it is - presenting a UI to describe the mappings for example), that it then clears the mapping state as described next. - - Thus, the only time this property will return a valid value is when the AU has made a mapping. If the AU's mapping - state has been cleared (or it has not been asked to make a mapping), then the AU should return - kAudioUnitErr_InvalidPropertyValue if the host tries to read this value. - - (2) If the value passed in is NULL, then if the AU had a parameter that it was in the process of mapping, it - should disregard that (stop listening to the MIDI messages to create a mapping) and discard the partially - mapped struct. If the value is NULL and the AU is not in the process of mapping, the AU can ignore the request. - - At all times, the _AllMappings property will completely describe the current known state of the AU's mappings - of MIDI messages to parameters. -*/ - - -/* - When mapping, it is recommended that LSB controllers are in general not mapped (ie. the controller range of 32 < 64) - as many host parsers will map 14 bit control values. If you know (or can present an option) that the host deals with - 7 bit controllers only, then these controller ID's can be mapped of course. -*/ - - -struct MIDIValueTransformer { - virtual double tolinear(double) = 0; - virtual double fromlinear(double) = 0; -#if DEBUG - // suppress warning - virtual ~MIDIValueTransformer() { } -#endif -}; - -struct MIDILinearTransformer : public MIDIValueTransformer { - virtual double tolinear(double x) { return x; } - virtual double fromlinear(double x) { return x; } -}; - -struct MIDILogTransformer : public MIDIValueTransformer { - virtual double tolinear(double x) { return log(std::max(x, .00001)); } - virtual double fromlinear(double x) { return exp(x); } -}; - -struct MIDIExpTransformer : public MIDIValueTransformer { - virtual double tolinear(double x) { return exp(x); } - virtual double fromlinear(double x) { return log(std::max(x, .00001)); } -}; - -struct MIDISqrtTransformer : public MIDIValueTransformer { - virtual double tolinear(double x) { return x < 0. ? -(sqrt(-x)) : sqrt(x); } - virtual double fromlinear(double x) { return x < 0. ? -(x * x) : x * x; } -}; - -struct MIDISquareTransformer : public MIDIValueTransformer { - virtual double tolinear(double x) { return x < 0. ? -(x * x) : x * x; } - virtual double fromlinear(double x) { return x < 0. ? -(sqrt(-x)) : sqrt(x); } -}; - -struct MIDICubeRtTransformer : public MIDIValueTransformer { - virtual double tolinear(double x) { return x < 0. ? -(pow(-x, 1./3.)) : pow(x, 1./3.); } - virtual double fromlinear(double x) { return x * x * x; } -}; - -struct MIDICubeTransformer : public MIDIValueTransformer { - virtual double tolinear(double x) { return x * x * x; } - virtual double fromlinear(double x) { return x < 0. ? -(pow(-x, 1./3.)) : pow(x, 1./3.); } -}; - - -class CAAUMIDIMap : public AUParameterMIDIMapping { - -public: -// variables for more efficient parsing of MIDI to Param value - Float32 mMinValue; - Float32 mMaxValue; - MIDIValueTransformer *mTransType; - -// methods - static MIDIValueTransformer *GetTransformer (UInt32 inFlags); - - CAAUMIDIMap() { memset(this, 0, sizeof(CAAUMIDIMap)); } - CAAUMIDIMap (const AUParameterMIDIMapping& inMap) - { - memset(this, 0, sizeof(CAAUMIDIMap)); - memcpy (this, &inMap, sizeof(inMap)); - } - CAAUMIDIMap (AudioUnitScope inScope, AudioUnitElement inElement, AudioUnitParameterID inParam) - { - memset(this, 0, sizeof(CAAUMIDIMap)); - mScope = inScope; - mElement = inElement; - mParameterID = inParam; - } - - - bool IsValid () const { return mStatus != 0; } - - // returns -1 if any channel bit is set - SInt32 Channel () const { return IsAnyChannel() ? -1 : (mStatus & 0xF); } - bool IsAnyChannel () const { - return mFlags & kAUParameterMIDIMapping_AnyChannelFlag; - } - // preserves the existing channel info in the status byte - // preserves any previously set mFlags value - void SetAnyChannel (bool inFlag) - { - if (inFlag) - mFlags |= kAUParameterMIDIMapping_AnyChannelFlag; - else - mFlags &= ~kAUParameterMIDIMapping_AnyChannelFlag; - } - - bool IsAnyNote () const { - return (mFlags & kAUParameterMIDIMapping_AnyNoteFlag) != 0; - } - // preserves the existing key num in the mData1 byte - // preserves any previously set mFlags value - void SetAnyNote (bool inFlag) - { - if (inFlag) - mFlags |= kAUParameterMIDIMapping_AnyNoteFlag; - else - mFlags &= ~kAUParameterMIDIMapping_AnyNoteFlag; - } - - bool IsToggle() const { return (mFlags & kAUParameterMIDIMapping_Toggle) != 0; } - void SetToggle (bool inFlag) - { - if (inFlag) - mFlags |= kAUParameterMIDIMapping_Toggle; - else - mFlags &= ~kAUParameterMIDIMapping_Toggle; - } - - bool IsBipolar() const { return (mFlags & kAUParameterMIDIMapping_Bipolar) != 0; } - // inUseOnValue is valid ONLY if inFlag is true - void SetBipolar (bool inFlag, bool inUseOnValue = false) - { - if (inFlag) { - mFlags |= kAUParameterMIDIMapping_Bipolar; - if (inUseOnValue) - mFlags |= kAUParameterMIDIMapping_Bipolar_On; - else - mFlags &= ~kAUParameterMIDIMapping_Bipolar_On; - } else { - mFlags &= ~kAUParameterMIDIMapping_Bipolar; - mFlags &= ~kAUParameterMIDIMapping_Bipolar_On; - } - } - bool IsBipolar_OnValue () const { return (mFlags & kAUParameterMIDIMapping_Bipolar_On) != 0; } - - bool IsSubRange () const { return (mFlags & kAUParameterMIDIMapping_SubRange) != 0; } - void SetSubRange (Float32 inStartValue, Float32 inStopValue) - { - mFlags |= kAUParameterMIDIMapping_SubRange; - - mSubRangeMin = inStartValue; - mSubRangeMax = inStopValue; - } - - void SetParamRange(Float32 minValue, Float32 maxValue) - { - mMinValue = minValue; - mMaxValue = maxValue; - } - - // this will retain the subrange values previously set. - void SetSubRange (bool inFlag) - { - if (inFlag) - mFlags |= kAUParameterMIDIMapping_SubRange; - else - mFlags &= ~kAUParameterMIDIMapping_SubRange; - } - - bool IsAnyValue() const{return !IsBipolar();} - bool IsOnValue() const{return IsBipolar_OnValue();} - bool IsOffValue() const{return IsBipolar();} - - bool IsNoteOff () const { return ((mStatus & 0xF0) == 0x80); } - bool IsNoteOn () const { return ((mStatus & 0xF0) == 0x90); } - - bool IsKeyPressure () const { return ((mStatus & 0xF0) == 0xA0); } - - bool IsKeyEvent () const { return (mStatus > 0x7F) && (mStatus < 0xB0); } - - bool IsPatchChange () const { return ((mStatus & 0xF0) == 0xC0); } - bool IsChannelPressure () const { return ((mStatus & 0xF0) == 0xD0); } - bool IsPitchBend () const { return ((mStatus & 0xF0) == 0xE0); } - bool IsControlChange () const { return ((mStatus & 0xF0) == 0xB0); } - - - void SetControllerOnValue(){SetBipolar(true,true);} - void SetControllerOffValue(){SetBipolar(true,false);} - void SetControllerAnyValue(){SetBipolar(false,false);} - - // All of these Set calls will reset the mFlags field based on the - // anyChannel param value - void SetNoteOff (UInt8 key, SInt8 channel, bool anyChannel = false) - { - mStatus = 0x80 | (channel & 0xF); - mData1 = key; - mFlags = (anyChannel ? kAUParameterMIDIMapping_AnyChannelFlag : 0); - - } - - void SetNoteOn (UInt8 key, SInt8 channel, bool anyChannel = false) - { - mStatus = 0x90 | (channel & 0xF); - mData1 = key; - mFlags = (anyChannel ? kAUParameterMIDIMapping_AnyChannelFlag : 0); - } - - void SetPolyKey (UInt8 key, SInt8 channel, bool anyChannel = false) - { - mStatus = 0xA0 | (channel & 0xF); - mData1 = key; - mFlags = (anyChannel ? kAUParameterMIDIMapping_AnyChannelFlag : 0); - } - - void SetControlChange (UInt8 controllerID, SInt8 channel, bool anyChannel = false) - { - mStatus = 0xB0 | (channel & 0xF); - mData1 = controllerID; - mFlags = (anyChannel ? kAUParameterMIDIMapping_AnyChannelFlag : 0); - } - - void SetPatchChange (UInt8 patchChange, SInt8 channel, bool anyChannel = false) - { - mStatus = 0xC0 | (channel & 0xF); - mData1 = patchChange; - mFlags = (anyChannel ? kAUParameterMIDIMapping_AnyChannelFlag : 0); - } - - void SetChannelPressure (SInt8 channel, bool anyChannel = false) - { - mStatus = 0xD0 | (channel & 0xF); - mData1 = 0; - mFlags = (anyChannel ? kAUParameterMIDIMapping_AnyChannelFlag : 0); - } - - void SetPitchBend (SInt8 channel, bool anyChannel = false) - { - mStatus = 0xE0 | (channel & 0xF); - mData1 = 0; - mFlags = (anyChannel ? kAUParameterMIDIMapping_AnyChannelFlag : 0); - } - - - Float32 ParamValueFromMIDILinear (Float32 inLinearValue) const - { - Float32 low, high; - if (IsSubRange()){ - low = mSubRangeMin; - high = mSubRangeMax; - } - else { - low = mMinValue; - high = mMaxValue; - } - - - // WE ARE ASSUMING YOU HAVE SET THIS UP PROPERLY!!!!! (or this will crash cause it will be NULL) - return (Float32)mTransType->fromlinear((inLinearValue * (high - low)) + low); - } - - - // The CALLER of this method must ensure that the status byte's MIDI Command (ignoring the channel) matches!!! - bool MIDI_Matches (UInt8 inChannel, UInt8 inData1, UInt8 inData2, Float32 &outLinear) const; - - void Print () const; - - void Save (CFPropertyListRef &outData) const; - void Restore (CFDictionaryRef inData); - - static void SaveAsMapPList (AudioUnit inUnit, - const AUParameterMIDIMapping * inMappings, - UInt32 inNumMappings, - CFPropertyListRef &outData, - CFStringRef inName = NULL); - - // inNumMappings describes how much memory is allocated in outMappings - static void RestoreFromMapPList (const CFDictionaryRef inData, - AUParameterMIDIMapping * outMappings, - UInt32 inNumMappings); - - static UInt32 NumberOfMaps (const CFDictionaryRef inData); -}; - - - // these sorting operations sort for run-time efficiency based on the MIDI messages -inline bool operator== (const CAAUMIDIMap &a, const CAAUMIDIMap &b) -{ - // ignore channel first - return (((a.mStatus & 0xF0) == (b.mStatus & 0xF0)) - && (a.mData1 == b.mData1) - && ((a.mStatus & 0xF) == (b.mStatus & 0xf)) // now compare the channel - && (a.mParameterID == b.mParameterID) - && (a.mElement == b.mElement) - && (a.mScope == b.mScope)); - - // reserved field comparisons - ignored until/if they are used -} - -inline bool operator< (const CAAUMIDIMap &a, const CAAUMIDIMap &b) -{ - if ((a.mStatus & 0xF0) != (b.mStatus & 0xF0)) - return ((a.mStatus & 0xF0) < (b.mStatus & 0xF0)); - - if (a.mData1 != b.mData1) - return (a.mData1 < b.mData1); - - if ((a.mStatus & 0xF) != (b.mStatus & 0xf)) // now compare the channel - return ((a.mStatus & 0xF) < (b.mStatus & 0xf)); - -// reserved field comparisons - ignored until/if they are used - -// we're sorting this by MIDI, so we don't really care how the rest is sorted - return ((a.mParameterID < b.mParameterID) - && (a.mElement < b.mElement) - && (a.mScope < b.mScope)); -} - - - -class CompareMIDIMap { - int compare (const CAAUMIDIMap &a, const CAAUMIDIMap &b) - { - if ((a.mStatus & 0xF0) < (b.mStatus & 0xF0)) - return -1; - if ((a.mStatus & 0xF0) > (b.mStatus & 0xF0)) - return 1; - - // note event - if (a.mStatus < 0xB0 || a.mStatus >= 0xD0) - return 0; - if (a.mData1 > b.mData1) return 1; - if (a.mData1 < b.mData1) return -1; - return 0; - } - -public: - bool operator() (const CAAUMIDIMap &a, const CAAUMIDIMap &b) { - return compare (a, b) < 0; - } - bool Finish (const CAAUMIDIMap &a, const CAAUMIDIMap &b) { - return compare (a, b) != 0; - } -}; - - -/* - usage: To find potential mapped events for a given status byte, where mMMapEvents is a sorted vec - CompareMIDIMap comparObj; - sortVecIter lower_iter = std::lower_bound(mMMapEvents.begin(), mMMapEvents.end(), inStatusByte, compareObj); - for (;lower_iter < mMMapEvents.end(); ++lower_iter) { - // then, see if we go out of the status byte range, using the Finish method - if (compareObj.Finish(map, tempMap)) // tempMap is a CAAUMIDIMap object with the status/dataByte 1 set - break; - // ... - } - - in the for loop you call the MIDI_Matches call, to see if the MIDI event matches a given AUMIDIParam mapping - special note: you HAVE to transform note on (with vel zero) events to the note off status byte -*/ - -#endif diff --git a/src/CoreAudio/CoreAudioComponent/PublicUtility/CAAUMIDIMapManager.cpp b/src/CoreAudio/CoreAudioComponent/PublicUtility/CAAUMIDIMapManager.cpp deleted file mode 100644 index b24ff9945..000000000 --- a/src/CoreAudio/CoreAudioComponent/PublicUtility/CAAUMIDIMapManager.cpp +++ /dev/null @@ -1,233 +0,0 @@ -/* - File: CAAUMIDIMapManager.cpp - Abstract: CAAUMIDIMapManager.h - Version: 1.1 - - Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple - Inc. ("Apple") in consideration of your agreement to the following - terms, and your use, installation, modification or redistribution of - this Apple software constitutes acceptance of these terms. If you do - not agree with these terms, please do not use, install, modify or - redistribute this Apple software. - - In consideration of your agreement to abide by the following terms, and - subject to these terms, Apple grants you a personal, non-exclusive - license, under Apple's copyrights in this original Apple software (the - "Apple Software"), to use, reproduce, modify and redistribute the Apple - Software, with or without modifications, in source and/or binary forms; - provided that if you redistribute the Apple Software in its entirety and - without modifications, you must retain this notice and the following - text and disclaimers in all such redistributions of the Apple Software. - Neither the name, trademarks, service marks or logos of Apple Inc. may - be used to endorse or promote products derived from the Apple Software - without specific prior written permission from Apple. Except as - expressly stated in this notice, no other rights or licenses, express or - implied, are granted by Apple herein, including but not limited to any - patent rights that may be infringed by your derivative works or by other - works in which the Apple Software may be incorporated. - - The Apple Software is provided by Apple on an "AS IS" basis. APPLE - MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION - THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS - FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND - OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS. - - IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL - OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, - MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED - AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), - STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE - POSSIBILITY OF SUCH DAMAGE. - - Copyright (C) 2014 Apple Inc. All Rights Reserved. - -*/ -#include "CAAUMIDIMapManager.h" -#include - -CAAUMIDIMapManager::CAAUMIDIMapManager() -{ - hotMapping = false; -} - -static void FillInMap (CAAUMIDIMap &map, AUBase &That) -{ - AudioUnitParameterInfo info; - That.GetParameterInfo (map.mScope, map.mParameterID, info); - - if (map.IsSubRange()) { - map.mMinValue = map.mSubRangeMin; - map.mMaxValue = map.mSubRangeMax; - } else { - map.mMinValue = info.minValue; - map.mMaxValue = info.maxValue; - } - - map.mTransType = CAAUMIDIMap::GetTransformer(info.flags); -} - -OSStatus CAAUMIDIMapManager::SortedInsertToParamaterMaps (AUParameterMIDIMapping *maps, UInt32 inNumMaps, AUBase &That) -{ - for (unsigned int i = 0; i < inNumMaps; ++i) - { - CAAUMIDIMap map(maps[i]); - - FillInMap (map, That); - - int idx = FindParameterIndex (maps[i]); - if (idx > -1) - mParameterMaps.erase(mParameterMaps.begin() + idx); - - // least disruptive place to put this is at the end - mParameterMaps.push_back(map); - } - - std::sort(mParameterMaps.begin(), mParameterMaps.end(), CompareMIDIMap()); - - return noErr; -} - -void CAAUMIDIMapManager::GetHotParameterMap(AUParameterMIDIMapping &outMap ) -{ - outMap = mHotMap; -} - -void CAAUMIDIMapManager::SortedRemoveFromParameterMaps(AUParameterMIDIMapping *maps, UInt32 inNumMaps, bool &outMapDidChange) -{ - if (hotMapping) { - hotMapping = false; - } - - outMapDidChange = false; - for (unsigned int i = 0; i < inNumMaps; ++i) { - int idx = FindParameterIndex (maps[i]); - if (idx > -1) { - //mParameterMaps[idx].Print(); - mParameterMaps.erase(mParameterMaps.begin() + idx); - outMapDidChange = true; - } - } -} - -void CAAUMIDIMapManager::ReplaceAllMaps (AUParameterMIDIMapping* inMappings, UInt32 inNumMaps, AUBase &That) -{ - mParameterMaps.clear(); - - for (unsigned int i = 0; i < inNumMaps; ++i) { - CAAUMIDIMap mapping(inMappings[i]); - - FillInMap (mapping, That); - mParameterMaps.push_back (mapping); - } - - std::sort(mParameterMaps.begin(),mParameterMaps.end(), CompareMIDIMap()); -} - -bool CAAUMIDIMapManager::HandleHotMapping(UInt8 inStatus, - UInt8 inChannel, - UInt8 inData1, - AUBase &That) -{ //used to set the hot map info - - if (inStatus == 0xf0) return false; - - if (!hotMapping) return false; - hotMapping = false; - - mHotMap.mStatus = inStatus | inChannel; - mHotMap.mData1 = inData1; - - SortedInsertToParamaterMaps (&mHotMap, 1, That); - return true; -} - -#if DEBUG - -void CAAUMIDIMapManager::Print() -{ - for ( ParameterMaps::iterator i = mParameterMaps.begin(); i < mParameterMaps.end(); ++i) { - CAAUMIDIMap* listmap = &(*i); - listmap->Print(); - } -} - -#endif // DEBUG - -void CAAUMIDIMapManager::GetMaps(AUParameterMIDIMapping* maps) -{ - int i = 0; - for ( ParameterMaps::iterator iter = mParameterMaps.begin(); iter < mParameterMaps.end(); ++iter, ++i) { - AUParameterMIDIMapping &listmap = (*iter); - maps[i] = listmap; - } -} - -int CAAUMIDIMapManager::FindParameterIndex (AUParameterMIDIMapping &inMap) -{ - //used to get back hot mapping and one at a time maps, for ui - - int idx = 0; - for ( ParameterMaps::iterator i = mParameterMaps.begin(); i < mParameterMaps.end(); ++i) { - CAAUMIDIMap & listmap = (*i); - if ( (listmap.mParameterID == inMap.mParameterID) && - (listmap.mScope == inMap.mScope) && - (listmap.mElement == inMap.mElement) ) - { - return idx; - } - idx++; - } - return -1; -} - -bool CAAUMIDIMapManager::FindParameterMapEventMatch( UInt8 inStatus, - UInt8 inChannel, - UInt8 inData1, - UInt8 inData2, - UInt32 inBufferOffset, - AUBase& inAUBase) -{ - bool ret_value = false; - - if (inStatus == 0x90 && !inData2) - inStatus = 0x80 | inChannel; - - //used to test for midi matches once map is made - CAAUMIDIMap tempMap; - tempMap.mStatus = inStatus | inChannel; - tempMap.mData1 = inData1; - - CompareMIDIMap compareObj; - - AudioUnitEvent event; - event.mEventType = kAudioUnitEvent_ParameterValueChange; - event.mArgument.mParameter.mAudioUnit = inAUBase.GetComponentInstance(); - - ParameterMaps::iterator lower_iter = - std::lower_bound(mParameterMaps.begin(), mParameterMaps.end(), tempMap, compareObj); - - while (lower_iter < mParameterMaps.end()) - { - CAAUMIDIMap & map = (*lower_iter); - if (compareObj.Finish(map, tempMap)) - break; - - Float32 value; - if (map.MIDI_Matches(inChannel, inData1, inData2, value)) - { - inAUBase.SetParameter ( map.mParameterID, map.mScope, map.mElement, - map.ParamValueFromMIDILinear(value), inBufferOffset); - - event.mArgument.mParameter.mParameterID = map.mParameterID; - event.mArgument.mParameter.mScope = map.mScope; - event.mArgument.mParameter.mElement = map.mElement; - - AUEventListenerNotify(NULL, NULL, &event); - ret_value = true; - } - ++lower_iter; - } - return ret_value; -} diff --git a/src/CoreAudio/CoreAudioComponent/PublicUtility/CAAUMIDIMapManager.h b/src/CoreAudio/CoreAudioComponent/PublicUtility/CAAUMIDIMapManager.h deleted file mode 100644 index 8926d8f6e..000000000 --- a/src/CoreAudio/CoreAudioComponent/PublicUtility/CAAUMIDIMapManager.h +++ /dev/null @@ -1,102 +0,0 @@ -/* - File: CAAUMIDIMapManager.h - Abstract: Part of CoreAudio Utility Classes - Version: 1.1 - - Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple - Inc. ("Apple") in consideration of your agreement to the following - terms, and your use, installation, modification or redistribution of - this Apple software constitutes acceptance of these terms. If you do - not agree with these terms, please do not use, install, modify or - redistribute this Apple software. - - In consideration of your agreement to abide by the following terms, and - subject to these terms, Apple grants you a personal, non-exclusive - license, under Apple's copyrights in this original Apple software (the - "Apple Software"), to use, reproduce, modify and redistribute the Apple - Software, with or without modifications, in source and/or binary forms; - provided that if you redistribute the Apple Software in its entirety and - without modifications, you must retain this notice and the following - text and disclaimers in all such redistributions of the Apple Software. - Neither the name, trademarks, service marks or logos of Apple Inc. may - be used to endorse or promote products derived from the Apple Software - without specific prior written permission from Apple. Except as - expressly stated in this notice, no other rights or licenses, express or - implied, are granted by Apple herein, including but not limited to any - patent rights that may be infringed by your derivative works or by other - works in which the Apple Software may be incorporated. - - The Apple Software is provided by Apple on an "AS IS" basis. APPLE - MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION - THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS - FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND - OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS. - - IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL - OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, - MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED - AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), - STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE - POSSIBILITY OF SUCH DAMAGE. - - Copyright (C) 2014 Apple Inc. All Rights Reserved. - -*/ -#ifndef __CAAUMIDIMapManager_h_ -#define __CAAUMIDIMapManager_h_ - -#include "AUBase.h" -#include "CAAUMIDIMap.h" -#include -#include - -class CAAUMIDIMapManager { - -protected: - - typedef std::vector ParameterMaps; - ParameterMaps mParameterMaps; - - bool hotMapping; - AUParameterMIDIMapping mHotMap; - -public: - - CAAUMIDIMapManager(); - - UInt32 NumMaps(){return static_cast(mParameterMaps.size());} - void GetMaps(AUParameterMIDIMapping* maps); - - int FindParameterIndex(AUParameterMIDIMapping &map); - - void GetHotParameterMap(AUParameterMIDIMapping &outMap); - - void SortedRemoveFromParameterMaps (AUParameterMIDIMapping *maps, UInt32 inNumMaps, bool &outMapDidChange); - OSStatus SortedInsertToParamaterMaps (AUParameterMIDIMapping *maps, UInt32 inNumMaps, AUBase &That); - - void ReplaceAllMaps (AUParameterMIDIMapping* inMappings, UInt32 inNumMaps, AUBase &That); - - bool IsHotMapping(){return hotMapping;} - void SetHotMapping (AUParameterMIDIMapping &inMap){hotMapping = true; mHotMap = inMap; } - - bool HandleHotMapping( UInt8 inStatus, - UInt8 inChannel, - UInt8 inData1, - AUBase &That); - - - bool FindParameterMapEventMatch(UInt8 inStatus, - UInt8 inChannel, - UInt8 inData1, - UInt8 inData2, - UInt32 inBufferOffset, - AUBase& inAUBase); -#if DEBUG - void Print(); -#endif -}; - - -#endif diff --git a/src/CoreAudio/CoreAudioComponent/PublicUtility/CAAtomic.h b/src/CoreAudio/CoreAudioComponent/PublicUtility/CAAtomic.h deleted file mode 100644 index c9a611bf7..000000000 --- a/src/CoreAudio/CoreAudioComponent/PublicUtility/CAAtomic.h +++ /dev/null @@ -1,305 +0,0 @@ -/* - File: CAAtomic.h - Abstract: Part of CoreAudio Utility Classes - Version: 1.1 - - Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple - Inc. ("Apple") in consideration of your agreement to the following - terms, and your use, installation, modification or redistribution of - this Apple software constitutes acceptance of these terms. If you do - not agree with these terms, please do not use, install, modify or - redistribute this Apple software. - - In consideration of your agreement to abide by the following terms, and - subject to these terms, Apple grants you a personal, non-exclusive - license, under Apple's copyrights in this original Apple software (the - "Apple Software"), to use, reproduce, modify and redistribute the Apple - Software, with or without modifications, in source and/or binary forms; - provided that if you redistribute the Apple Software in its entirety and - without modifications, you must retain this notice and the following - text and disclaimers in all such redistributions of the Apple Software. - Neither the name, trademarks, service marks or logos of Apple Inc. may - be used to endorse or promote products derived from the Apple Software - without specific prior written permission from Apple. Except as - expressly stated in this notice, no other rights or licenses, express or - implied, are granted by Apple herein, including but not limited to any - patent rights that may be infringed by your derivative works or by other - works in which the Apple Software may be incorporated. - - The Apple Software is provided by Apple on an "AS IS" basis. APPLE - MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION - THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS - FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND - OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS. - - IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL - OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, - MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED - AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), - STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE - POSSIBILITY OF SUCH DAMAGE. - - Copyright (C) 2014 Apple Inc. All Rights Reserved. - -*/ -/* - This file implements all Atomic operations using Interlocked functions specified in - Winbase.h -NOTE: According to Microsoft documentation, all Interlocked functions generates a -full barrier. - On Windows: - As the Interlocked functions returns the Old value, Extra checks and operations - are made after the atomic operation to return value consistent with OSX counterparts. -*/ -#ifndef __CAAtomic_h__ -#define __CAAtomic_h__ - -#if TARGET_OS_WIN32 - #include - #include - #pragma intrinsic(_InterlockedOr) - #pragma intrinsic(_InterlockedAnd) -#else - #include - #include -#endif - -inline void CAMemoryBarrier() -{ -#if TARGET_OS_WIN32 - MemoryBarrier(); -#else - OSMemoryBarrier(); -#endif -} - -inline SInt32 CAAtomicAdd32Barrier(SInt32 theAmt, volatile SInt32* theValue) -{ -#if TARGET_OS_WIN32 - long lRetVal = InterlockedExchangeAdd((volatile long*)theValue, theAmt); - // InterlockedExchangeAdd returns the original value which differs from OSX version. - // At this point the addition would have occured and hence returning the new value - // to keep it sync with OSX. - return lRetVal + theAmt; -#else - return OSAtomicAdd32Barrier(theAmt, (volatile int32_t *)theValue); -#endif -} - -inline SInt32 CAAtomicOr32Barrier(UInt32 theMask, volatile UInt32* theValue) -{ -#if TARGET_OS_WIN32 - // InterlockedAnd macro is not defined in x86 platform, and hence using the intrinsic - // function instead. - long j = _InterlockedOr((volatile long*)theValue, theMask); - // _InterlockedOr returns the original value which differs from OSX version. - // Returning the new value similar to OSX - return (SInt32)(j | theMask); -#else - return OSAtomicOr32Barrier(theMask, (volatile uint32_t *)theValue); -#endif -} - -inline SInt32 CAAtomicAnd32Barrier(UInt32 theMask, volatile UInt32* theValue) -{ -#if TARGET_OS_WIN32 -// InterlockedAnd macro is not defined in x86 platform, and hence using the intrinsic -// function instead. - long j = _InterlockedAnd((volatile long*)theValue, theMask); - // _InterlockedAnd returns the original value which differs from OSX version. - // Returning the new value similar to OSX - return (SInt32)(j & theMask); -#else - return OSAtomicAnd32Barrier(theMask, (volatile uint32_t *)theValue); -#endif -} - -inline bool CAAtomicCompareAndSwap32Barrier(SInt32 oldValue, SInt32 newValue, volatile SInt32 *theValue) -{ -#if TARGET_OS_WIN32 - // InterlockedCompareExchange returns the old value. But we need to return bool value. - long lRetVal = InterlockedCompareExchange((volatile long*)theValue, newValue, oldValue); -// Hence we check if the new value is set and if it is we return true else false. -// If theValue is equal to oldValue then the swap happens. Otherwise swap doesn't happen. - return (oldValue == lRetVal); -#else - return OSAtomicCompareAndSwap32Barrier(oldValue, newValue, (volatile int32_t *)theValue); -#endif -} - - -inline SInt32 CAAtomicIncrement32(volatile SInt32* theValue) -{ -#if TARGET_OS_WIN32 - return (SInt32)InterlockedIncrement((volatile long*)theValue); -#else - return OSAtomicIncrement32((volatile int32_t *)theValue); -#endif -} - -inline SInt32 CAAtomicDecrement32(volatile SInt32* theValue) -{ -#if TARGET_OS_WIN32 - return (SInt32)InterlockedDecrement((volatile long*)theValue); -#else - return OSAtomicDecrement32((volatile int32_t *)theValue); -#endif -} - -inline SInt32 CAAtomicIncrement32Barrier(volatile SInt32* theValue) -{ -#if TARGET_OS_WIN32 - return CAAtomicIncrement32(theValue); -#else - return OSAtomicIncrement32Barrier((volatile int32_t *)theValue); -#endif -} - -inline SInt32 CAAtomicDecrement32Barrier(volatile SInt32* theValue) -{ -#if TARGET_OS_WIN32 - return CAAtomicDecrement32(theValue); -#else - return OSAtomicDecrement32Barrier((volatile int32_t *)theValue); -#endif -} - -inline bool CAAtomicTestAndClearBarrier(int bitToClear, void* theAddress) -{ -#if TARGET_OS_WIN32 - BOOL bOldVal = InterlockedBitTestAndReset((long*)theAddress, bitToClear); - return (bOldVal ? true : false); -#else - return OSAtomicTestAndClearBarrier(bitToClear, (volatile void *)theAddress); -#endif -} - -inline bool CAAtomicTestAndClear(int bitToClear, void* theAddress) -{ -#if TARGET_OS_WIN32 - BOOL bOldVal = CAAtomicTestAndClearBarrier(bitToClear, (long*)theAddress); - return (bOldVal ? true : false); -#else - return OSAtomicTestAndClear(bitToClear, (volatile void *)theAddress); -#endif -} - -inline bool CAAtomicTestAndSetBarrier(int bitToSet, void* theAddress) -{ -#if TARGET_OS_WIN32 - BOOL bOldVal = InterlockedBitTestAndSet((long*)theAddress, bitToSet); - return (bOldVal ? true : false); -#else - return OSAtomicTestAndSetBarrier(bitToSet, (volatile void *)theAddress); -#endif -} - -// int32_t flavors -- for C++ only since we can't overload in C -// CFBase.h defines SInt32 as signed int which is similar to int32_t. If CFBase.h is included, then -// this will generate redefinition error. But on Mac, CFBase.h, still includes MacTypes.h where -// SInt32 is defined as signed long so this would work there. -// So in order to fix the redefinition errors, we define these functions only if MacTypes.h is included. -#if defined(__cplusplus) && defined(__MACTYPES__) && !__LP64__ -inline int32_t CAAtomicAdd32Barrier(int32_t theAmt, volatile int32_t* theValue) -{ - return CAAtomicAdd32Barrier(theAmt, (volatile SInt32 *)theValue); -} - -inline int32_t CAAtomicOr32Barrier(uint32_t theMask, volatile uint32_t* theValue) -{ - return CAAtomicOr32Barrier(theMask, (volatile UInt32 *)theValue); -} - -inline int32_t CAAtomicAnd32Barrier(uint32_t theMask, volatile uint32_t* theValue) -{ - return CAAtomicAnd32Barrier(theMask, (volatile UInt32 *)theValue); -} - -inline bool CAAtomicCompareAndSwap32Barrier(int32_t oldValue, int32_t newValue, volatile int32_t *theValue) -{ - return CAAtomicCompareAndSwap32Barrier(oldValue, newValue, (volatile SInt32 *)theValue); -} - -inline int32_t CAAtomicIncrement32(volatile int32_t* theValue) -{ - return CAAtomicIncrement32((volatile SInt32 *)theValue); -} - -inline int32_t CAAtomicDecrement32(volatile int32_t* theValue) -{ - return CAAtomicDecrement32((volatile SInt32 *)theValue); -} - -inline int32_t CAAtomicIncrement32Barrier(volatile int32_t* theValue) -{ - return CAAtomicIncrement32Barrier((volatile SInt32 *)theValue); -} - -inline int32_t CAAtomicDecrement32Barrier(volatile int32_t* theValue) -{ - return CAAtomicDecrement32Barrier((volatile SInt32 *)theValue); -} -#endif // __cplusplus && !__LP64__ - -#if __LP64__ -inline bool CAAtomicCompareAndSwap64Barrier( int64_t __oldValue, int64_t __newValue, volatile int64_t *__theValue ) -{ - return OSAtomicCompareAndSwap64Barrier(__oldValue, __newValue, __theValue); -} -#endif - -inline bool CAAtomicCompareAndSwapPtrBarrier(void *__oldValue, void *__newValue, volatile void ** __theValue) -{ -#if __LP64__ - return CAAtomicCompareAndSwap64Barrier((int64_t)__oldValue, (int64_t)__newValue, (int64_t *)__theValue); -#else - return CAAtomicCompareAndSwap32Barrier((int32_t)__oldValue, (int32_t)__newValue, (int32_t *)__theValue); -#endif -} - -/* Spinlocks. These use memory barriers as required to synchronize access to shared - * memory protected by the lock. The lock operation spins, but employs various strategies - * to back off if the lock is held, making it immune to most priority-inversion livelocks. - * The try operation immediately returns false if the lock was held, true if it took the - * lock. The convention is that unlocked is zero, locked is nonzero. - */ -#define CA_SPINLOCK_INIT 0 - -typedef int32_t CASpinLock; - -bool CASpinLockTry( volatile CASpinLock *__lock ); -void CASpinLockLock( volatile CASpinLock *__lock ); -void CASpinLockUnlock( volatile CASpinLock *__lock ); - -inline void CASpinLockLock( volatile CASpinLock *__lock ) -{ -#if TARGET_OS_MAC - OSSpinLockLock(__lock); -#else - while (CAAtomicTestAndSetBarrier(0, (void*)__lock)) - usleep(1000); // ??? -#endif -} - -inline void CASpinLockUnlock( volatile CASpinLock *__lock ) -{ -#if TARGET_OS_MAC - OSSpinLockUnlock(__lock); -#else - CAAtomicTestAndClearBarrier(0, (void*)__lock); -#endif -} - -inline bool CASpinLockTry( volatile CASpinLock *__lock ) -{ -#if TARGET_OS_MAC - return OSSpinLockTry(__lock); -#else - return (CAAtomicTestAndSetBarrier(0, (void*)__lock) == 0); -#endif -} - - -#endif // __CAAtomic_h__ diff --git a/src/CoreAudio/CoreAudioComponent/PublicUtility/CAAtomicStack.h b/src/CoreAudio/CoreAudioComponent/PublicUtility/CAAtomicStack.h deleted file mode 100644 index 8d40fc5d2..000000000 --- a/src/CoreAudio/CoreAudioComponent/PublicUtility/CAAtomicStack.h +++ /dev/null @@ -1,239 +0,0 @@ -/* - File: CAAtomicStack.h - Abstract: Part of CoreAudio Utility Classes - Version: 1.1 - - Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple - Inc. ("Apple") in consideration of your agreement to the following - terms, and your use, installation, modification or redistribution of - this Apple software constitutes acceptance of these terms. If you do - not agree with these terms, please do not use, install, modify or - redistribute this Apple software. - - In consideration of your agreement to abide by the following terms, and - subject to these terms, Apple grants you a personal, non-exclusive - license, under Apple's copyrights in this original Apple software (the - "Apple Software"), to use, reproduce, modify and redistribute the Apple - Software, with or without modifications, in source and/or binary forms; - provided that if you redistribute the Apple Software in its entirety and - without modifications, you must retain this notice and the following - text and disclaimers in all such redistributions of the Apple Software. - Neither the name, trademarks, service marks or logos of Apple Inc. may - be used to endorse or promote products derived from the Apple Software - without specific prior written permission from Apple. Except as - expressly stated in this notice, no other rights or licenses, express or - implied, are granted by Apple herein, including but not limited to any - patent rights that may be infringed by your derivative works or by other - works in which the Apple Software may be incorporated. - - The Apple Software is provided by Apple on an "AS IS" basis. APPLE - MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION - THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS - FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND - OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS. - - IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL - OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, - MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED - AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), - STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE - POSSIBILITY OF SUCH DAMAGE. - - Copyright (C) 2014 Apple Inc. All Rights Reserved. - -*/ -#ifndef __CAAtomicStack_h__ -#define __CAAtomicStack_h__ - -#if !defined(__COREAUDIO_USE_FLAT_INCLUDES__) - #include -#else - #include -#endif - -#if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_4 - #include -#endif - -// linked list LIFO or FIFO (pop_all_reversed) stack, elements are pushed and popped atomically -// class T must implement T *& next(). -template -class TAtomicStack { -public: - TAtomicStack() : mHead(NULL) { } - - // non-atomic routines, for use when initializing/deinitializing, operate NON-atomically - void push_NA(T *item) - { - item->next() = mHead; - mHead = item; - } - - T * pop_NA() - { - T *result = mHead; - if (result) - mHead = result->next(); - return result; - } - - bool empty() const { return mHead == NULL; } - - T * head() { return mHead; } - - // atomic routines - void push_atomic(T *item) - { - T *head_; - do { - head_ = mHead; - item->next() = head_; - } while (!compare_and_swap(head_, item, &mHead)); - } - - void push_multiple_atomic(T *item) - // pushes entire linked list headed by item - { - T *head_, *p = item, *tail; - // find the last one -- when done, it will be linked to head - do { - tail = p; - p = p->next(); - } while (p); - do { - head_ = mHead; - tail->next() = head_; - } while (!compare_and_swap(head_, item, &mHead)); - } - - T * pop_atomic_single_reader() - // this may only be used when only one thread may potentially pop from the stack. - // if multiple threads may pop, this suffers from the ABA problem. - // TAtomicStack suffers from the ABA problem - { - T *result; - do { - if ((result = mHead) == NULL) - break; - } while (!compare_and_swap(result, result->next(), &mHead)); - return result; - } - - T * pop_atomic() - // This is inefficient for large linked lists. - // prefer pop_all() to a series of calls to pop_atomic. - // push_multiple_atomic has to traverse the entire list. - { - T *result = pop_all(); - if (result) { - T *next = result->next(); - if (next) - // push all the remaining items back onto the stack - push_multiple_atomic(next); - } - return result; - } - - T * pop_all() - { - T *result; - do { - if ((result = mHead) == NULL) - break; - } while (!compare_and_swap(result, NULL, &mHead)); - return result; - } - - T* pop_all_reversed() - { - TAtomicStack reversed; - T *p = pop_all(), *next; - while (p != NULL) { - next = p->next(); - reversed.push_NA(p); - p = next; - } - return reversed.mHead; - } - - static bool compare_and_swap(T *oldvalue, T *newvalue, T **pvalue) - { -#if TARGET_OS_MAC - #if __LP64__ - return ::OSAtomicCompareAndSwap64Barrier(int64_t(oldvalue), int64_t(newvalue), (int64_t *)pvalue); - #elif MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_4 - return ::OSAtomicCompareAndSwap32Barrier(int32_t(oldvalue), int32_t(newvalue), (int32_t *)pvalue); - #else - return ::CompareAndSwap(UInt32(oldvalue), UInt32(newvalue), (UInt32 *)pvalue); - #endif -#else - //return ::CompareAndSwap(UInt32(oldvalue), UInt32(newvalue), (UInt32 *)pvalue); - return CAAtomicCompareAndSwap32Barrier(SInt32(oldvalue), SInt32(newvalue), (SInt32*)pvalue); -#endif - } - -protected: - T * mHead; -}; - -#if ((MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5) && !TARGET_OS_WIN32) -#include - -class CAAtomicStack { -public: - CAAtomicStack(size_t nextPtrOffset) : mNextPtrOffset(nextPtrOffset) { - /*OSQueueHead h = OS_ATOMIC_QUEUE_INIT; mHead = h;*/ - mHead.opaque1 = 0; mHead.opaque2 = 0; - } - // a subset of the above - void push_atomic(void *p) { OSAtomicEnqueue(&mHead, p, mNextPtrOffset); } - void push_NA(void *p) { push_atomic(p); } - - void * pop_atomic() { return OSAtomicDequeue(&mHead, mNextPtrOffset); } - void * pop_atomic_single_reader() { return pop_atomic(); } - void * pop_NA() { return pop_atomic(); } - -private: - OSQueueHead mHead; - size_t mNextPtrOffset; -}; - -// a more efficient subset of TAtomicStack using OSQueue. -template -class TAtomicStack2 { -public: - TAtomicStack2() { - /*OSQueueHead h = OS_ATOMIC_QUEUE_INIT; mHead = h;*/ - mHead.opaque1 = 0; mHead.opaque2 = 0; - mNextPtrOffset = -1; - } - void push_atomic(T *item) { - if (mNextPtrOffset < 0) { - T **pnext = &item->next(); // hack around offsetof not working with C++ - mNextPtrOffset = (Byte *)pnext - (Byte *)item; - } - OSAtomicEnqueue(&mHead, item, mNextPtrOffset); - } - void push_NA(T *item) { push_atomic(item); } - - T * pop_atomic() { return (T *)OSAtomicDequeue(&mHead, mNextPtrOffset); } - T * pop_atomic_single_reader() { return pop_atomic(); } - T * pop_NA() { return pop_atomic(); } - - // caution: do not try to implement pop_all_reversed here. the writer could add new elements - // while the reader is trying to pop old ones! - -private: - OSQueueHead mHead; - ssize_t mNextPtrOffset; -}; - -#else - -#define TAtomicStack2 TAtomicStack - -#endif // MAC_OS_X_VERSION_MAX_ALLOWED && !TARGET_OS_WIN32 - -#endif // __CAAtomicStack_h__ diff --git a/src/CoreAudio/CoreAudioComponent/PublicUtility/CAAudioChannelLayout.cpp b/src/CoreAudio/CoreAudioComponent/PublicUtility/CAAudioChannelLayout.cpp deleted file mode 100644 index 74753598d..000000000 --- a/src/CoreAudio/CoreAudioComponent/PublicUtility/CAAudioChannelLayout.cpp +++ /dev/null @@ -1,153 +0,0 @@ -/* - File: CAAudioChannelLayout.cpp - Abstract: CAAudioChannelLayout.h - Version: 1.1 - - Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple - Inc. ("Apple") in consideration of your agreement to the following - terms, and your use, installation, modification or redistribution of - this Apple software constitutes acceptance of these terms. If you do - not agree with these terms, please do not use, install, modify or - redistribute this Apple software. - - In consideration of your agreement to abide by the following terms, and - subject to these terms, Apple grants you a personal, non-exclusive - license, under Apple's copyrights in this original Apple software (the - "Apple Software"), to use, reproduce, modify and redistribute the Apple - Software, with or without modifications, in source and/or binary forms; - provided that if you redistribute the Apple Software in its entirety and - without modifications, you must retain this notice and the following - text and disclaimers in all such redistributions of the Apple Software. - Neither the name, trademarks, service marks or logos of Apple Inc. may - be used to endorse or promote products derived from the Apple Software - without specific prior written permission from Apple. Except as - expressly stated in this notice, no other rights or licenses, express or - implied, are granted by Apple herein, including but not limited to any - patent rights that may be infringed by your derivative works or by other - works in which the Apple Software may be incorporated. - - The Apple Software is provided by Apple on an "AS IS" basis. APPLE - MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION - THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS - FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND - OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS. - - IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL - OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, - MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED - AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), - STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE - POSSIBILITY OF SUCH DAMAGE. - - Copyright (C) 2014 Apple Inc. All Rights Reserved. - -*/ -//============================================================================= -// Includes -//============================================================================= - -// Self Include -#include "CAAudioChannelLayout.h" -#include "CAAutoDisposer.h" -#include -#include - -//============================================================================= -// CAAudioChannelLayout -//============================================================================= - -AudioChannelLayout* CAAudioChannelLayout::Create(UInt32 inNumberChannelDescriptions) -{ - UInt32 theSize = CalculateByteSize(inNumberChannelDescriptions); - AudioChannelLayout* theAnswer = static_cast(CA_calloc(1, theSize)); - if(theAnswer != NULL) - { - SetAllToUnknown(*theAnswer, inNumberChannelDescriptions); - } - return theAnswer; -} - -void CAAudioChannelLayout::Destroy(AudioChannelLayout* inChannelLayout) -{ - free(inChannelLayout); -} - -void CAAudioChannelLayout::SetAllToUnknown(AudioChannelLayout& outChannelLayout, UInt32 inNumberChannelDescriptions) -{ - outChannelLayout.mChannelLayoutTag = kAudioChannelLayoutTag_UseChannelDescriptions; - outChannelLayout.mChannelBitmap = 0; - outChannelLayout.mNumberChannelDescriptions = inNumberChannelDescriptions; - for(UInt32 theChannelIndex = 0; theChannelIndex < inNumberChannelDescriptions; ++theChannelIndex) - { - outChannelLayout.mChannelDescriptions[theChannelIndex].mChannelLabel = kAudioChannelLabel_Unknown; - outChannelLayout.mChannelDescriptions[theChannelIndex].mChannelFlags = 0; - outChannelLayout.mChannelDescriptions[theChannelIndex].mCoordinates[0] = 0; - outChannelLayout.mChannelDescriptions[theChannelIndex].mCoordinates[1] = 0; - outChannelLayout.mChannelDescriptions[theChannelIndex].mCoordinates[2] = 0; - } -} - -bool operator== (const AudioChannelLayout &x, const AudioChannelLayout &y) -{ - // compare based on the number of channel descriptions present - // (this may be too strict a comparison if all you care about are matching layout tags) - UInt32 theSize1 = CAAudioChannelLayout::CalculateByteSize(x.mNumberChannelDescriptions); - UInt32 theSize2 = CAAudioChannelLayout::CalculateByteSize(y.mNumberChannelDescriptions); - - if (theSize1 != theSize2) - return false; - - return !memcmp (&x, &y, theSize1); -} - -bool operator!= (const AudioChannelLayout &x, const AudioChannelLayout &y) -{ - return !(x == y); -} - -// counting the one bits in a word -inline UInt32 CountOnes(UInt32 x) -{ - // secret magic algorithm for counting bits in a word. - UInt32 t; - x = x - ((x >> 1) & 0x55555555); - t = ((x >> 2) & 0x33333333); - x = (x & 0x33333333) + t; - x = (x + (x >> 4)) & 0x0F0F0F0F; - x = x + (x << 8); - x = x + (x << 16); - return x >> 24; -} - -UInt32 CAAudioChannelLayout::NumberChannels (const AudioChannelLayout& inLayout) -{ - if (inLayout.mChannelLayoutTag == kAudioChannelLayoutTag_UseChannelDescriptions) - return inLayout.mNumberChannelDescriptions; - - if (inLayout.mChannelLayoutTag == kAudioChannelLayoutTag_UseChannelBitmap) - return CountOnes (inLayout.mChannelBitmap); - - return AudioChannelLayoutTag_GetNumberOfChannels(inLayout.mChannelLayoutTag); -} - -void CAShowAudioChannelLayout (FILE* file, const AudioChannelLayout *layout) -{ - if (layout == NULL) - { - fprintf (file, "\tNULL layout\n"); - return; - } - fprintf (file, "\tTag=0x%X, ", (int)layout->mChannelLayoutTag); - if (layout->mChannelLayoutTag == kAudioChannelLayoutTag_UseChannelBitmap) - fprintf (file, "Using Bitmap:0x%X\n", (int)layout->mChannelBitmap); - else { - fprintf (file, "Num Chan Descs=%d\n", (int)layout->mNumberChannelDescriptions); - const AudioChannelDescription *desc = layout->mChannelDescriptions; - for (unsigned int i = 0; i < layout->mNumberChannelDescriptions; ++i, ++desc) { - fprintf (file, "\t\tLabel=%d, Flags=0x%X, ", (int)desc->mChannelLabel, (int)desc->mChannelFlags); - fprintf (file, "[az=%f,el=%f,dist=%f]\n", desc->mCoordinates[0], desc->mCoordinates[1], desc->mCoordinates[2]); - } - } -} diff --git a/src/CoreAudio/CoreAudioComponent/PublicUtility/CAAudioChannelLayout.h b/src/CoreAudio/CoreAudioComponent/PublicUtility/CAAudioChannelLayout.h deleted file mode 100644 index 4307054ae..000000000 --- a/src/CoreAudio/CoreAudioComponent/PublicUtility/CAAudioChannelLayout.h +++ /dev/null @@ -1,199 +0,0 @@ -/* - File: CAAudioChannelLayout.h - Abstract: Part of CoreAudio Utility Classes - Version: 1.1 - - Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple - Inc. ("Apple") in consideration of your agreement to the following - terms, and your use, installation, modification or redistribution of - this Apple software constitutes acceptance of these terms. If you do - not agree with these terms, please do not use, install, modify or - redistribute this Apple software. - - In consideration of your agreement to abide by the following terms, and - subject to these terms, Apple grants you a personal, non-exclusive - license, under Apple's copyrights in this original Apple software (the - "Apple Software"), to use, reproduce, modify and redistribute the Apple - Software, with or without modifications, in source and/or binary forms; - provided that if you redistribute the Apple Software in its entirety and - without modifications, you must retain this notice and the following - text and disclaimers in all such redistributions of the Apple Software. - Neither the name, trademarks, service marks or logos of Apple Inc. may - be used to endorse or promote products derived from the Apple Software - without specific prior written permission from Apple. Except as - expressly stated in this notice, no other rights or licenses, express or - implied, are granted by Apple herein, including but not limited to any - patent rights that may be infringed by your derivative works or by other - works in which the Apple Software may be incorporated. - - The Apple Software is provided by Apple on an "AS IS" basis. APPLE - MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION - THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS - FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND - OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS. - - IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL - OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, - MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED - AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), - STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE - POSSIBILITY OF SUCH DAMAGE. - - Copyright (C) 2014 Apple Inc. All Rights Reserved. - -*/ -#if !defined(__CAAudioChannelLayout_h__) -#define __CAAudioChannelLayout_h__ - -//============================================================================= -// Includes -//============================================================================= - -// System Includes -#if !defined(__COREAUDIO_USE_FLAT_INCLUDES__) - #include - #include -#else - #include - #include -#endif -#include -#include -#include - -#include "CADebugMacros.h" -#include "CAAutoDisposer.h" - -#if !HAL_Build - #include "CAReferenceCounted.h" -#endif - -//============================================================================= -// CAAudioChannelLayout -//============================================================================= - -bool operator== (const AudioChannelLayout &x, const AudioChannelLayout &y); -bool operator!= (const AudioChannelLayout &x, const AudioChannelLayout &y); - -extern "C" void CAShowAudioChannelLayout (FILE* file, const AudioChannelLayout *layout); - -class CAAudioChannelLayout -{ -// static Construction/Destruction -public: - static AudioChannelLayout* Create(UInt32 inNumberChannelDescriptions); - static void Destroy(AudioChannelLayout* inChannelLayout); - static UInt32 CalculateByteSize(UInt32 inNumberChannelDescriptions) { - return SizeOf32(AudioChannelLayout) - SizeOf32(AudioChannelDescription) + (inNumberChannelDescriptions * SizeOf32(AudioChannelDescription)); - } - static void SetAllToUnknown(AudioChannelLayout& outChannelLayout, UInt32 inNumberChannelDescriptions); - static UInt32 NumberChannels(const AudioChannelLayout& inLayout); - -#if !HAL_Build -// object methods -public: - CAAudioChannelLayout (); - - CAAudioChannelLayout (UInt32 inNumberChannels, bool inChooseSurround); - // if inChooseSurround is false, then symmetrical speaker arrangements - // are chosen in place of surround layouts if there is a choice - // This call chooses layouts based on the expected defaults in - // AudioUnit usage - CAAudioChannelLayout (AudioChannelLayoutTag inTag); - CAAudioChannelLayout (const CAAudioChannelLayout &c); - CAAudioChannelLayout (const AudioChannelLayout* inChannelLayout); - ~CAAudioChannelLayout(); - - CAAudioChannelLayout& operator= (const AudioChannelLayout* inChannelLayout); - CAAudioChannelLayout& operator= (const CAAudioChannelLayout& c); - bool operator== (const CAAudioChannelLayout &c) const; - bool operator!= (const CAAudioChannelLayout &c) const; - - void SetWithTag(AudioChannelLayoutTag inTag); - - bool IsValid() const { return NumberChannels() > 0; } - UInt32 Size() const { return mLayout ? mLayout->Size() : 0; } - - UInt32 NumberChannels() const { return mLayout ? mLayout->NumberChannels() : 0; } - - AudioChannelLayoutTag Tag() const { return Layout().mChannelLayoutTag; } - const AudioChannelLayout& Layout() const { return mLayout->Layout(); } - operator const AudioChannelLayout *() const { return &Layout(); } - - void Print () const { Print (stdout); } - void Print (FILE* file) const; - - OSStatus Save (CFPropertyListRef *outData) const; - OSStatus Restore (CFPropertyListRef &inData); - -private: - class RefCountedLayout : public CAReferenceCounted { - void * operator new(size_t /* size */, size_t aclSize) - { - return CA_malloc(sizeof(RefCountedLayout) - sizeof(AudioChannelLayout) + aclSize); - } - - void operator delete(void *mem) - { - free(mem); - } - - - RefCountedLayout(UInt32 inDataSize) : - mByteSize(inDataSize) - { - memset(&mACL, 0, inDataSize); - } - - public: - static RefCountedLayout *CreateWithNumberChannelDescriptions(unsigned nChannels) { - size_t size = CAAudioChannelLayout::CalculateByteSize(nChannels); - return new(size) RefCountedLayout((UInt32)size); - } - - static RefCountedLayout *CreateWithLayout(const AudioChannelLayout *layout) { - size_t size = CAAudioChannelLayout::CalculateByteSize(layout->mNumberChannelDescriptions); - RefCountedLayout *acl = new(size) RefCountedLayout((UInt32)size); - memcpy(&acl->mACL, layout, size); - return acl; - } - static RefCountedLayout *CreateWithLayoutTag(AudioChannelLayoutTag layoutTag) { - RefCountedLayout *acl = CreateWithNumberChannelDescriptions(0); - acl->mACL.mChannelLayoutTag = layoutTag; - return acl; - } - - const AudioChannelLayout & Layout() const { return mACL; } - - UInt32 Size () const { return mByteSize; } - - UInt32 NumberChannels() { return CAAudioChannelLayout::NumberChannels(Layout()); } - - private: - const UInt32 mByteSize; - AudioChannelLayout mACL; - // * * * mACL is variable length and thus must be last * * * - - // only the constructors can change the actual state of the layout - friend CAAudioChannelLayout::CAAudioChannelLayout (UInt32 inNumberChannels, bool inChooseSurround); - friend OSStatus CAAudioChannelLayout::Restore (CFPropertyListRef &inData); - friend CAAudioChannelLayout& CAAudioChannelLayout::operator= (const AudioChannelLayout* inChannelLayout); - friend void CAAudioChannelLayout::SetWithTag(AudioChannelLayoutTag inTag); - - AudioChannelLayout * GetLayout() { return &mACL; } - - private: - // prohibited methods: private and unimplemented. - RefCountedLayout(); - RefCountedLayout(const RefCountedLayout& c); - RefCountedLayout& operator=(const RefCountedLayout& c); - }; - - RefCountedLayout *mLayout; -#endif // HAL_Build - -}; - -#endif diff --git a/src/CoreAudio/CoreAudioComponent/PublicUtility/CAAudioChannelLayoutObject.cpp b/src/CoreAudio/CoreAudioComponent/PublicUtility/CAAudioChannelLayoutObject.cpp deleted file mode 100644 index 009d4b3b5..000000000 --- a/src/CoreAudio/CoreAudioComponent/PublicUtility/CAAudioChannelLayoutObject.cpp +++ /dev/null @@ -1,210 +0,0 @@ -/* - File: CAAudioChannelLayoutObject.cpp - Abstract: CAAudioChannelLayoutObject.h - Version: 1.1 - - Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple - Inc. ("Apple") in consideration of your agreement to the following - terms, and your use, installation, modification or redistribution of - this Apple software constitutes acceptance of these terms. If you do - not agree with these terms, please do not use, install, modify or - redistribute this Apple software. - - In consideration of your agreement to abide by the following terms, and - subject to these terms, Apple grants you a personal, non-exclusive - license, under Apple's copyrights in this original Apple software (the - "Apple Software"), to use, reproduce, modify and redistribute the Apple - Software, with or without modifications, in source and/or binary forms; - provided that if you redistribute the Apple Software in its entirety and - without modifications, you must retain this notice and the following - text and disclaimers in all such redistributions of the Apple Software. - Neither the name, trademarks, service marks or logos of Apple Inc. may - be used to endorse or promote products derived from the Apple Software - without specific prior written permission from Apple. Except as - expressly stated in this notice, no other rights or licenses, express or - implied, are granted by Apple herein, including but not limited to any - patent rights that may be infringed by your derivative works or by other - works in which the Apple Software may be incorporated. - - The Apple Software is provided by Apple on an "AS IS" basis. APPLE - MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION - THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS - FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND - OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS. - - IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL - OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, - MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED - AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), - STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE - POSSIBILITY OF SUCH DAMAGE. - - Copyright (C) 2014 Apple Inc. All Rights Reserved. - -*/ -#include "CAAudioChannelLayout.h" -#if !defined(__COREAUDIO_USE_FLAT_INCLUDES__) - #include -#else - #include -#endif - -CAAudioChannelLayout::CAAudioChannelLayout () -{ - mLayout = RefCountedLayout::CreateWithNumberChannelDescriptions(0); -} - -//============================================================================= -// CAAudioChannelLayout::CAAudioChannelLayout -//============================================================================= -CAAudioChannelLayout::CAAudioChannelLayout (UInt32 inNumberChannels, bool inChooseSurround) -{ - // this chooses default layouts based on the number of channels... - AudioChannelLayoutTag tag; - - switch (inNumberChannels) - { - default: - // here we have a "broken" layout, in the sense that we haven't any idea how to lay this out - mLayout = RefCountedLayout::CreateWithNumberChannelDescriptions(inNumberChannels); - SetAllToUnknown(*mLayout->GetLayout(), inNumberChannels); - return; // don't fall into the tag case - case 1: - tag = kAudioChannelLayoutTag_Mono; - break; - case 2: - tag = inChooseSurround ? kAudioChannelLayoutTag_Binaural : kAudioChannelLayoutTag_Stereo; - break; - case 4: - tag = inChooseSurround ? kAudioChannelLayoutTag_Ambisonic_B_Format : kAudioChannelLayoutTag_AudioUnit_4; - break; - case 5: - tag = inChooseSurround ? kAudioChannelLayoutTag_AudioUnit_5_0 : kAudioChannelLayoutTag_AudioUnit_5; - break; - case 6: - tag = inChooseSurround ? kAudioChannelLayoutTag_AudioUnit_6_0 : kAudioChannelLayoutTag_AudioUnit_6; - break; - case 7: - tag = kAudioChannelLayoutTag_AudioUnit_7_0; - break; - case 8: - tag = kAudioChannelLayoutTag_AudioUnit_8; - break; - } - - mLayout = RefCountedLayout::CreateWithLayoutTag(tag); -} - -//============================================================================= -// CAAudioChannelLayout::CAAudioChannelLayout -//============================================================================= -CAAudioChannelLayout::CAAudioChannelLayout (AudioChannelLayoutTag inLayoutTag) - : mLayout(NULL) -{ - SetWithTag(inLayoutTag); -} - -//============================================================================= -// CAAudioChannelLayout::CAAudioChannelLayout -//============================================================================= -CAAudioChannelLayout::CAAudioChannelLayout (const CAAudioChannelLayout &c) - : mLayout(NULL) -{ - *this = c; -} - - -//============================================================================= -// CAAudioChannelLayout::AudioChannelLayout -//============================================================================= -CAAudioChannelLayout::CAAudioChannelLayout (const AudioChannelLayout* inChannelLayout) - : mLayout(NULL) -{ - *this = inChannelLayout; -} - -//============================================================================= -// CAAudioChannelLayout::~CAAudioChannelLayout -//============================================================================= -CAAudioChannelLayout::~CAAudioChannelLayout () -{ - if (mLayout) { - mLayout->release(); - mLayout = NULL; - } -} - -//============================================================================= -// CAAudioChannelLayout::CAAudioChannelLayout -//============================================================================= -CAAudioChannelLayout& CAAudioChannelLayout::operator= (const CAAudioChannelLayout &c) -{ - if (mLayout != c.mLayout) { - if (mLayout) - mLayout->release(); - - if ((mLayout = c.mLayout) != NULL) - mLayout->retain(); - } - - return *this; -} - -CAAudioChannelLayout& CAAudioChannelLayout::operator= (const AudioChannelLayout* inChannelLayout) -{ - if (mLayout && &mLayout->Layout() == inChannelLayout) - return *this; - - if (mLayout) - mLayout->release(); - - if (inChannelLayout == NULL) - { - mLayout = RefCountedLayout::CreateWithNumberChannelDescriptions(0); - } - else - { - mLayout = RefCountedLayout::CreateWithLayout(inChannelLayout); - } - return *this; -} - -void CAAudioChannelLayout::SetWithTag(AudioChannelLayoutTag inTag) -{ - if (mLayout) - mLayout->release(); - - mLayout = RefCountedLayout::CreateWithLayoutTag(inTag); -} - -//============================================================================= -// CAAudioChannelLayout::operator== -//============================================================================= -bool CAAudioChannelLayout::operator== (const CAAudioChannelLayout &c) const -{ - if (mLayout == c.mLayout) - return true; - return Layout() == c.Layout(); -} - -//============================================================================= -// CAAudioChannelLayout::operator!= -//============================================================================= -bool CAAudioChannelLayout::operator!= (const CAAudioChannelLayout &c) const -{ - if (mLayout == c.mLayout) - return false; - - return !(Layout() == c.Layout()); -} - -//============================================================================= -// CAAudioChannelLayout::Print -//============================================================================= -void CAAudioChannelLayout::Print (FILE* file) const -{ - CAShowAudioChannelLayout (file, &Layout()); -} - diff --git a/src/CoreAudio/CoreAudioComponent/PublicUtility/CAAutoDisposer.h b/src/CoreAudio/CoreAudioComponent/PublicUtility/CAAutoDisposer.h deleted file mode 100644 index 2da241506..000000000 --- a/src/CoreAudio/CoreAudioComponent/PublicUtility/CAAutoDisposer.h +++ /dev/null @@ -1,508 +0,0 @@ -/* - File: CAAutoDisposer.h - Abstract: Part of CoreAudio Utility Classes - Version: 1.1 - - Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple - Inc. ("Apple") in consideration of your agreement to the following - terms, and your use, installation, modification or redistribution of - this Apple software constitutes acceptance of these terms. If you do - not agree with these terms, please do not use, install, modify or - redistribute this Apple software. - - In consideration of your agreement to abide by the following terms, and - subject to these terms, Apple grants you a personal, non-exclusive - license, under Apple's copyrights in this original Apple software (the - "Apple Software"), to use, reproduce, modify and redistribute the Apple - Software, with or without modifications, in source and/or binary forms; - provided that if you redistribute the Apple Software in its entirety and - without modifications, you must retain this notice and the following - text and disclaimers in all such redistributions of the Apple Software. - Neither the name, trademarks, service marks or logos of Apple Inc. may - be used to endorse or promote products derived from the Apple Software - without specific prior written permission from Apple. Except as - expressly stated in this notice, no other rights or licenses, express or - implied, are granted by Apple herein, including but not limited to any - patent rights that may be infringed by your derivative works or by other - works in which the Apple Software may be incorporated. - - The Apple Software is provided by Apple on an "AS IS" basis. APPLE - MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION - THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS - FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND - OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS. - - IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL - OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, - MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED - AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), - STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE - POSSIBILITY OF SUCH DAMAGE. - - Copyright (C) 2014 Apple Inc. All Rights Reserved. - -*/ -#if !defined(__CAPtr_h__) -#define __CAPtr_h__ - -#include // for malloc -#include // for bad_alloc -#include // for memset - -inline void* CA_malloc(size_t size) -{ - void* p = malloc(size); - if (!p && size) throw std::bad_alloc(); - return p; -} - -inline void* CA_realloc(void* old, size_t size) -{ -#if TARGET_OS_WIN32 - void* p = realloc(old, size); -#else - void* p = reallocf(old, size); // reallocf ensures the old pointer is freed if memory is full (p is NULL). -#endif - if (!p && size) throw std::bad_alloc(); - return p; -} - -#ifndef UINTPTR_MAX -#if __LP64__ -#define UINTPTR_MAX 18446744073709551615ULL -#else -#define UINTPTR_MAX 4294967295U -#endif -#endif - -inline void* CA_calloc(size_t n, size_t size) -{ - // ensure that multiplication will not overflow - if (n && UINTPTR_MAX / n < size) throw std::bad_alloc(); - - size_t nsize = n*size; - void* p = malloc(nsize); - if (!p && nsize) throw std::bad_alloc(); - - memset(p, 0, nsize); - return p; -} - - -// helper class for automatic conversions -template -struct CAPtrRef -{ - T* ptr_; - - explicit CAPtrRef(T* ptr) : ptr_(ptr) {} -}; - -template -class CAAutoFree -{ -private: - T* ptr_; - -public: - - CAAutoFree() : ptr_(0) {} - - explicit CAAutoFree(T* ptr) : ptr_(ptr) {} - - template - CAAutoFree(CAAutoFree& that) : ptr_(that.release()) {} // take ownership - - // C++ std says: a template constructor is never a copy constructor - CAAutoFree(CAAutoFree& that) : ptr_(that.release()) {} // take ownership - - CAAutoFree(size_t n, bool clear = false) - // this becomes an ambiguous call if n == 0 - : ptr_(0) - { - size_t maxItems = ~size_t(0) / sizeof(T); - if (n > maxItems) - throw std::bad_alloc(); - - ptr_ = static_cast(clear ? CA_calloc(n, sizeof(T)) : CA_malloc(n * sizeof(T))); - } - - ~CAAutoFree() { free(); } - - void alloc(size_t numItems, bool clear = false) - { - size_t maxItems = ~size_t(0) / sizeof(T); - if (numItems > maxItems) throw std::bad_alloc(); - - free(); - ptr_ = static_cast(clear ? CA_calloc(numItems, sizeof(T)) : CA_malloc(numItems * sizeof(T))); - } - - void allocBytes(size_t numBytes, bool clear = false) - { - free(); - ptr_ = static_cast(clear ? CA_calloc(1, numBytes) : CA_malloc(numBytes)); - } - - void reallocBytes(size_t numBytes) - { - ptr_ = static_cast(CA_realloc(ptr_, numBytes)); - } - - void reallocItems(size_t numItems) - { - size_t maxItems = ~size_t(0) / sizeof(T); - if (numItems > maxItems) throw std::bad_alloc(); - - ptr_ = static_cast(CA_realloc(ptr_, numItems * sizeof(T))); - } - - template - CAAutoFree& operator=(CAAutoFree& that) - { - set(that.release()); // take ownership - return *this; - } - - CAAutoFree& operator=(CAAutoFree& that) - { - set(that.release()); // take ownership - return *this; - } - - CAAutoFree& operator=(T* ptr) - { - set(ptr); - return *this; - } - - template - CAAutoFree& operator=(U* ptr) - { - set(ptr); - return *this; - } - - T& operator*() const { return *ptr_; } - T* operator->() const { return ptr_; } - - T* operator()() const { return ptr_; } - T* get() const { return ptr_; } - operator T*() const { return ptr_; } - - bool operator==(CAAutoFree const& that) const { return ptr_ == that.ptr_; } - bool operator!=(CAAutoFree const& that) const { return ptr_ != that.ptr_; } - bool operator==(T* ptr) const { return ptr_ == ptr; } - bool operator!=(T* ptr) const { return ptr_ != ptr; } - - T* release() - { - // release ownership - T* result = ptr_; - ptr_ = 0; - return result; - } - - void set(T* ptr) - { - if (ptr != ptr_) - { - ::free(ptr_); - ptr_ = ptr; - } - } - - void free() - { - set(0); - } - - - // automatic conversions to allow assignment from results of functions. - // hard to explain. see auto_ptr implementation and/or Josuttis' STL book. - CAAutoFree(CAPtrRef ref) : ptr_(ref.ptr_) { } - - CAAutoFree& operator=(CAPtrRef ref) - { - set(ref.ptr_); - return *this; - } - - template - operator CAPtrRef() - { return CAPtrRef(release()); } - - template - operator CAAutoFree() - { return CAAutoFree(release()); } - -}; - - -template -class CAAutoDelete -{ -private: - T* ptr_; - -public: - CAAutoDelete() : ptr_(0) {} - - explicit CAAutoDelete(T* ptr) : ptr_(ptr) {} - - template - CAAutoDelete(CAAutoDelete& that) : ptr_(that.release()) {} // take ownership - - // C++ std says: a template constructor is never a copy constructor - CAAutoDelete(CAAutoDelete& that) : ptr_(that.release()) {} // take ownership - - ~CAAutoDelete() { free(); } - - template - CAAutoDelete& operator=(CAAutoDelete& that) - { - set(that.release()); // take ownership - return *this; - } - - CAAutoDelete& operator=(CAAutoDelete& that) - { - set(that.release()); // take ownership - return *this; - } - - CAAutoDelete& operator=(T* ptr) - { - set(ptr); - return *this; - } - - template - CAAutoDelete& operator=(U* ptr) - { - set(ptr); - return *this; - } - - T& operator*() const { return *ptr_; } - T* operator->() const { return ptr_; } - - T* operator()() const { return ptr_; } - T* get() const { return ptr_; } - operator T*() const { return ptr_; } - - bool operator==(CAAutoDelete const& that) const { return ptr_ == that.ptr_; } - bool operator!=(CAAutoDelete const& that) const { return ptr_ != that.ptr_; } - bool operator==(T* ptr) const { return ptr_ == ptr; } - bool operator!=(T* ptr) const { return ptr_ != ptr; } - - T* release() - { - // release ownership - T* result = ptr_; - ptr_ = 0; - return result; - } - - void set(T* ptr) - { - if (ptr != ptr_) - { - delete ptr_; - ptr_ = ptr; - } - } - - void free() - { - set(0); - } - - - // automatic conversions to allow assignment from results of functions. - // hard to explain. see auto_ptr implementation and/or Josuttis' STL book. - CAAutoDelete(CAPtrRef ref) : ptr_(ref.ptr_) { } - - CAAutoDelete& operator=(CAPtrRef ref) - { - set(ref.ptr_); - return *this; - } - - template - operator CAPtrRef() - { return CAPtrRef(release()); } - - template - operator CAAutoFree() - { return CAAutoFree(release()); } - -}; - - -template -class CAAutoArrayDelete -{ -private: - T* ptr_; - -public: - CAAutoArrayDelete() : ptr_(0) {} - - explicit CAAutoArrayDelete(T* ptr) : ptr_(ptr) {} - - template - CAAutoArrayDelete(CAAutoArrayDelete& that) : ptr_(that.release()) {} // take ownership - - // C++ std says: a template constructor is never a copy constructor - CAAutoArrayDelete(CAAutoArrayDelete& that) : ptr_(that.release()) {} // take ownership - - // this becomes an ambiguous call if n == 0 - CAAutoArrayDelete(size_t n) : ptr_(new T[n]) {} - - ~CAAutoArrayDelete() { free(); } - - void alloc(size_t numItems) - { - free(); - ptr_ = new T [numItems]; - } - - template - CAAutoArrayDelete& operator=(CAAutoArrayDelete& that) - { - set(that.release()); // take ownership - return *this; - } - - CAAutoArrayDelete& operator=(CAAutoArrayDelete& that) - { - set(that.release()); // take ownership - return *this; - } - - CAAutoArrayDelete& operator=(T* ptr) - { - set(ptr); - return *this; - } - - template - CAAutoArrayDelete& operator=(U* ptr) - { - set(ptr); - return *this; - } - - T& operator*() const { return *ptr_; } - T* operator->() const { return ptr_; } - - T* operator()() const { return ptr_; } - T* get() const { return ptr_; } - operator T*() const { return ptr_; } - - bool operator==(CAAutoArrayDelete const& that) const { return ptr_ == that.ptr_; } - bool operator!=(CAAutoArrayDelete const& that) const { return ptr_ != that.ptr_; } - bool operator==(T* ptr) const { return ptr_ == ptr; } - bool operator!=(T* ptr) const { return ptr_ != ptr; } - - T* release() - { - // release ownership - T* result = ptr_; - ptr_ = 0; - return result; - } - - void set(T* ptr) - { - if (ptr != ptr_) - { - delete [] ptr_; - ptr_ = ptr; - } - } - - void free() - { - set(0); - } - - - // automatic conversions to allow assignment from results of functions. - // hard to explain. see auto_ptr implementation and/or Josuttis' STL book. - CAAutoArrayDelete(CAPtrRef ref) : ptr_(ref.ptr_) { } - - CAAutoArrayDelete& operator=(CAPtrRef ref) - { - set(ref.ptr_); - return *this; - } - - template - operator CAPtrRef() - { return CAPtrRef(release()); } - - template - operator CAAutoArrayDelete() - { return CAAutoFree(release()); } - -}; - - - - - -// convenience function -template -void free(CAAutoFree& p) -{ - p.free(); -} - -//////////////////////////////////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////////////////////////////////// - -#if 0 -// example program showing ownership transfer - -CAAutoFree source() -{ - // source allocates and returns ownership to the caller. - const char* str = "this is a test"; - size_t size = strlen(str) + 1; - CAAutoFree captr(size, false); - strlcpy(captr(), str, size); - printf("source %08X %08X '%s'\n", &captr, captr(), captr()); - return captr; -} - -void user(CAAutoFree const& captr) -{ - // passed by const reference. user can access the pointer but does not take ownership. - printf("user: %08X %08X '%s'\n", &captr, captr(), captr()); -} - -void sink(CAAutoFree captr) -{ - // passed by value. sink takes ownership and frees the pointer on return. - printf("sink: %08X %08X '%s'\n", &captr, captr(), captr()); -} - - -int main (int argc, char * const argv[]) -{ - - CAAutoFree captr(source()); - printf("main captr A %08X %08X\n", &captr, captr()); - user(captr); - sink(captr); - printf("main captr B %08X %08X\n", &captr, captr()); - return 0; -} -#endif - -#endif diff --git a/src/CoreAudio/CoreAudioComponent/PublicUtility/CABufferList.cpp b/src/CoreAudio/CoreAudioComponent/PublicUtility/CABufferList.cpp deleted file mode 100644 index 3249013b5..000000000 --- a/src/CoreAudio/CoreAudioComponent/PublicUtility/CABufferList.cpp +++ /dev/null @@ -1,259 +0,0 @@ -/* - File: CABufferList.cpp - Abstract: CABufferList.h - Version: 1.1 - - Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple - Inc. ("Apple") in consideration of your agreement to the following - terms, and your use, installation, modification or redistribution of - this Apple software constitutes acceptance of these terms. If you do - not agree with these terms, please do not use, install, modify or - redistribute this Apple software. - - In consideration of your agreement to abide by the following terms, and - subject to these terms, Apple grants you a personal, non-exclusive - license, under Apple's copyrights in this original Apple software (the - "Apple Software"), to use, reproduce, modify and redistribute the Apple - Software, with or without modifications, in source and/or binary forms; - provided that if you redistribute the Apple Software in its entirety and - without modifications, you must retain this notice and the following - text and disclaimers in all such redistributions of the Apple Software. - Neither the name, trademarks, service marks or logos of Apple Inc. may - be used to endorse or promote products derived from the Apple Software - without specific prior written permission from Apple. Except as - expressly stated in this notice, no other rights or licenses, express or - implied, are granted by Apple herein, including but not limited to any - patent rights that may be infringed by your derivative works or by other - works in which the Apple Software may be incorporated. - - The Apple Software is provided by Apple on an "AS IS" basis. APPLE - MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION - THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS - FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND - OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS. - - IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL - OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, - MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED - AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), - STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE - POSSIBILITY OF SUCH DAMAGE. - - Copyright (C) 2014 Apple Inc. All Rights Reserved. - -*/ -#include "CABufferList.h" -#include "CAByteOrder.h" - -void CABufferList::AllocateBuffers(UInt32 nBytes) -{ - if (nBytes <= GetNumBytes()) return; - - if (mABL.mNumberBuffers > 1) - // align successive buffers for Altivec and to take alternating - // cache line hits by spacing them by odd multiples of 16 - nBytes = ((nBytes + 15) & ~15) | 16; - UInt32 memorySize = nBytes * mABL.mNumberBuffers; - Byte *newMemory = new Byte[memorySize], *p = newMemory; - memset(newMemory, 0, memorySize); // get page faults now, not later - - AudioBuffer *buf = mABL.mBuffers; - for (UInt32 i = mABL.mNumberBuffers; i--; ++buf) { - if (buf->mData != NULL && buf->mDataByteSize > 0) - // preserve existing buffer contents - memcpy(p, buf->mData, buf->mDataByteSize); - buf->mDataByteSize = nBytes; - buf->mData = p; - p += nBytes; - } - Byte *oldMemory = mBufferMemory; - mBufferMemory = newMemory; - mBufferCapacity = nBytes; - delete[] oldMemory; -} - -void CABufferList::AllocateBuffersAndCopyFrom(UInt32 nBytes, CABufferList *inSrcList, CABufferList *inSetPtrList) -{ - if (mABL.mNumberBuffers != inSrcList->mABL.mNumberBuffers) return; - if (mABL.mNumberBuffers != inSetPtrList->mABL.mNumberBuffers) return; - if (nBytes <= GetNumBytes()) { - CopyAllFrom(inSrcList, inSetPtrList); - return; - } - inSetPtrList->VerifyNotTrashingOwnedBuffer(); - UInt32 fromByteSize = inSrcList->GetNumBytes(); - - if (mABL.mNumberBuffers > 1) - // align successive buffers for Altivec and to take alternating - // cache line hits by spacing them by odd multiples of 16 - nBytes = ((nBytes + 15) & ~15) | 16; - UInt32 memorySize = nBytes * mABL.mNumberBuffers; - Byte *newMemory = new Byte[memorySize], *p = newMemory; - memset(newMemory, 0, memorySize); // make buffer "hot" - - AudioBuffer *buf = mABL.mBuffers; - AudioBuffer *ptrBuf = inSetPtrList->mABL.mBuffers; - AudioBuffer *srcBuf = inSrcList->mABL.mBuffers; - for (UInt32 i = mABL.mNumberBuffers; i--; ++buf, ++ptrBuf, ++srcBuf) { - if (srcBuf->mData != NULL && srcBuf->mDataByteSize > 0) - // preserve existing buffer contents - memmove(p, srcBuf->mData, srcBuf->mDataByteSize); - buf->mDataByteSize = nBytes; - buf->mData = p; - ptrBuf->mDataByteSize = srcBuf->mDataByteSize; - ptrBuf->mData = p; - p += nBytes; - } - Byte *oldMemory = mBufferMemory; - mBufferMemory = newMemory; - mBufferCapacity = nBytes; - if (inSrcList != inSetPtrList) - inSrcList->BytesConsumed(fromByteSize); - delete[] oldMemory; -} - -void CABufferList::DeallocateBuffers() -{ - AudioBuffer *buf = mABL.mBuffers; - for (UInt32 i = mABL.mNumberBuffers; i--; ++buf) { - buf->mData = NULL; - buf->mDataByteSize = 0; - } - if (mBufferMemory != NULL) { - delete[] mBufferMemory; - mBufferMemory = NULL; - mBufferCapacity = 0; - } - -} - -static void show(const AudioBufferList &abl, int framesToPrint, int wordSize, const char *label, const char *fmtstr=NULL) -{ - printf("%s %p (%d fr%s):\n", label ? label : "AudioBufferList", &abl, framesToPrint, fmtstr ? fmtstr : ""); - const AudioBuffer *buf = abl.mBuffers; - for (UInt32 i = 0; i < abl.mNumberBuffers; ++i, ++buf) { - printf(" [%2d] %5dbytes %dch @ %p", (int)i, (int)buf->mDataByteSize, (int)buf->mNumberChannels, buf->mData); - if (framesToPrint && buf->mData != NULL) { - printf(":"); - Byte *p = (Byte *)buf->mData; - for (int j = framesToPrint * buf->mNumberChannels; --j >= 0; ) - switch (wordSize) { - case 0: // native float - printf(" %6.3f", *(Float32 *)p); - p += sizeof(Float32); - break; - // positive: big endian - case 1: - case -1: - printf(" %02X", *p); - p += 1; - break; - case 2: - printf(" %04X", CFSwapInt16BigToHost(*(UInt16 *)p)); - p += 2; - break; - case 3: - printf(" %06X", (p[0] << 16) | (p[1] << 8) | p[2]); - p += 3; - break; - case 4: - printf(" %08X", (unsigned int)CFSwapInt32BigToHost(*(UInt32 *)p)); - p += 4; - break; - case 10: - printf(" %6.3f", CASwapFloat32BigToHost(*(Float32 *)p)); - p += sizeof(Float32); - break; - case -2: - printf(" %04X", CFSwapInt16LittleToHost(*(UInt16 *)p)); - p += 2; - break; - case -3: - printf(" %06X", (p[2] << 16) | (p[1] << 8) | p[0]); - p += 3; - break; - case -4: - printf(" %08X", (unsigned int)CFSwapInt32LittleToHost(*(UInt32 *)p)); - p += 4; - break; - case -10: - printf(" %6.3f", CASwapFloat32LittleToHost(*(Float32 *)p)); - p += sizeof(Float32); - break; - } - } - printf("\n"); - } -} - -void CAShowAudioBufferList(const AudioBufferList &abl, int framesToPrint, const AudioStreamBasicDescription &asbd, const char *label) -{ - CAStreamBasicDescription fmt(asbd); - int wordSize = 1; - char fmtstr[80] = { 0 }; - - if (fmt.mFormatID == kAudioFormatLinearPCM) { - if (fmt.mFormatFlags & kLinearPCMFormatFlagIsFloat) { - if (fmt.mBitsPerChannel == 32) { - if (fmt.mFormatFlags & kLinearPCMFormatFlagIsBigEndian) { - wordSize = 10; - strlcpy(fmtstr, ", BEF", sizeof(fmtstr)); - } else { - wordSize = -10; - strlcpy(fmtstr, ", LEF", sizeof(fmtstr)); - } - } - } else { - wordSize = fmt.SampleWordSize(); - if (wordSize > 0) { - int fracbits = (asbd.mFormatFlags & kLinearPCMFormatFlagsSampleFractionMask) >> kLinearPCMFormatFlagsSampleFractionShift; - if (fracbits > 0) - snprintf(fmtstr, sizeof(fmtstr), ", %d.%d-bit", (int)asbd.mBitsPerChannel - fracbits, fracbits); - else - snprintf(fmtstr, sizeof(fmtstr), ", %d-bit", (int)asbd.mBitsPerChannel); - - if (!(fmt.mFormatFlags & kLinearPCMFormatFlagIsBigEndian)) { - wordSize = -wordSize; - strlcat(fmtstr, " LEI", sizeof(fmtstr)); - } else { - strlcat(fmtstr, " BEI", sizeof(fmtstr)); - } - } - } - } - show(abl, framesToPrint, wordSize, label, fmtstr); -} - -void CAShowAudioBufferList(const AudioBufferList &abl, int framesToPrint, int wordSize, const char *label) -{ - show(abl, framesToPrint, wordSize, label); -} - -extern "C" void CAShowAudioBufferList(const AudioBufferList *abl, int framesToPrint, int wordSize) -{ - show(*abl, framesToPrint, wordSize, NULL); -} - -// if the return result is odd, there was a null buffer. -extern "C" int CrashIfClientProvidedBogusAudioBufferList(const AudioBufferList *abl, bool nullok) -{ - const AudioBuffer *buf = abl->mBuffers, *bufend = buf + abl->mNumberBuffers; - int sum = 0; // defeat attempts by the compiler to optimize away the code that touches the buffers - int anyNull = 0; - for ( ; buf < bufend; ++buf) { - const int *p = (const int *)buf->mData; - if (p == NULL) { - anyNull = 1; - if (nullok) continue; - } - unsigned datasize = buf->mDataByteSize; - if (datasize >= sizeof(int) && p != NULL) { - sum += p[0]; - sum += p[datasize / sizeof(int) - 1]; - } - } - return anyNull | (sum & ~1); -} - diff --git a/src/CoreAudio/CoreAudioComponent/PublicUtility/CABufferList.h b/src/CoreAudio/CoreAudioComponent/PublicUtility/CABufferList.h deleted file mode 100644 index 72c93f862..000000000 --- a/src/CoreAudio/CoreAudioComponent/PublicUtility/CABufferList.h +++ /dev/null @@ -1,324 +0,0 @@ -/* - File: CABufferList.h - Abstract: Part of CoreAudio Utility Classes - Version: 1.1 - - Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple - Inc. ("Apple") in consideration of your agreement to the following - terms, and your use, installation, modification or redistribution of - this Apple software constitutes acceptance of these terms. If you do - not agree with these terms, please do not use, install, modify or - redistribute this Apple software. - - In consideration of your agreement to abide by the following terms, and - subject to these terms, Apple grants you a personal, non-exclusive - license, under Apple's copyrights in this original Apple software (the - "Apple Software"), to use, reproduce, modify and redistribute the Apple - Software, with or without modifications, in source and/or binary forms; - provided that if you redistribute the Apple Software in its entirety and - without modifications, you must retain this notice and the following - text and disclaimers in all such redistributions of the Apple Software. - Neither the name, trademarks, service marks or logos of Apple Inc. may - be used to endorse or promote products derived from the Apple Software - without specific prior written permission from Apple. Except as - expressly stated in this notice, no other rights or licenses, express or - implied, are granted by Apple herein, including but not limited to any - patent rights that may be infringed by your derivative works or by other - works in which the Apple Software may be incorporated. - - The Apple Software is provided by Apple on an "AS IS" basis. APPLE - MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION - THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS - FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND - OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS. - - IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL - OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, - MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED - AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), - STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE - POSSIBILITY OF SUCH DAMAGE. - - Copyright (C) 2014 Apple Inc. All Rights Reserved. - -*/ -#ifndef __CABufferList_h__ -#define __CABufferList_h__ - -#include -#include "CAStreamBasicDescription.h" -#include "CAXException.h" - -void CAShowAudioBufferList(const AudioBufferList &abl, int framesToPrint, const AudioStreamBasicDescription &fmt, const char *label=NULL); -void CAShowAudioBufferList(const AudioBufferList &abl, int framesToPrint, int wordSize, const char *label=NULL); -extern "C" void CAShowAudioBufferList(const AudioBufferList *abl, int framesToPrint, int wordSize); -extern "C" int CrashIfClientProvidedBogusAudioBufferList(const AudioBufferList *abl, bool nullOK=false); - -/* ____________________________________________________________________________ -// CABufferList - variable length buffer list - - This class is designed for use in non-simplistic cases. For AudioUnits, AUBufferList - is preferred. - - CABufferList can be used in one of two ways: - - as mutable pointers into non-owned memory - - as an immutable array of buffers (owns its own memory). - - All buffers are assumed to have the same format (number of channels, word size), so that - we can assume their mDataByteSizes are all the same. -____________________________________________________________________________ */ -class CABufferList { -public: - void * operator new(size_t /*size*/, int nBuffers) { - return ::operator new(sizeof(CABufferList) + (nBuffers-1) * sizeof(AudioBuffer)); - } - static CABufferList * New(const char *name, const CAStreamBasicDescription &format) - { - UInt32 numBuffers = format.NumberChannelStreams(), channelsPerBuffer = format.NumberInterleavedChannels(); - return new(numBuffers) CABufferList(name, numBuffers, channelsPerBuffer); - } - static CABufferList * New(const CAStreamBasicDescription &format) { return New("", format); } - - static CABufferList * New(UInt32 numBuffers, UInt32 channelsPerBuffer, const char *name="") { - return new(numBuffers) CABufferList(name, numBuffers, channelsPerBuffer); - } - -protected: - CABufferList(const char *name, UInt32 numBuffers, UInt32 channelsPerBuffer) : - mName(name), - mBufferMemory(NULL), - mBufferCapacity(0) - { - //XAssert(numBuffers > 0 /*&& channelsPerBuffer > 0*/); - mABL.mNumberBuffers = numBuffers; - AudioBuffer *buf = mABL.mBuffers; - for (UInt32 i = mABL.mNumberBuffers; i--; ++buf) { - buf->mNumberChannels = channelsPerBuffer; - buf->mDataByteSize = 0; - buf->mData = NULL; - } - } - -public: - ~CABufferList() - { - if (mBufferMemory) - delete[] mBufferMemory; - } - - const char * Name() { return mName; } - - const AudioBufferList & GetBufferList() const { return mABL; } - - AudioBufferList & GetModifiableBufferList() { return _GetBufferList(); } - - UInt32 GetNumberBuffers() const { return mABL.mNumberBuffers; } - - UInt32 GetNumBytes() const - { - return mABL.mBuffers[0].mDataByteSize; - } - - void SetBytes(UInt32 nBytes, void *data) - { - VerifyNotTrashingOwnedBuffer(); - XAssert(mABL.mNumberBuffers == 1); - mABL.mBuffers[0].mDataByteSize = nBytes; - mABL.mBuffers[0].mData = data; - } - - void CopyAllFrom(CABufferList *srcbl, CABufferList *ptrbl) - // copies bytes from srcbl - // make ptrbl reflect the length copied - // note that srcbl may be same as ptrbl! - { - // Note that this buffer *can* own memory and its pointers/lengths are not - // altered; only its buffer contents, which are copied from srcbl. - // The pointers/lengths in ptrbl are updated to reflect the addresses/lengths - // of the copied data, and srcbl's contents are consumed. - ptrbl->VerifyNotTrashingOwnedBuffer(); - UInt32 nBytes = srcbl->GetNumBytes(); - AudioBuffer *mybuf = mABL.mBuffers, *srcbuf = srcbl->mABL.mBuffers, - *ptrbuf = ptrbl->mABL.mBuffers; - for (UInt32 i = mABL.mNumberBuffers; i--; ++mybuf, ++srcbuf, ++ptrbuf) { - memmove(mybuf->mData, srcbuf->mData, srcbuf->mDataByteSize); - ptrbuf->mData = mybuf->mData; - ptrbuf->mDataByteSize = srcbuf->mDataByteSize; - } - if (srcbl != ptrbl) - srcbl->BytesConsumed(nBytes); - } - - // copies data from another buffer list. - void CopyDataFrom(const AudioBufferList &other) - { - for (unsigned i = 0; i < other.mNumberBuffers; ++i) { - XAssert(mBufferCapacity == 0 || other.mBuffers[i].mDataByteSize <= mBufferCapacity); - memcpy(mABL.mBuffers[i].mData, other.mBuffers[i].mData, - mABL.mBuffers[i].mDataByteSize = other.mBuffers[i].mDataByteSize); - } - } - - void AppendFrom(CABufferList *blp, UInt32 nBytes) - { - // this may mutate a buffer that owns memory. - AudioBuffer *mybuf = mABL.mBuffers, *srcbuf = blp->mABL.mBuffers; - for (UInt32 i = mABL.mNumberBuffers; i--; ++mybuf, ++srcbuf) { - XAssert(nBytes <= srcbuf->mDataByteSize); - XAssert(mBufferCapacity == 0 || mybuf->mDataByteSize + nBytes <= mBufferCapacity); - memcpy((Byte *)mybuf->mData + mybuf->mDataByteSize, srcbuf->mData, nBytes); - mybuf->mDataByteSize += nBytes; - } - blp->BytesConsumed(nBytes); - } - - void PadWithZeroes(UInt32 desiredBufferSize) - // for cases where an algorithm (e.g. SRC) requires some - // padding to create silence following end-of-file - { - XAssert(mBufferCapacity == 0 || desiredBufferSize <= mBufferCapacity); - if (GetNumBytes() > desiredBufferSize) return; - AudioBuffer *buf = mABL.mBuffers; - for (UInt32 i = mABL.mNumberBuffers; i--; ++buf) { - memset((Byte *)buf->mData + buf->mDataByteSize, 0, desiredBufferSize - buf->mDataByteSize); - buf->mDataByteSize = desiredBufferSize; - } - } - - void SetToZeroes(UInt32 nBytes) - { - XAssert(mBufferCapacity == 0 || nBytes <= mBufferCapacity); - AudioBuffer *buf = mABL.mBuffers; - for (UInt32 i = mABL.mNumberBuffers; i--; ++buf) { - memset((Byte *)buf->mData, 0, nBytes); - buf->mDataByteSize = nBytes; - } - } - - void Reset() - { - DeallocateBuffers(); - } - - Boolean SameDataAs(const CABufferList* anotherBufferList) - { - // check to see if two buffer lists point to the same memory. - if (mABL.mNumberBuffers != anotherBufferList->mABL.mNumberBuffers) return false; - - for (UInt32 i = 0; i < mABL.mNumberBuffers; ++i) { - if (mABL.mBuffers[i].mData != anotherBufferList->mABL.mBuffers[i].mData) return false; - } - return true; - } - - void BytesConsumed(UInt32 nBytes) - // advance buffer pointers, decrease buffer sizes - { - VerifyNotTrashingOwnedBuffer(); - AudioBuffer *buf = mABL.mBuffers; - for (UInt32 i = mABL.mNumberBuffers; i--; ++buf) { - XAssert(nBytes <= buf->mDataByteSize); - buf->mData = (Byte *)buf->mData + nBytes; - buf->mDataByteSize -= nBytes; - } - } - - void SetFrom(const AudioBufferList *abl) - { - VerifyNotTrashingOwnedBuffer(); - memcpy(&_GetBufferList(), abl, (char *)&abl->mBuffers[abl->mNumberBuffers] - (char *)abl); - } - - void SetFrom(const CABufferList *blp) - { - SetFrom(&blp->GetBufferList()); - } - - void SetFrom(const AudioBufferList *abl, UInt32 nBytes) - { - VerifyNotTrashingOwnedBuffer(); - AudioBuffer *mybuf = mABL.mBuffers; - const AudioBuffer *srcbuf = abl->mBuffers; - for (UInt32 i = mABL.mNumberBuffers; i--; ++mybuf, ++srcbuf) { - mybuf->mNumberChannels = srcbuf->mNumberChannels; - mybuf->mDataByteSize = nBytes; - mybuf->mData = srcbuf->mData; - } - } - - void SetFrom(const CABufferList *blp, UInt32 nBytes) - { - SetFrom(&blp->GetBufferList(), nBytes); - } - - AudioBufferList * ToAudioBufferList(AudioBufferList *abl) const - { - memcpy(abl, &GetBufferList(), (char *)&abl->mBuffers[mABL.mNumberBuffers] - (char *)abl); - return abl; - } - - void AllocateBuffers(UInt32 nBytes); - void AllocateBuffersAndCopyFrom(UInt32 nBytes, CABufferList *inCopyFromList, CABufferList *inSetPtrList); - - void DeallocateBuffers(); - - void UseExternalBuffer(Byte *ptr, UInt32 nBytes); - - void AdvanceBufferPointers(UInt32 nBytes) // $$$ ReducingSize - // this is for bufferlists that function simply as - // an array of pointers into another bufferlist, being advanced, - // as in RenderOutput implementations - { - VerifyNotTrashingOwnedBuffer(); - AudioBuffer *buf = mABL.mBuffers; - for (UInt32 i = mABL.mNumberBuffers; i--; ++buf) { - buf->mData = (Byte *)buf->mData + nBytes; - buf->mDataByteSize -= nBytes; - } - } - - void SetNumBytes(UInt32 nBytes) - { - XAssert(mBufferCapacity == 0 || nBytes <= mBufferCapacity); - AudioBuffer *buf = mABL.mBuffers; - for (UInt32 i = mABL.mNumberBuffers; i--; ++buf) - buf->mDataByteSize = nBytes; - } - - void Print(const char *label=NULL, int nframes=0, int wordSize=0) const - { - if (label == NULL) - label = mName; - printf("%s - ", label); - CAShowAudioBufferList(&GetBufferList(), nframes, wordSize); - if (mBufferMemory) - printf(" owned memory @ 0x%p:\n", mBufferMemory); - } - - UInt32 GetCapacityBytes() const { return mBufferCapacity; } - - template - T* GetData(UInt32 inBuffer) { - return static_cast(mABL.mBuffers[inBuffer].mData); - } - -protected: - AudioBufferList & _GetBufferList() { return mABL; } // use with care - // if we make this public, then we lose ability to call VerifyNotTrashingOwnedBuffer - void VerifyNotTrashingOwnedBuffer() - { - // This needs to be called from places where we are modifying the buffer pointers. - // It's an error to modify the buffer pointers or lengths if we own the buffer memory. - XAssert(mBufferMemory == NULL); - } - - const char * mName; // for debugging - Byte * mBufferMemory; - UInt32 mBufferCapacity; // max mDataByteSize of each buffer - AudioBufferList mABL; - // don't add anything here -}; - -#endif // __CABufferList_h__ diff --git a/src/CoreAudio/CoreAudioComponent/PublicUtility/CAByteOrder.h b/src/CoreAudio/CoreAudioComponent/PublicUtility/CAByteOrder.h deleted file mode 100644 index 9a56c6d85..000000000 --- a/src/CoreAudio/CoreAudioComponent/PublicUtility/CAByteOrder.h +++ /dev/null @@ -1,161 +0,0 @@ -/* - File: CAByteOrder.h - Abstract: Part of CoreAudio Utility Classes - Version: 1.1 - - Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple - Inc. ("Apple") in consideration of your agreement to the following - terms, and your use, installation, modification or redistribution of - this Apple software constitutes acceptance of these terms. If you do - not agree with these terms, please do not use, install, modify or - redistribute this Apple software. - - In consideration of your agreement to abide by the following terms, and - subject to these terms, Apple grants you a personal, non-exclusive - license, under Apple's copyrights in this original Apple software (the - "Apple Software"), to use, reproduce, modify and redistribute the Apple - Software, with or without modifications, in source and/or binary forms; - provided that if you redistribute the Apple Software in its entirety and - without modifications, you must retain this notice and the following - text and disclaimers in all such redistributions of the Apple Software. - Neither the name, trademarks, service marks or logos of Apple Inc. may - be used to endorse or promote products derived from the Apple Software - without specific prior written permission from Apple. Except as - expressly stated in this notice, no other rights or licenses, express or - implied, are granted by Apple herein, including but not limited to any - patent rights that may be infringed by your derivative works or by other - works in which the Apple Software may be incorporated. - - The Apple Software is provided by Apple on an "AS IS" basis. APPLE - MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION - THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS - FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND - OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS. - - IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL - OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, - MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED - AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), - STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE - POSSIBILITY OF SUCH DAMAGE. - - Copyright (C) 2014 Apple Inc. All Rights Reserved. - -*/ -#if !defined(__CAByteOrder_h__) -#define __CAByteOrder_h__ - -//============================================================================= -// Includes -//============================================================================= - -// System Includes -#if !defined(__COREAUDIO_USE_FLAT_INCLUDES__) - #include -#else - #include "CoreFoundation.h" -#endif - - -#if defined(__cplusplus) -extern "C" { -#endif - -CF_INLINE Float32 CASwapFloat32 (Float32 arg) { - union { - Float32 f; - UInt32 i; - } flip; - - flip.f = arg; - flip.i = CFSwapInt32 (flip.i); - - return flip.f; -} - -CF_INLINE Float64 CASwapFloat64 (Float64 arg) { - union { - Float64 f; - UInt64 i; - } flip; - - flip.f = arg; - flip.i = CFSwapInt64 (flip.i); - - return flip.f; -} - -#pragma mark -Flippers - -CF_INLINE Float32 CASwapFloat32BigToHost(Float32 arg) { -#if defined(__BIG_ENDIAN__) - return arg; -#else - return CASwapFloat32(arg); -#endif -} - -CF_INLINE Float64 CASwapFloat64BigToHost(Float64 arg) { -#if defined(__BIG_ENDIAN__) - return arg; -#else - return CASwapFloat64(arg); -#endif -} - -CF_INLINE Float32 CASwapFloat32HostToBig(Float32 arg) { -#if defined(__BIG_ENDIAN__) - return arg; -#else - return CASwapFloat32(arg); -#endif -} - -CF_INLINE Float64 CASwapFloat64HostToBig(Float64 arg) { -#if defined(__BIG_ENDIAN__) - return arg; -#else - return CASwapFloat64(arg); -#endif -} - -CF_INLINE Float32 CASwapFloat32LittleToHost(Float32 arg) { -#if defined(__LITTLE_ENDIAN__) - return arg; -#else - return CASwapFloat32(arg); -#endif -} - -CF_INLINE Float64 CASwapFloat64LittleToHost(Float64 arg) { -#if defined(__LITTLE_ENDIAN__) - return arg; -#else - return CASwapFloat64(arg); -#endif -} - -CF_INLINE Float32 CASwapFloat32HostToLittle(Float32 arg) { -#if defined(__LITTLE_ENDIAN__) - return arg; -#else - return CASwapFloat32(arg); -#endif -} - -CF_INLINE Float64 CASwapFloat64HostToLittle(Float64 arg) { -#if defined(__LITTLE_ENDIAN__) - return arg; -#else - return CASwapFloat64(arg); -#endif -} - - -#if defined(__cplusplus) -} -#endif - -#endif diff --git a/src/CoreAudio/CoreAudioComponent/PublicUtility/CADebugMacros.cpp b/src/CoreAudio/CoreAudioComponent/PublicUtility/CADebugMacros.cpp deleted file mode 100644 index 9739e3753..000000000 --- a/src/CoreAudio/CoreAudioComponent/PublicUtility/CADebugMacros.cpp +++ /dev/null @@ -1,90 +0,0 @@ -/* - File: CADebugMacros.cpp - Abstract: CADebugMacros.h - Version: 1.1 - - Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple - Inc. ("Apple") in consideration of your agreement to the following - terms, and your use, installation, modification or redistribution of - this Apple software constitutes acceptance of these terms. If you do - not agree with these terms, please do not use, install, modify or - redistribute this Apple software. - - In consideration of your agreement to abide by the following terms, and - subject to these terms, Apple grants you a personal, non-exclusive - license, under Apple's copyrights in this original Apple software (the - "Apple Software"), to use, reproduce, modify and redistribute the Apple - Software, with or without modifications, in source and/or binary forms; - provided that if you redistribute the Apple Software in its entirety and - without modifications, you must retain this notice and the following - text and disclaimers in all such redistributions of the Apple Software. - Neither the name, trademarks, service marks or logos of Apple Inc. may - be used to endorse or promote products derived from the Apple Software - without specific prior written permission from Apple. Except as - expressly stated in this notice, no other rights or licenses, express or - implied, are granted by Apple herein, including but not limited to any - patent rights that may be infringed by your derivative works or by other - works in which the Apple Software may be incorporated. - - The Apple Software is provided by Apple on an "AS IS" basis. APPLE - MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION - THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS - FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND - OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS. - - IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL - OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, - MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED - AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), - STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE - POSSIBILITY OF SUCH DAMAGE. - - Copyright (C) 2014 Apple Inc. All Rights Reserved. - -*/ -#include "CADebugMacros.h" -#include -#include -#if TARGET_API_MAC_OSX - #include -#endif - -#if DEBUG -#include - -void DebugPrint(const char *fmt, ...) -{ - va_list args; - va_start(args, fmt); - vprintf(fmt, args); - va_end(args); -} -#endif // DEBUG - -void LogError(const char *fmt, ...) -{ - va_list args; - va_start(args, fmt); -#if DEBUG - vprintf(fmt, args); -#endif -#if TARGET_API_MAC_OSX - vsyslog(LOG_ERR, fmt, args); -#endif - va_end(args); -} - -void LogWarning(const char *fmt, ...) -{ - va_list args; - va_start(args, fmt); -#if DEBUG - vprintf(fmt, args); -#endif -#if TARGET_API_MAC_OSX - vsyslog(LOG_WARNING, fmt, args); -#endif - va_end(args); -} diff --git a/src/CoreAudio/CoreAudioComponent/PublicUtility/CADebugMacros.h b/src/CoreAudio/CoreAudioComponent/PublicUtility/CADebugMacros.h deleted file mode 100644 index 15af91909..000000000 --- a/src/CoreAudio/CoreAudioComponent/PublicUtility/CADebugMacros.h +++ /dev/null @@ -1,581 +0,0 @@ -/* - File: CADebugMacros.h - Abstract: Part of CoreAudio Utility Classes - Version: 1.1 - - Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple - Inc. ("Apple") in consideration of your agreement to the following - terms, and your use, installation, modification or redistribution of - this Apple software constitutes acceptance of these terms. If you do - not agree with these terms, please do not use, install, modify or - redistribute this Apple software. - - In consideration of your agreement to abide by the following terms, and - subject to these terms, Apple grants you a personal, non-exclusive - license, under Apple's copyrights in this original Apple software (the - "Apple Software"), to use, reproduce, modify and redistribute the Apple - Software, with or without modifications, in source and/or binary forms; - provided that if you redistribute the Apple Software in its entirety and - without modifications, you must retain this notice and the following - text and disclaimers in all such redistributions of the Apple Software. - Neither the name, trademarks, service marks or logos of Apple Inc. may - be used to endorse or promote products derived from the Apple Software - without specific prior written permission from Apple. Except as - expressly stated in this notice, no other rights or licenses, express or - implied, are granted by Apple herein, including but not limited to any - patent rights that may be infringed by your derivative works or by other - works in which the Apple Software may be incorporated. - - The Apple Software is provided by Apple on an "AS IS" basis. APPLE - MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION - THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS - FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND - OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS. - - IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL - OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, - MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED - AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), - STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE - POSSIBILITY OF SUCH DAMAGE. - - Copyright (C) 2014 Apple Inc. All Rights Reserved. - -*/ -#if !defined(__CADebugMacros_h__) -#define __CADebugMacros_h__ - -//============================================================================= -// Includes -//============================================================================= - -#if !defined(__COREAUDIO_USE_FLAT_INCLUDES__) - #include -#else - #include "CoreAudioTypes.h" -#endif - -//============================================================================= -// CADebugMacros -//============================================================================= - -//#define CoreAudio_StopOnFailure 1 -//#define CoreAudio_TimeStampMessages 1 -//#define CoreAudio_ThreadStampMessages 1 -//#define CoreAudio_FlushDebugMessages 1 - -#if TARGET_RT_BIG_ENDIAN - #define CA4CCToCString(the4CC) { ((char*)&the4CC)[0], ((char*)&the4CC)[1], ((char*)&the4CC)[2], ((char*)&the4CC)[3], 0 } - #define CACopy4CCToCString(theCString, the4CC) { theCString[0] = ((char*)&the4CC)[0]; theCString[1] = ((char*)&the4CC)[1]; theCString[2] = ((char*)&the4CC)[2]; theCString[3] = ((char*)&the4CC)[3]; theCString[4] = 0; } -#else - #define CA4CCToCString(the4CC) { ((char*)&the4CC)[3], ((char*)&the4CC)[2], ((char*)&the4CC)[1], ((char*)&the4CC)[0], 0 } - #define CACopy4CCToCString(theCString, the4CC) { theCString[0] = ((char*)&the4CC)[3]; theCString[1] = ((char*)&the4CC)[2]; theCString[2] = ((char*)&the4CC)[1]; theCString[3] = ((char*)&the4CC)[0]; theCString[4] = 0; } -#endif - -// This is a macro that does a sizeof and casts the result to a UInt32. This is useful for all the -// places where -wshorten64-32 catches assigning a sizeof expression to a UInt32. -// For want of a better place to park this, we'll park it here. -#define SizeOf32(X) ((UInt32)sizeof(X)) - -// This is a macro that does a offsetof and casts the result to a UInt32. This is useful for all the -// places where -wshorten64-32 catches assigning an offsetof expression to a UInt32. -// For want of a better place to park this, we'll park it here. -#define OffsetOf32(X, Y) ((UInt32)offsetof(X, Y)) - -// This macro casts the expression to a UInt32. It is called out specially to allow us to track casts -// that have been added purely to avert -wshorten64-32 warnings on 64 bit platforms. -// For want of a better place to park this, we'll park it here. -#define ToUInt32(X) ((UInt32)(X)) -#define ToSInt32(X) ((SInt32)(X)) - -#pragma mark Basic Definitions - -#if DEBUG || CoreAudio_Debug - // can be used to break into debugger immediately, also see CADebugger - #define BusError() { long* p=NULL; *p=0; } - - // basic debugging print routines - #if TARGET_OS_MAC && !TARGET_API_MAC_CARBON - extern void DebugStr(const unsigned char* debuggerMsg); - #define DebugMessage(msg) DebugStr("\p"msg) - #define DebugMessageN1(msg, N1) - #define DebugMessageN2(msg, N1, N2) - #define DebugMessageN3(msg, N1, N2, N3) - #else - #include "CADebugPrintf.h" - - #if (CoreAudio_FlushDebugMessages && !CoreAudio_UseSysLog) || defined(CoreAudio_UseSideFile) - #define FlushRtn ,fflush(DebugPrintfFile) - #else - #define FlushRtn - #endif - - #if CoreAudio_ThreadStampMessages - #include - #include "CAHostTimeBase.h" - #if TARGET_RT_64_BIT - #define DebugPrintfThreadIDFormat "%16p" - #else - #define DebugPrintfThreadIDFormat "%8p" - #endif - #define DebugMsg(inFormat, ...) DebugPrintf("%17qd: " DebugPrintfThreadIDFormat " " inFormat, CAHostTimeBase::GetCurrentTimeInNanos(), pthread_self(), ## __VA_ARGS__) FlushRtn - #elif CoreAudio_TimeStampMessages - #include "CAHostTimeBase.h" - #define DebugMsg(inFormat, ...) DebugPrintf("%17qd: " inFormat, CAHostTimeBase::GetCurrentTimeInNanos(), ## __VA_ARGS__) FlushRtn - #else - #define DebugMsg(inFormat, ...) DebugPrintf(inFormat, ## __VA_ARGS__) FlushRtn - #endif - #endif - void DebugPrint(const char *fmt, ...); // can be used like printf - #ifndef DEBUGPRINT - #define DEBUGPRINT(msg) DebugPrint msg // have to double-parenthesize arglist (see Debugging.h) - #endif - #if VERBOSE - #define vprint(msg) DEBUGPRINT(msg) - #else - #define vprint(msg) - #endif - - // Original macro keeps its function of turning on and off use of CADebuggerStop() for both asserts and throws. - // For backwards compat, it overrides any setting of the two sub-macros. - #if CoreAudio_StopOnFailure - #include "CADebugger.h" - #undef CoreAudio_StopOnAssert - #define CoreAudio_StopOnAssert 1 - #undef CoreAudio_StopOnThrow - #define CoreAudio_StopOnThrow 1 - #define STOP CADebuggerStop() - #else - #define STOP - #endif - - #if CoreAudio_StopOnAssert - #if !CoreAudio_StopOnFailure - #include "CADebugger.h" - #define STOP - #endif - #define __ASSERT_STOP CADebuggerStop() - #else - #define __ASSERT_STOP - #endif - - #if CoreAudio_StopOnThrow - #if !CoreAudio_StopOnFailure - #include "CADebugger.h" - #define STOP - #endif - #define __THROW_STOP CADebuggerStop() - #else - #define __THROW_STOP - #endif - -#else - #define DebugMsg(inFormat, ...) - #ifndef DEBUGPRINT - #define DEBUGPRINT(msg) - #endif - #define vprint(msg) - #define STOP - #define __ASSERT_STOP - #define __THROW_STOP -#endif - -// Old-style numbered DebugMessage calls are implemented in terms of DebugMsg() now -#define DebugMessage(msg) DebugMsg(msg) -#define DebugMessageN1(msg, N1) DebugMsg(msg, N1) -#define DebugMessageN2(msg, N1, N2) DebugMsg(msg, N1, N2) -#define DebugMessageN3(msg, N1, N2, N3) DebugMsg(msg, N1, N2, N3) -#define DebugMessageN4(msg, N1, N2, N3, N4) DebugMsg(msg, N1, N2, N3, N4) -#define DebugMessageN5(msg, N1, N2, N3, N4, N5) DebugMsg(msg, N1, N2, N3, N4, N5) -#define DebugMessageN6(msg, N1, N2, N3, N4, N5, N6) DebugMsg(msg, N1, N2, N3, N4, N5, N6) -#define DebugMessageN7(msg, N1, N2, N3, N4, N5, N6, N7) DebugMsg(msg, N1, N2, N3, N4, N5, N6, N7) -#define DebugMessageN8(msg, N1, N2, N3, N4, N5, N6, N7, N8) DebugMsg(msg, N1, N2, N3, N4, N5, N6, N7, N8) -#define DebugMessageN9(msg, N1, N2, N3, N4, N5, N6, N7, N8, N9) DebugMsg(msg, N1, N2, N3, N4, N5, N6, N7, N8, N9) - -void LogError(const char *fmt, ...); // writes to syslog (and stderr if debugging) -void LogWarning(const char *fmt, ...); // writes to syslog (and stderr if debugging) - -#define NO_ACTION (void)0 - -#if DEBUG || CoreAudio_Debug - -#pragma mark Debug Macros - -#define Assert(inCondition, inMessage) \ - if(!(inCondition)) \ - { \ - DebugMessage(inMessage); \ - __ASSERT_STOP; \ - } - -#define AssertFileLine(inCondition, inMessage) \ - if(!(inCondition)) \ - { \ - DebugMessageN3("%s, line %d: %s", __FILE__, __LINE__, inMessage); \ - __ASSERT_STOP; \ - } - -#define AssertNoError(inError, inMessage) \ - { \ - SInt32 __Err = (inError); \ - if(__Err != 0) \ - { \ - char __4CC[5] = CA4CCToCString(__Err); \ - DebugMessageN2(inMessage ", Error: %d (%s)", (int)__Err, __4CC); \ - __ASSERT_STOP; \ - } \ - } - -#define AssertNoKernelError(inError, inMessage) \ - { \ - unsigned int __Err = (unsigned int)(inError); \ - if(__Err != 0) \ - { \ - DebugMessageN1(inMessage ", Error: 0x%X", __Err); \ - __ASSERT_STOP; \ - } \ - } - -#define AssertNotNULL(inPtr, inMessage) \ - { \ - if((inPtr) == NULL) \ - { \ - DebugMessage(inMessage); \ - __ASSERT_STOP; \ - } \ - } - -#define FailIf(inCondition, inHandler, inMessage) \ - if(inCondition) \ - { \ - DebugMessage(inMessage); \ - STOP; \ - goto inHandler; \ - } - -#define FailWithAction(inCondition, inAction, inHandler, inMessage) \ - if(inCondition) \ - { \ - DebugMessage(inMessage); \ - STOP; \ - { inAction; } \ - goto inHandler; \ - } - -#define FailIfNULL(inPointer, inAction, inHandler, inMessage) \ - if((inPointer) == NULL) \ - { \ - DebugMessage(inMessage); \ - STOP; \ - { inAction; } \ - goto inHandler; \ - } - -#define FailIfKernelError(inKernelError, inAction, inHandler, inMessage) \ - { \ - unsigned int __Err = (inKernelError); \ - if(__Err != 0) \ - { \ - DebugMessageN1(inMessage ", Error: 0x%X", __Err); \ - STOP; \ - { inAction; } \ - goto inHandler; \ - } \ - } - -#define FailIfError(inError, inAction, inHandler, inMessage) \ - { \ - SInt32 __Err = (inError); \ - if(__Err != 0) \ - { \ - char __4CC[5] = CA4CCToCString(__Err); \ - DebugMessageN2(inMessage ", Error: %ld (%s)", (long int)__Err, __4CC); \ - STOP; \ - { inAction; } \ - goto inHandler; \ - } \ - } - -#define FailIfNoMessage(inCondition, inHandler, inMessage) \ - if(inCondition) \ - { \ - STOP; \ - goto inHandler; \ - } - -#define FailWithActionNoMessage(inCondition, inAction, inHandler, inMessage) \ - if(inCondition) \ - { \ - STOP; \ - { inAction; } \ - goto inHandler; \ - } - -#define FailIfNULLNoMessage(inPointer, inAction, inHandler, inMessage) \ - if((inPointer) == NULL) \ - { \ - STOP; \ - { inAction; } \ - goto inHandler; \ - } - -#define FailIfKernelErrorNoMessage(inKernelError, inAction, inHandler, inMessage) \ - { \ - unsigned int __Err = (inKernelError); \ - if(__Err != 0) \ - { \ - STOP; \ - { inAction; } \ - goto inHandler; \ - } \ - } - -#define FailIfErrorNoMessage(inError, inAction, inHandler, inMessage) \ - { \ - SInt32 __Err = (inError); \ - if(__Err != 0) \ - { \ - STOP; \ - { inAction; } \ - goto inHandler; \ - } \ - } - -#if defined(__cplusplus) - -#define Throw(inException) __THROW_STOP; throw (inException) - -#define ThrowIf(inCondition, inException, inMessage) \ - if(inCondition) \ - { \ - DebugMessage(inMessage); \ - Throw(inException); \ - } - -#define ThrowIfNULL(inPointer, inException, inMessage) \ - if((inPointer) == NULL) \ - { \ - DebugMessage(inMessage); \ - Throw(inException); \ - } - -#define ThrowIfKernelError(inKernelError, inException, inMessage) \ - { \ - int __Err = (inKernelError); \ - if(__Err != 0) \ - { \ - DebugMessageN1(inMessage ", Error: 0x%X", __Err); \ - Throw(inException); \ - } \ - } - -#define ThrowIfError(inError, inException, inMessage) \ - { \ - SInt32 __Err = (inError); \ - if(__Err != 0) \ - { \ - char __4CC[5] = CA4CCToCString(__Err); \ - DebugMessageN2(inMessage ", Error: %d (%s)", (int)__Err, __4CC); \ - Throw(inException); \ - } \ - } - -#if TARGET_OS_WIN32 -#define ThrowIfWinError(inError, inException, inMessage) \ - { \ - HRESULT __Err = (inError); \ - if(FAILED(__Err)) \ - { \ - DebugMessageN2(inMessage ", Code: %d, Facility: 0x%X", HRESULT_CODE(__Err), HRESULT_FACILITY(__Err)); \ - Throw(inException); \ - } \ - } -#endif - -#define SubclassResponsibility(inMethodName, inException) \ - { \ - DebugMessage(inMethodName": Subclasses must implement this method"); \ - Throw(inException); \ - } - -#endif // defined(__cplusplus) - -#else - -#pragma mark Release Macros - -#define Assert(inCondition, inMessage) \ - if(!(inCondition)) \ - { \ - __ASSERT_STOP; \ - } - -#define AssertFileLine(inCondition, inMessage) Assert(inCondition, inMessage) - -#define AssertNoError(inError, inMessage) \ - { \ - SInt32 __Err = (inError); \ - if(__Err != 0) \ - { \ - __ASSERT_STOP; \ - } \ - } - -#define AssertNoKernelError(inError, inMessage) \ - { \ - unsigned int __Err = (unsigned int)(inError); \ - if(__Err != 0) \ - { \ - __ASSERT_STOP; \ - } \ - } - -#define AssertNotNULL(inPtr, inMessage) \ - { \ - if((inPtr) == NULL) \ - { \ - __ASSERT_STOP; \ - } \ - } - -#define FailIf(inCondition, inHandler, inMessage) \ - if(inCondition) \ - { \ - STOP; \ - goto inHandler; \ - } - -#define FailWithAction(inCondition, inAction, inHandler, inMessage) \ - if(inCondition) \ - { \ - STOP; \ - { inAction; } \ - goto inHandler; \ - } - -#define FailIfNULL(inPointer, inAction, inHandler, inMessage) \ - if((inPointer) == NULL) \ - { \ - STOP; \ - { inAction; } \ - goto inHandler; \ - } - -#define FailIfKernelError(inKernelError, inAction, inHandler, inMessage) \ - if((inKernelError) != 0) \ - { \ - STOP; \ - { inAction; } \ - goto inHandler; \ - } - -#define FailIfError(inError, inAction, inHandler, inMessage) \ - if((inError) != 0) \ - { \ - STOP; \ - { inAction; } \ - goto inHandler; \ - } - -#define FailIfNoMessage(inCondition, inHandler, inMessage) \ - if(inCondition) \ - { \ - STOP; \ - goto inHandler; \ - } - -#define FailWithActionNoMessage(inCondition, inAction, inHandler, inMessage) \ - if(inCondition) \ - { \ - STOP; \ - { inAction; } \ - goto inHandler; \ - } - -#define FailIfNULLNoMessage(inPointer, inAction, inHandler, inMessage) \ - if((inPointer) == NULL) \ - { \ - STOP; \ - { inAction; } \ - goto inHandler; \ - } - -#define FailIfKernelErrorNoMessage(inKernelError, inAction, inHandler, inMessage) \ - { \ - unsigned int __Err = (inKernelError); \ - if(__Err != 0) \ - { \ - STOP; \ - { inAction; } \ - goto inHandler; \ - } \ - } - -#define FailIfErrorNoMessage(inError, inAction, inHandler, inMessage) \ - { \ - SInt32 __Err = (inError); \ - if(__Err != 0) \ - { \ - STOP; \ - { inAction; } \ - goto inHandler; \ - } \ - } - -#if defined(__cplusplus) - -#define Throw(inException) __THROW_STOP; throw (inException) - -#define ThrowIf(inCondition, inException, inMessage) \ - if(inCondition) \ - { \ - Throw(inException); \ - } - -#define ThrowIfNULL(inPointer, inException, inMessage) \ - if((inPointer) == NULL) \ - { \ - Throw(inException); \ - } - -#define ThrowIfKernelError(inKernelError, inException, inMessage) \ - { \ - int __Err = (inKernelError); \ - if(__Err != 0) \ - { \ - Throw(inException); \ - } \ - } - -#define ThrowIfError(inError, inException, inMessage) \ - { \ - SInt32 __Err = (inError); \ - if(__Err != 0) \ - { \ - Throw(inException); \ - } \ - } - -#if TARGET_OS_WIN32 -#define ThrowIfWinError(inError, inException, inMessage) \ - { \ - HRESULT __Err = (inError); \ - if(FAILED(__Err)) \ - { \ - Throw(inException); \ - } \ - } -#endif - -#define SubclassResponsibility(inMethodName, inException) \ - { \ - Throw(inException); \ - } - -#endif // defined(__cplusplus) - -#endif // DEBUG || CoreAudio_Debug - -#endif diff --git a/src/CoreAudio/CoreAudioComponent/PublicUtility/CADebugPrintf.cpp b/src/CoreAudio/CoreAudioComponent/PublicUtility/CADebugPrintf.cpp deleted file mode 100644 index d691de3cd..000000000 --- a/src/CoreAudio/CoreAudioComponent/PublicUtility/CADebugPrintf.cpp +++ /dev/null @@ -1,89 +0,0 @@ -/* - File: CADebugPrintf.cpp - Abstract: CADebugPrintf.h - Version: 1.1 - - Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple - Inc. ("Apple") in consideration of your agreement to the following - terms, and your use, installation, modification or redistribution of - this Apple software constitutes acceptance of these terms. If you do - not agree with these terms, please do not use, install, modify or - redistribute this Apple software. - - In consideration of your agreement to abide by the following terms, and - subject to these terms, Apple grants you a personal, non-exclusive - license, under Apple's copyrights in this original Apple software (the - "Apple Software"), to use, reproduce, modify and redistribute the Apple - Software, with or without modifications, in source and/or binary forms; - provided that if you redistribute the Apple Software in its entirety and - without modifications, you must retain this notice and the following - text and disclaimers in all such redistributions of the Apple Software. - Neither the name, trademarks, service marks or logos of Apple Inc. may - be used to endorse or promote products derived from the Apple Software - without specific prior written permission from Apple. Except as - expressly stated in this notice, no other rights or licenses, express or - implied, are granted by Apple herein, including but not limited to any - patent rights that may be infringed by your derivative works or by other - works in which the Apple Software may be incorporated. - - The Apple Software is provided by Apple on an "AS IS" basis. APPLE - MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION - THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS - FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND - OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS. - - IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL - OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, - MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED - AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), - STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE - POSSIBILITY OF SUCH DAMAGE. - - Copyright (C) 2014 Apple Inc. All Rights Reserved. - -*/ -//================================================================================================== -// Includes -//================================================================================================== - -// Self Include -#include "CADebugPrintf.h" - -#if DEBUG || CoreAudio_Debug - - #if TARGET_OS_WIN32 - #include - #include - #include - extern "C" - int CAWin32DebugPrintf(char* inFormat, ...) - { - char theMessage[1024]; - va_list theArguments; - va_start(theArguments, inFormat); - _vsnprintf(theMessage, 1024, inFormat, theArguments); - va_end(theArguments); - OutputDebugString(theMessage); - return 0; - } - #endif - - #if defined(CoreAudio_UseSideFile) - #include - FILE* sDebugPrintfSideFile = NULL; - extern "C" - void OpenDebugPrintfSideFile() - { - if(sDebugPrintfSideFile == NULL) - { - char theFileName[1024]; - snprintf(theFileName, sizeof(theFileName), CoreAudio_UseSideFile, getpid()); - sDebugPrintfSideFile = fopen(theFileName, "a+"); - DebugPrintfRtn(DebugPrintfFileComma "\n------------------------------\n"); - } - } - #endif - -#endif diff --git a/src/CoreAudio/CoreAudioComponent/PublicUtility/CADebugPrintf.h b/src/CoreAudio/CoreAudioComponent/PublicUtility/CADebugPrintf.h deleted file mode 100644 index 79aa15daf..000000000 --- a/src/CoreAudio/CoreAudioComponent/PublicUtility/CADebugPrintf.h +++ /dev/null @@ -1,115 +0,0 @@ -/* - File: CADebugPrintf.h - Abstract: Part of CoreAudio Utility Classes - Version: 1.1 - - Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple - Inc. ("Apple") in consideration of your agreement to the following - terms, and your use, installation, modification or redistribution of - this Apple software constitutes acceptance of these terms. If you do - not agree with these terms, please do not use, install, modify or - redistribute this Apple software. - - In consideration of your agreement to abide by the following terms, and - subject to these terms, Apple grants you a personal, non-exclusive - license, under Apple's copyrights in this original Apple software (the - "Apple Software"), to use, reproduce, modify and redistribute the Apple - Software, with or without modifications, in source and/or binary forms; - provided that if you redistribute the Apple Software in its entirety and - without modifications, you must retain this notice and the following - text and disclaimers in all such redistributions of the Apple Software. - Neither the name, trademarks, service marks or logos of Apple Inc. may - be used to endorse or promote products derived from the Apple Software - without specific prior written permission from Apple. Except as - expressly stated in this notice, no other rights or licenses, express or - implied, are granted by Apple herein, including but not limited to any - patent rights that may be infringed by your derivative works or by other - works in which the Apple Software may be incorporated. - - The Apple Software is provided by Apple on an "AS IS" basis. APPLE - MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION - THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS - FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND - OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS. - - IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL - OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, - MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED - AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), - STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE - POSSIBILITY OF SUCH DAMAGE. - - Copyright (C) 2014 Apple Inc. All Rights Reserved. - -*/ -#if !defined(__CADebugPrintf_h__) -#define __CADebugPrintf_h__ - -//============================================================================= -// Includes -//============================================================================= - -#if !defined(__COREAUDIO_USE_FLAT_INCLUDES__) - #include -#else - #include "CoreAudioTypes.h" -#endif - -//============================================================================= -// Macros to redirect debugging output to various logging services -//============================================================================= - -//#define CoreAudio_UseSysLog 1 -//#define CoreAudio_UseSideFile "/CoreAudio-%d.txt" - -#if DEBUG || CoreAudio_Debug - - #if TARGET_OS_WIN32 - #if defined(__cplusplus) - extern "C" - #endif - extern int CAWin32DebugPrintf(char* inFormat, ...); - #define DebugPrintfRtn CAWin32DebugPrintf - #define DebugPrintfFile - #define DebugPrintfLineEnding "\n" - #define DebugPrintfFileComma - #else - #if CoreAudio_UseSysLog - #include - #define DebugPrintfRtn syslog - #define DebugPrintfFile LOG_NOTICE - #define DebugPrintfLineEnding "" - #define DebugPrintfFileComma DebugPrintfFile, - #elif defined(CoreAudio_UseSideFile) - #include - #if defined(__cplusplus) - extern "C" - #endif - void OpenDebugPrintfSideFile(); - extern FILE* sDebugPrintfSideFile; - #define DebugPrintfRtn fprintf - #define DebugPrintfFile ((sDebugPrintfSideFile != NULL) ? sDebugPrintfSideFile : stderr) - #define DebugPrintfLineEnding "\n" - #define DebugPrintfFileComma DebugPrintfFile, - #else - #include - #define DebugPrintfRtn fprintf - #define DebugPrintfFile stderr - #define DebugPrintfLineEnding "\n" - #define DebugPrintfFileComma DebugPrintfFile, - #endif - #endif - - #define DebugPrintf(inFormat, ...) DebugPrintfRtn(DebugPrintfFileComma inFormat DebugPrintfLineEnding, ## __VA_ARGS__) -#else - #define DebugPrintfRtn - #define DebugPrintfFile - #define DebugPrintfLineEnding - #define DebugPrintfFileComma - #define DebugPrintf(inFormat, ...) -#endif - - -#endif diff --git a/src/CoreAudio/CoreAudioComponent/PublicUtility/CADebugger.cpp b/src/CoreAudio/CoreAudioComponent/PublicUtility/CADebugger.cpp deleted file mode 100644 index 7f0141d20..000000000 --- a/src/CoreAudio/CoreAudioComponent/PublicUtility/CADebugger.cpp +++ /dev/null @@ -1,103 +0,0 @@ -/* - File: CADebugger.cpp - Abstract: CADebugger.h - Version: 1.1 - - Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple - Inc. ("Apple") in consideration of your agreement to the following - terms, and your use, installation, modification or redistribution of - this Apple software constitutes acceptance of these terms. If you do - not agree with these terms, please do not use, install, modify or - redistribute this Apple software. - - In consideration of your agreement to abide by the following terms, and - subject to these terms, Apple grants you a personal, non-exclusive - license, under Apple's copyrights in this original Apple software (the - "Apple Software"), to use, reproduce, modify and redistribute the Apple - Software, with or without modifications, in source and/or binary forms; - provided that if you redistribute the Apple Software in its entirety and - without modifications, you must retain this notice and the following - text and disclaimers in all such redistributions of the Apple Software. - Neither the name, trademarks, service marks or logos of Apple Inc. may - be used to endorse or promote products derived from the Apple Software - without specific prior written permission from Apple. Except as - expressly stated in this notice, no other rights or licenses, express or - implied, are granted by Apple herein, including but not limited to any - patent rights that may be infringed by your derivative works or by other - works in which the Apple Software may be incorporated. - - The Apple Software is provided by Apple on an "AS IS" basis. APPLE - MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION - THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS - FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND - OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS. - - IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL - OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, - MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED - AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), - STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE - POSSIBILITY OF SUCH DAMAGE. - - Copyright (C) 2014 Apple Inc. All Rights Reserved. - -*/ -//============================================================================= -// Includes -//============================================================================= - -#include "CADebugger.h" - -//============================================================================= -// CADebugger -//============================================================================= - -#if TARGET_API_MAC_OSX - -#include -#include -#include - -bool CAIsDebuggerAttached(void) -{ - int mib[4]; - struct kinfo_proc info; - size_t size; - - mib[0] = CTL_KERN; - mib[1] = KERN_PROC; - mib[2] = KERN_PROC_PID; - mib[3] = getpid(); - size = sizeof(info); - info.kp_proc.p_flag = 0; - - sysctl(mib, 4, &info, &size, NULL, 0); - - return (info.kp_proc.p_flag & P_TRACED) == P_TRACED; -} - -#endif - -void CADebuggerStop(void) -{ - #if CoreAudio_Debug - #if TARGET_API_MAC_OSX - if(CAIsDebuggerAttached()) - { - #if defined(__i386__) || defined(__x86_64__) - asm("int3"); - #else - __builtin_trap(); - #endif - } - else - { - abort(); - } - #else - __debugbreak(); - #endif - #endif -} diff --git a/src/CoreAudio/CoreAudioComponent/PublicUtility/CADebugger.h b/src/CoreAudio/CoreAudioComponent/PublicUtility/CADebugger.h deleted file mode 100644 index 9391f011a..000000000 --- a/src/CoreAudio/CoreAudioComponent/PublicUtility/CADebugger.h +++ /dev/null @@ -1,69 +0,0 @@ -/* - File: CADebugger.h - Abstract: Part of CoreAudio Utility Classes - Version: 1.1 - - Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple - Inc. ("Apple") in consideration of your agreement to the following - terms, and your use, installation, modification or redistribution of - this Apple software constitutes acceptance of these terms. If you do - not agree with these terms, please do not use, install, modify or - redistribute this Apple software. - - In consideration of your agreement to abide by the following terms, and - subject to these terms, Apple grants you a personal, non-exclusive - license, under Apple's copyrights in this original Apple software (the - "Apple Software"), to use, reproduce, modify and redistribute the Apple - Software, with or without modifications, in source and/or binary forms; - provided that if you redistribute the Apple Software in its entirety and - without modifications, you must retain this notice and the following - text and disclaimers in all such redistributions of the Apple Software. - Neither the name, trademarks, service marks or logos of Apple Inc. may - be used to endorse or promote products derived from the Apple Software - without specific prior written permission from Apple. Except as - expressly stated in this notice, no other rights or licenses, express or - implied, are granted by Apple herein, including but not limited to any - patent rights that may be infringed by your derivative works or by other - works in which the Apple Software may be incorporated. - - The Apple Software is provided by Apple on an "AS IS" basis. APPLE - MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION - THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS - FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND - OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS. - - IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL - OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, - MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED - AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), - STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE - POSSIBILITY OF SUCH DAMAGE. - - Copyright (C) 2014 Apple Inc. All Rights Reserved. - -*/ -#if !defined(__CADebugger_h__) -#define __CADebugger_h__ - -//============================================================================= -// Includes -//============================================================================= - -#if !defined(__COREAUDIO_USE_FLAT_INCLUDES__) - #include -#else - #include -#endif - -//============================================================================= -// CADebugger -//============================================================================= - -#if TARGET_API_MAC_OSX - extern bool CAIsDebuggerAttached(void); -#endif -extern void CADebuggerStop(void); - -#endif diff --git a/src/CoreAudio/CoreAudioComponent/PublicUtility/CAException.h b/src/CoreAudio/CoreAudioComponent/PublicUtility/CAException.h deleted file mode 100644 index 7217001d7..000000000 --- a/src/CoreAudio/CoreAudioComponent/PublicUtility/CAException.h +++ /dev/null @@ -1,83 +0,0 @@ -/* - File: CAException.h - Abstract: Part of CoreAudio Utility Classes - Version: 1.1 - - Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple - Inc. ("Apple") in consideration of your agreement to the following - terms, and your use, installation, modification or redistribution of - this Apple software constitutes acceptance of these terms. If you do - not agree with these terms, please do not use, install, modify or - redistribute this Apple software. - - In consideration of your agreement to abide by the following terms, and - subject to these terms, Apple grants you a personal, non-exclusive - license, under Apple's copyrights in this original Apple software (the - "Apple Software"), to use, reproduce, modify and redistribute the Apple - Software, with or without modifications, in source and/or binary forms; - provided that if you redistribute the Apple Software in its entirety and - without modifications, you must retain this notice and the following - text and disclaimers in all such redistributions of the Apple Software. - Neither the name, trademarks, service marks or logos of Apple Inc. may - be used to endorse or promote products derived from the Apple Software - without specific prior written permission from Apple. Except as - expressly stated in this notice, no other rights or licenses, express or - implied, are granted by Apple herein, including but not limited to any - patent rights that may be infringed by your derivative works or by other - works in which the Apple Software may be incorporated. - - The Apple Software is provided by Apple on an "AS IS" basis. APPLE - MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION - THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS - FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND - OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS. - - IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL - OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, - MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED - AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), - STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE - POSSIBILITY OF SUCH DAMAGE. - - Copyright (C) 2014 Apple Inc. All Rights Reserved. - -*/ -#if !defined(__CAException_h__) -#define __CAException_h__ - -//============================================================================= -// Includes -//============================================================================= - -#if !defined(__COREAUDIO_USE_FLAT_INCLUDES__) - #include -#else - #include "CoreAudioTypes.h" -#endif - -//============================================================================= -// CAException -//============================================================================= - -class CAException -{ - -public: - CAException(OSStatus inError) : mError(inError) {} - CAException(const CAException& inException) : mError(inException.mError) {} - CAException& operator=(const CAException& inException) { mError = inException.mError; return *this; } - ~CAException() {} - - OSStatus GetError() const { return mError; } - -protected: - OSStatus mError; -}; - -#define CATry try{ -#define CACatch } catch(...) {} -#define CASwallowException(inExpression) try { inExpression; } catch(...) {} - -#endif diff --git a/src/CoreAudio/CoreAudioComponent/PublicUtility/CAGuard.cpp b/src/CoreAudio/CoreAudioComponent/PublicUtility/CAGuard.cpp deleted file mode 100644 index a1c83be9d..000000000 --- a/src/CoreAudio/CoreAudioComponent/PublicUtility/CAGuard.cpp +++ /dev/null @@ -1,343 +0,0 @@ -/* - File: CAGuard.cpp - Abstract: CAGuard.h - Version: 1.1 - - Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple - Inc. ("Apple") in consideration of your agreement to the following - terms, and your use, installation, modification or redistribution of - this Apple software constitutes acceptance of these terms. If you do - not agree with these terms, please do not use, install, modify or - redistribute this Apple software. - - In consideration of your agreement to abide by the following terms, and - subject to these terms, Apple grants you a personal, non-exclusive - license, under Apple's copyrights in this original Apple software (the - "Apple Software"), to use, reproduce, modify and redistribute the Apple - Software, with or without modifications, in source and/or binary forms; - provided that if you redistribute the Apple Software in its entirety and - without modifications, you must retain this notice and the following - text and disclaimers in all such redistributions of the Apple Software. - Neither the name, trademarks, service marks or logos of Apple Inc. may - be used to endorse or promote products derived from the Apple Software - without specific prior written permission from Apple. Except as - expressly stated in this notice, no other rights or licenses, express or - implied, are granted by Apple herein, including but not limited to any - patent rights that may be infringed by your derivative works or by other - works in which the Apple Software may be incorporated. - - The Apple Software is provided by Apple on an "AS IS" basis. APPLE - MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION - THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS - FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND - OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS. - - IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL - OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, - MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED - AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), - STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE - POSSIBILITY OF SUCH DAMAGE. - - Copyright (C) 2014 Apple Inc. All Rights Reserved. - -*/ -//================================================================================================== -// Includes -//================================================================================================== - -// Self Include -#include "CAGuard.h" - -#if TARGET_OS_MAC - #include -#endif - -// PublicUtility Inludes -#include "CADebugMacros.h" -#include "CAException.h" -#include "CAHostTimeBase.h" - -//================================================================================================== -// Logging -//================================================================================================== - -#if CoreAudio_Debug -// #define Log_Ownership 1 -// #define Log_WaitOwnership 1 -// #define Log_TimedWaits 1 -// #define Log_Latency 1 -// #define Log_Errors 1 -#endif - -//#warning Need a try-based Locker too -//================================================================================================== -// CAGuard -//================================================================================================== - -CAGuard::CAGuard(const char* inName) -: - CAMutex(inName) -#if Log_Average_Latency - ,mAverageLatencyAccumulator(0.0), - mAverageLatencyCount(0) -#endif -{ -#if TARGET_OS_MAC - OSStatus theError = pthread_cond_init(&mCondVar, NULL); - ThrowIf(theError != 0, CAException(theError), "CAGuard::CAGuard: Could not init the cond var"); -#elif TARGET_OS_WIN32 - mEvent = CreateEvent(NULL, true, false, NULL); - ThrowIfNULL(mEvent, CAException(GetLastError()), "CAGuard::CAGuard: Could not create the event"); -#endif -} - -CAGuard::~CAGuard() -{ -#if TARGET_OS_MAC - pthread_cond_destroy(&mCondVar); -#elif TARGET_OS_WIN32 - if(mEvent != NULL) - { - CloseHandle(mEvent); - } -#endif -} - -void CAGuard::Wait() -{ -#if TARGET_OS_MAC - ThrowIf(!pthread_equal(pthread_self(), mOwner), CAException(1), "CAGuard::Wait: A thread has to have locked a guard before it can wait"); - - mOwner = 0; - - #if Log_WaitOwnership - DebugPrintfRtn(DebugPrintfFileComma "%p %.4f: CAGuard::Wait: thread %p is waiting on %s, owner: %p\n", pthread_self(), ((Float64)(CAHostTimeBase::GetCurrentTimeInNanos()) / 1000000.0), pthread_self(), mName, mOwner); - #endif - - OSStatus theError = pthread_cond_wait(&mCondVar, &mMutex); - ThrowIf(theError != 0, CAException(theError), "CAGuard::Wait: Could not wait for a signal"); - mOwner = pthread_self(); - - #if Log_WaitOwnership - DebugPrintfRtn(DebugPrintfFileComma "%p %.4f: CAGuard::Wait: thread %p waited on %s, owner: %p\n", pthread_self(), ((Float64)(CAHostTimeBase::GetCurrentTimeInNanos()) / 1000000.0), pthread_self(), mName, mOwner); - #endif -#elif TARGET_OS_WIN32 - ThrowIf(GetCurrentThreadId() != mOwner, CAException(1), "CAGuard::Wait: A thread has to have locked a guard before it can wait"); - - mOwner = 0; - - #if Log_WaitOwnership - DebugPrintfRtn(DebugPrintfFileComma "%lu %.4f: CAGuard::Wait: thread %lu is waiting on %s, owner: %lu\n", GetCurrentThreadId(), ((Float64)(CAHostTimeBase::GetCurrentTimeInNanos()) / 1000000.0), GetCurrentThreadId(), mName, mOwner); - #endif - - ReleaseMutex(mMutex); - HANDLE theHandles[] = { mMutex, mEvent }; - OSStatus theError = WaitForMultipleObjects(2, theHandles, true, INFINITE); - ThrowIfError(theError, CAException(GetLastError()), "CAGuard::Wait: Could not wait for the signal"); - mOwner = GetCurrentThreadId(); - ResetEvent(mEvent); - - #if Log_WaitOwnership - DebugPrintfRtn(DebugPrintfFileComma "%lu %.4f: CAGuard::Wait: thread %lu waited on %s, owner: %lu\n", GetCurrentThreadId(), ((Float64)(CAHostTimeBase::GetCurrentTimeInNanos()) / 1000000.0), GetCurrentThreadId(), mName, mOwner); - #endif -#endif -} - -bool CAGuard::WaitFor(UInt64 inNanos) -{ - bool theAnswer = false; - -#if TARGET_OS_MAC - ThrowIf(!pthread_equal(pthread_self(), mOwner), CAException(1), "CAGuard::WaitFor: A thread has to have locked a guard be for it can wait"); - - #if Log_TimedWaits - DebugMessageN1("CAGuard::WaitFor: waiting %.0f", (Float64)inNanos); - #endif - - struct timespec theTimeSpec; - static const UInt64 kNanosPerSecond = 1000000000ULL; - if(inNanos >= kNanosPerSecond) - { - theTimeSpec.tv_sec = static_cast(inNanos / kNanosPerSecond); - theTimeSpec.tv_nsec = static_cast(inNanos % kNanosPerSecond); - } - else - { - theTimeSpec.tv_sec = 0; - theTimeSpec.tv_nsec = static_cast(inNanos); - } - - #if Log_TimedWaits || Log_Latency || Log_Average_Latency - UInt64 theStartNanos = CAHostTimeBase::GetCurrentTimeInNanos(); - #endif - - mOwner = 0; - - #if Log_WaitOwnership - DebugPrintfRtn(DebugPrintfFileComma "%p %.4f: CAGuard::WaitFor: thread %p is waiting on %s, owner: %p\n", pthread_self(), ((Float64)(CAHostTimeBase::GetCurrentTimeInNanos()) / 1000000.0), pthread_self(), mName, mOwner); - #endif - - OSStatus theError = pthread_cond_timedwait_relative_np(&mCondVar, &mMutex, &theTimeSpec); - ThrowIf((theError != 0) && (theError != ETIMEDOUT), CAException(theError), "CAGuard::WaitFor: Wait got an error"); - mOwner = pthread_self(); - - #if Log_TimedWaits || Log_Latency || Log_Average_Latency - UInt64 theEndNanos = CAHostTimeBase::GetCurrentTimeInNanos(); - #endif - - #if Log_TimedWaits - DebugMessageN1("CAGuard::WaitFor: waited %.0f", (Float64)(theEndNanos - theStartNanos)); - #endif - - #if Log_Latency - DebugMessageN1("CAGuard::WaitFor: latency %.0f", (Float64)((theEndNanos - theStartNanos) - inNanos)); - #endif - - #if Log_Average_Latency - ++mAverageLatencyCount; - mAverageLatencyAccumulator += (theEndNanos - theStartNanos) - inNanos; - if(mAverageLatencyCount >= 50) - { - DebugMessageN2("CAGuard::WaitFor: average latency %.3f ns over %ld waits", mAverageLatencyAccumulator / mAverageLatencyCount, mAverageLatencyCount); - mAverageLatencyCount = 0; - mAverageLatencyAccumulator = 0.0; - } - #endif - - #if Log_WaitOwnership - DebugPrintfRtn(DebugPrintfFileComma "%p %.4f: CAGuard::WaitFor: thread %p waited on %s, owner: %p\n", pthread_self(), ((Float64)(CAHostTimeBase::GetCurrentTimeInNanos()) / 1000000.0), pthread_self(), mName, mOwner); - #endif - - theAnswer = theError == ETIMEDOUT; -#elif TARGET_OS_WIN32 - ThrowIf(GetCurrentThreadId() != mOwner, CAException(1), "CAGuard::WaitFor: A thread has to have locked a guard be for it can wait"); - - #if Log_TimedWaits - DebugMessageN1("CAGuard::WaitFor: waiting %.0f", (Float64)inNanos); - #endif - - // the time out is specified in milliseconds(!) - UInt32 theWaitTime = static_cast(inNanos / 1000000ULL); - - #if Log_TimedWaits || Log_Latency || Log_Average_Latency - UInt64 theStartNanos = CAHostTimeBase::GetCurrentTimeInNanos(); - #endif - - mOwner = 0; - - #if Log_WaitOwnership - DebugPrintfRtn(DebugPrintfFileComma "%lu %.4f: CAGuard::WaitFor: thread %lu is waiting on %s, owner: %lu\n", GetCurrentThreadId(), ((Float64)(CAHostTimeBase::GetCurrentTimeInNanos()) / 1000000.0), GetCurrentThreadId(), mName, mOwner); - #endif - - ReleaseMutex(mMutex); - HANDLE theHandles[] = { mMutex, mEvent }; - OSStatus theError = WaitForMultipleObjects(2, theHandles, true, theWaitTime); - ThrowIf((theError != WAIT_OBJECT_0) && (theError != WAIT_TIMEOUT), CAException(GetLastError()), "CAGuard::WaitFor: Wait got an error"); - mOwner = GetCurrentThreadId(); - ResetEvent(mEvent); - // This mutex should be locked again when time out happens.rdar://12270555 - if(theError == WAIT_TIMEOUT) { - DWORD dwError = WaitForSingleObject(mMutex, INFINITE); - ThrowIf((dwError != WAIT_OBJECT_0), CAException(GetLastError()), "CAGuard::WaitFor: failed to acquire the mutex back when timeout happened\n"); - } - #if Log_TimedWaits || Log_Latency || Log_Average_Latency - UInt64 theEndNanos = CAHostTimeBase::GetCurrentTimeInNanos(); - #endif - - #if Log_TimedWaits - DebugMessageN1("CAGuard::WaitFor: waited %.0f", (Float64)(theEndNanos - theStartNanos)); - #endif - - #if Log_Latency - DebugMessageN1("CAGuard::WaitFor: latency %.0f", (Float64)((theEndNanos - theStartNanos) - inNanos)); - #endif - - #if Log_Average_Latency - ++mAverageLatencyCount; - mAverageLatencyAccumulator += (theEndNanos - theStartNanos) - inNanos; - if(mAverageLatencyCount >= 50) - { - DebugMessageN2("CAGuard::WaitFor: average latency %.3f ns over %ld waits", mAverageLatencyAccumulator / mAverageLatencyCount, mAverageLatencyCount); - mAverageLatencyCount = 0; - mAverageLatencyAccumulator = 0.0; - } - #endif - - #if Log_WaitOwnership - DebugPrintfRtn(DebugPrintfFileComma "%lu %.4f: CAGuard::WaitFor: thread %lu waited on %s, owner: %lu\n", GetCurrentThreadId(), ((Float64)(CAHostTimeBase::GetCurrentTimeInNanos()) / 1000000.0), GetCurrentThreadId(), mName, mOwner); - #endif - - theAnswer = theError == WAIT_TIMEOUT; -#endif - - return theAnswer; -} - -bool CAGuard::WaitUntil(UInt64 inNanos) -{ - bool theAnswer = false; - UInt64 theCurrentNanos = CAHostTimeBase::GetCurrentTimeInNanos(); - -#if Log_TimedWaits - DebugMessageN2("CAGuard::WaitUntil: now: %.0f, requested: %.0f", (double)theCurrentNanos, (double)inNanos); -#endif - - if(inNanos > theCurrentNanos) - { -#if Log_Errors - if((inNanos - theCurrentNanos) > 1000000000ULL) - { - DebugMessage("CAGuard::WaitUntil: about to wait for more than a second"); - } -#endif - theAnswer = WaitFor(inNanos - theCurrentNanos); - } - else - { -#if Log_Errors - DebugMessageN2("CAGuard::WaitUntil: Time has expired before waiting, now: %.0f, requested: %.0f", (double)theCurrentNanos, (double)inNanos); -#endif - theAnswer = true; - } - - return theAnswer; -} - -void CAGuard::Notify() -{ -#if TARGET_OS_MAC - #if Log_WaitOwnership - DebugPrintfRtn(DebugPrintfFileComma "%p %.4f: CAGuard::Notify: thread %p is notifying %s, owner: %p\n", pthread_self(), ((Float64)(CAHostTimeBase::GetCurrentTimeInNanos()) / 1000000.0), pthread_self(), mName, mOwner); - #endif - - OSStatus theError = pthread_cond_signal(&mCondVar); - ThrowIf(theError != 0, CAException(theError), "CAGuard::Notify: failed"); -#elif TARGET_OS_WIN32 - #if Log_WaitOwnership - DebugPrintfRtn(DebugPrintfFileComma "%lu %.4f: CAGuard::Notify: thread %lu is notifying %s, owner: %lu\n", GetCurrentThreadId(), ((Float64)(CAHostTimeBase::GetCurrentTimeInNanos()) / 1000000.0), GetCurrentThreadId(), mName, mOwner); - #endif - - SetEvent(mEvent); -#endif -} - -void CAGuard::NotifyAll() -{ -#if TARGET_OS_MAC - #if Log_WaitOwnership - DebugPrintfRtn(DebugPrintfFileComma "%p %.4f: CAGuard::NotifyAll: thread %p is notifying %s, owner: %p\n", pthread_self(), ((Float64)(CAHostTimeBase::GetCurrentTimeInNanos()) / 1000000.0), pthread_self(), mName, mOwner); - #endif - - OSStatus theError = pthread_cond_broadcast(&mCondVar); - ThrowIf(theError != 0, CAException(theError), "CAGuard::NotifyAll: failed"); -#elif TARGET_OS_WIN32 - #if Log_WaitOwnership - DebugPrintfRtn(DebugPrintfFileComma "%lu %.4f: CAGuard::NotifyAll: thread %lu is notifying %s, owner: %lu\n", GetCurrentThreadId(), ((Float64)(CAHostTimeBase::GetCurrentTimeInNanos()) / 1000000.0), GetCurrentThreadId(), mName, mOwner); - #endif - - SetEvent(mEvent); -#endif -} diff --git a/src/CoreAudio/CoreAudioComponent/PublicUtility/CAGuard.h b/src/CoreAudio/CoreAudioComponent/PublicUtility/CAGuard.h deleted file mode 100644 index ffcb59da8..000000000 --- a/src/CoreAudio/CoreAudioComponent/PublicUtility/CAGuard.h +++ /dev/null @@ -1,133 +0,0 @@ -/* - File: CAGuard.h - Abstract: Part of CoreAudio Utility Classes - Version: 1.1 - - Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple - Inc. ("Apple") in consideration of your agreement to the following - terms, and your use, installation, modification or redistribution of - this Apple software constitutes acceptance of these terms. If you do - not agree with these terms, please do not use, install, modify or - redistribute this Apple software. - - In consideration of your agreement to abide by the following terms, and - subject to these terms, Apple grants you a personal, non-exclusive - license, under Apple's copyrights in this original Apple software (the - "Apple Software"), to use, reproduce, modify and redistribute the Apple - Software, with or without modifications, in source and/or binary forms; - provided that if you redistribute the Apple Software in its entirety and - without modifications, you must retain this notice and the following - text and disclaimers in all such redistributions of the Apple Software. - Neither the name, trademarks, service marks or logos of Apple Inc. may - be used to endorse or promote products derived from the Apple Software - without specific prior written permission from Apple. Except as - expressly stated in this notice, no other rights or licenses, express or - implied, are granted by Apple herein, including but not limited to any - patent rights that may be infringed by your derivative works or by other - works in which the Apple Software may be incorporated. - - The Apple Software is provided by Apple on an "AS IS" basis. APPLE - MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION - THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS - FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND - OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS. - - IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL - OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, - MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED - AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), - STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE - POSSIBILITY OF SUCH DAMAGE. - - Copyright (C) 2014 Apple Inc. All Rights Reserved. - -*/ -#if !defined(__CAGuard_h__) -#define __CAGuard_h__ - -//================================================================================================== -// Includes -//============================================================================= - -// Super Class Includes -#include "CAMutex.h" - -#if CoreAudio_Debug -// #define Log_Average_Latency 1 -#endif - -//================================================================================================== -// CAGuard -// -// This is your typical mutex with signalling implemented via pthreads. -// Lock() will return true if and only if the guard is locked on that call. -// A thread that already has the guard will receive 'false' if it locks it -// again. Use of the stack-based CAGuard::Locker class is highly recommended -// to properly manage the recursive nesting. The Wait calls with timeouts -// will return true if and only if the timeout period expired. They will -// return false if they receive notification any other way. -//================================================================================================== - -class CAGuard : public CAMutex -{ - -// Construction/Destruction -public: - CAGuard(const char* inName); - virtual ~CAGuard(); - -// Actions -public: - virtual void Wait(); - virtual bool WaitFor(UInt64 inNanos); - virtual bool WaitUntil(UInt64 inNanos); - - virtual void Notify(); - virtual void NotifyAll(); - -// Implementation -protected: -#if TARGET_OS_MAC - pthread_cond_t mCondVar; -#else - HANDLE mEvent; -#endif -#if Log_Average_Latency - Float64 mAverageLatencyAccumulator; - UInt32 mAverageLatencyCount; -#endif - -// Helper class to manage taking and releasing recursively -public: - class Locker - { - - // Construction/Destruction - public: - Locker(CAGuard& inGuard) : mGuard(inGuard), mNeedsRelease(false) { mNeedsRelease = mGuard.Lock(); } - ~Locker() { if(mNeedsRelease) { mGuard.Unlock(); } } - - private: - Locker(const Locker&); - Locker& operator=(const Locker&); - - // Actions - public: - void Wait() { mGuard.Wait(); } - bool WaitFor(UInt64 inNanos) { return mGuard.WaitFor(inNanos); } - bool WaitUntil(UInt64 inNanos) { return mGuard.WaitUntil(inNanos); } - - void Notify() { mGuard.Notify(); } - void NotifyAll() { mGuard.NotifyAll(); } - - // Implementation - private: - CAGuard& mGuard; - bool mNeedsRelease; - }; - -}; - -#endif diff --git a/src/CoreAudio/CoreAudioComponent/PublicUtility/CAHostTimeBase.cpp b/src/CoreAudio/CoreAudioComponent/PublicUtility/CAHostTimeBase.cpp deleted file mode 100644 index db78a4afe..000000000 --- a/src/CoreAudio/CoreAudioComponent/PublicUtility/CAHostTimeBase.cpp +++ /dev/null @@ -1,99 +0,0 @@ -/* - File: CAHostTimeBase.cpp - Abstract: CAHostTimeBase.h - Version: 1.1 - - Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple - Inc. ("Apple") in consideration of your agreement to the following - terms, and your use, installation, modification or redistribution of - this Apple software constitutes acceptance of these terms. If you do - not agree with these terms, please do not use, install, modify or - redistribute this Apple software. - - In consideration of your agreement to abide by the following terms, and - subject to these terms, Apple grants you a personal, non-exclusive - license, under Apple's copyrights in this original Apple software (the - "Apple Software"), to use, reproduce, modify and redistribute the Apple - Software, with or without modifications, in source and/or binary forms; - provided that if you redistribute the Apple Software in its entirety and - without modifications, you must retain this notice and the following - text and disclaimers in all such redistributions of the Apple Software. - Neither the name, trademarks, service marks or logos of Apple Inc. may - be used to endorse or promote products derived from the Apple Software - without specific prior written permission from Apple. Except as - expressly stated in this notice, no other rights or licenses, express or - implied, are granted by Apple herein, including but not limited to any - patent rights that may be infringed by your derivative works or by other - works in which the Apple Software may be incorporated. - - The Apple Software is provided by Apple on an "AS IS" basis. APPLE - MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION - THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS - FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND - OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS. - - IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL - OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, - MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED - AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), - STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE - POSSIBILITY OF SUCH DAMAGE. - - Copyright (C) 2014 Apple Inc. All Rights Reserved. - -*/ -//============================================================================= -// Includes -//============================================================================= - -#include "CAHostTimeBase.h" - -Float64 CAHostTimeBase::sFrequency = 0; -Float64 CAHostTimeBase::sInverseFrequency = 0; -UInt32 CAHostTimeBase::sMinDelta = 0; -UInt32 CAHostTimeBase::sToNanosNumerator = 0; -UInt32 CAHostTimeBase::sToNanosDenominator = 0; -pthread_once_t CAHostTimeBase::sIsInited = PTHREAD_ONCE_INIT; -#if Track_Host_TimeBase -UInt64 CAHostTimeBase::sLastTime = 0; -#endif - -//============================================================================= -// CAHostTimeBase -// -// This class provides platform independent access to the host's time base. -//============================================================================= - -void CAHostTimeBase::Initialize() -{ - // get the info about Absolute time - #if TARGET_OS_MAC - struct mach_timebase_info theTimeBaseInfo; - mach_timebase_info(&theTimeBaseInfo); - sMinDelta = 1; - sToNanosNumerator = theTimeBaseInfo.numer; - sToNanosDenominator = theTimeBaseInfo.denom; - - // the frequency of that clock is: (sToNanosDenominator / sToNanosNumerator) * 10^9 - sFrequency = static_cast(sToNanosDenominator) / static_cast(sToNanosNumerator); - sFrequency *= 1000000000.0; - #elif TARGET_OS_WIN32 - LARGE_INTEGER theFrequency; - QueryPerformanceFrequency(&theFrequency); - sMinDelta = 1; - sToNanosNumerator = 1000000000ULL; - sToNanosDenominator = *((UInt64*)&theFrequency); - sFrequency = static_cast(*((UInt64*)&theFrequency)); - #endif - sInverseFrequency = 1.0 / sFrequency; - - #if Log_Host_Time_Base_Parameters - DebugPrintf("Host Time Base Parameters"); - DebugPrintf(" Minimum Delta: %lu", (unsigned long)sMinDelta); - DebugPrintf(" Frequency: %f", sFrequency); - DebugPrintf(" To Nanos Numerator: %lu", (unsigned long)sToNanosNumerator); - DebugPrintf(" To Nanos Denominator: %lu", (unsigned long)sToNanosDenominator); - #endif -} diff --git a/src/CoreAudio/CoreAudioComponent/PublicUtility/CAHostTimeBase.h b/src/CoreAudio/CoreAudioComponent/PublicUtility/CAHostTimeBase.h deleted file mode 100644 index 50e350764..000000000 --- a/src/CoreAudio/CoreAudioComponent/PublicUtility/CAHostTimeBase.h +++ /dev/null @@ -1,234 +0,0 @@ -/* - File: CAHostTimeBase.h - Abstract: Part of CoreAudio Utility Classes - Version: 1.1 - - Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple - Inc. ("Apple") in consideration of your agreement to the following - terms, and your use, installation, modification or redistribution of - this Apple software constitutes acceptance of these terms. If you do - not agree with these terms, please do not use, install, modify or - redistribute this Apple software. - - In consideration of your agreement to abide by the following terms, and - subject to these terms, Apple grants you a personal, non-exclusive - license, under Apple's copyrights in this original Apple software (the - "Apple Software"), to use, reproduce, modify and redistribute the Apple - Software, with or without modifications, in source and/or binary forms; - provided that if you redistribute the Apple Software in its entirety and - without modifications, you must retain this notice and the following - text and disclaimers in all such redistributions of the Apple Software. - Neither the name, trademarks, service marks or logos of Apple Inc. may - be used to endorse or promote products derived from the Apple Software - without specific prior written permission from Apple. Except as - expressly stated in this notice, no other rights or licenses, express or - implied, are granted by Apple herein, including but not limited to any - patent rights that may be infringed by your derivative works or by other - works in which the Apple Software may be incorporated. - - The Apple Software is provided by Apple on an "AS IS" basis. APPLE - MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION - THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS - FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND - OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS. - - IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL - OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, - MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED - AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), - STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE - POSSIBILITY OF SUCH DAMAGE. - - Copyright (C) 2014 Apple Inc. All Rights Reserved. - -*/ -#if !defined(__CAHostTimeBase_h__) -#define __CAHostTimeBase_h__ - -//============================================================================= -// Includes -//============================================================================= - -#if !defined(__COREAUDIO_USE_FLAT_INCLUDES__) - #include -#else - #include -#endif - -#if TARGET_OS_MAC - #include - #include -#elif TARGET_OS_WIN32 - #include - #include "WinPThreadDefs.h" -#else - #error Unsupported operating system -#endif - -#include "CADebugPrintf.h" - -//============================================================================= -// CAHostTimeBase -// -// This class provides platform independent access to the host's time base. -//============================================================================= - -#if CoreAudio_Debug -// #define Log_Host_Time_Base_Parameters 1 -// #define Track_Host_TimeBase 1 -#endif - -class CAHostTimeBase -{ - -public: - static UInt64 ConvertToNanos(UInt64 inHostTime); - static UInt64 ConvertFromNanos(UInt64 inNanos); - - static UInt64 GetTheCurrentTime(); -#if TARGET_OS_MAC - static UInt64 GetCurrentTime() { return GetTheCurrentTime(); } -#endif - static UInt64 GetCurrentTimeInNanos(); - - static Float64 GetFrequency() { pthread_once(&sIsInited, Initialize); return sFrequency; } - static Float64 GetInverseFrequency() { pthread_once(&sIsInited, Initialize); return sInverseFrequency; } - static UInt32 GetMinimumDelta() { pthread_once(&sIsInited, Initialize); return sMinDelta; } - - static UInt64 AbsoluteHostDeltaToNanos(UInt64 inStartTime, UInt64 inEndTime); - static SInt64 HostDeltaToNanos(UInt64 inStartTime, UInt64 inEndTime); - - static UInt64 MultiplyByRatio(UInt64 inMuliplicand, UInt32 inNumerator, UInt32 inDenominator); - -private: - static void Initialize(); - - static pthread_once_t sIsInited; - - static Float64 sFrequency; - static Float64 sInverseFrequency; - static UInt32 sMinDelta; - static UInt32 sToNanosNumerator; - static UInt32 sToNanosDenominator; -#if Track_Host_TimeBase - static UInt64 sLastTime; -#endif -}; - -inline UInt64 CAHostTimeBase::GetTheCurrentTime() -{ - UInt64 theTime = 0; - - #if TARGET_OS_MAC - theTime = mach_absolute_time(); - #elif TARGET_OS_WIN32 - LARGE_INTEGER theValue; - QueryPerformanceCounter(&theValue); - theTime = *((UInt64*)&theValue); - #endif - - #if Track_Host_TimeBase - if(sLastTime != 0) - { - if(theTime <= sLastTime) - { - DebugPrintf("CAHostTimeBase::GetTheCurrentTime: the current time is earlier than the last time, now: %qd, then: %qd", theTime, sLastTime); - } - sLastTime = theTime; - } - else - { - sLastTime = theTime; - } - #endif - - return theTime; -} - -inline UInt64 CAHostTimeBase::ConvertToNanos(UInt64 inHostTime) -{ - pthread_once(&sIsInited, Initialize); - - UInt64 theAnswer = MultiplyByRatio(inHostTime, sToNanosNumerator, sToNanosDenominator); - #if CoreAudio_Debug - if(((sToNanosNumerator > sToNanosDenominator) && (theAnswer < inHostTime)) || ((sToNanosDenominator > sToNanosNumerator) && (theAnswer > inHostTime))) - { - DebugPrintf("CAHostTimeBase::ConvertToNanos: The conversion wrapped"); - } - #endif - - return theAnswer; -} - -inline UInt64 CAHostTimeBase::ConvertFromNanos(UInt64 inNanos) -{ - pthread_once(&sIsInited, Initialize); - - UInt64 theAnswer = MultiplyByRatio(inNanos, sToNanosDenominator, sToNanosNumerator); - #if CoreAudio_Debug - if(((sToNanosDenominator > sToNanosNumerator) && (theAnswer < inNanos)) || ((sToNanosNumerator > sToNanosDenominator) && (theAnswer > inNanos))) - { - DebugPrintf("CAHostTimeBase::ConvertFromNanos: The conversion wrapped"); - } - #endif - - return theAnswer; -} - -inline UInt64 CAHostTimeBase::GetCurrentTimeInNanos() -{ - return ConvertToNanos(GetTheCurrentTime()); -} - -inline UInt64 CAHostTimeBase::AbsoluteHostDeltaToNanos(UInt64 inStartTime, UInt64 inEndTime) -{ - UInt64 theAnswer; - - if(inStartTime <= inEndTime) - { - theAnswer = inEndTime - inStartTime; - } - else - { - theAnswer = inStartTime - inEndTime; - } - - return ConvertToNanos(theAnswer); -} - -inline SInt64 CAHostTimeBase::HostDeltaToNanos(UInt64 inStartTime, UInt64 inEndTime) -{ - SInt64 theAnswer; - SInt64 theSign = 1; - - if(inStartTime <= inEndTime) - { - theAnswer = static_cast(inEndTime - inStartTime); - } - else - { - theAnswer = static_cast(inStartTime - inEndTime); - theSign = -1; - } - - return theSign * static_cast(ConvertToNanos(static_cast(theAnswer))); -} - -inline UInt64 CAHostTimeBase::MultiplyByRatio(UInt64 inMuliplicand, UInt32 inNumerator, UInt32 inDenominator) -{ -#if TARGET_OS_MAC && TARGET_RT_64_BIT - __uint128_t theAnswer = inMuliplicand; -#else - long double theAnswer = inMuliplicand; -#endif - if(inNumerator != inDenominator) - { - theAnswer *= inNumerator; - theAnswer /= inDenominator; - } - return static_cast(theAnswer); -} - -#endif diff --git a/src/CoreAudio/CoreAudioComponent/PublicUtility/CALogMacros.h b/src/CoreAudio/CoreAudioComponent/PublicUtility/CALogMacros.h deleted file mode 100644 index 7fd4ac4c2..000000000 --- a/src/CoreAudio/CoreAudioComponent/PublicUtility/CALogMacros.h +++ /dev/null @@ -1,140 +0,0 @@ -/* - File: CALogMacros.h - Abstract: Part of CoreAudio Utility Classes - Version: 1.1 - - Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple - Inc. ("Apple") in consideration of your agreement to the following - terms, and your use, installation, modification or redistribution of - this Apple software constitutes acceptance of these terms. If you do - not agree with these terms, please do not use, install, modify or - redistribute this Apple software. - - In consideration of your agreement to abide by the following terms, and - subject to these terms, Apple grants you a personal, non-exclusive - license, under Apple's copyrights in this original Apple software (the - "Apple Software"), to use, reproduce, modify and redistribute the Apple - Software, with or without modifications, in source and/or binary forms; - provided that if you redistribute the Apple Software in its entirety and - without modifications, you must retain this notice and the following - text and disclaimers in all such redistributions of the Apple Software. - Neither the name, trademarks, service marks or logos of Apple Inc. may - be used to endorse or promote products derived from the Apple Software - without specific prior written permission from Apple. Except as - expressly stated in this notice, no other rights or licenses, express or - implied, are granted by Apple herein, including but not limited to any - patent rights that may be infringed by your derivative works or by other - works in which the Apple Software may be incorporated. - - The Apple Software is provided by Apple on an "AS IS" basis. APPLE - MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION - THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS - FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND - OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS. - - IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL - OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, - MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED - AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), - STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE - POSSIBILITY OF SUCH DAMAGE. - - Copyright (C) 2014 Apple Inc. All Rights Reserved. - -*/ -#if !defined(__CALogMacros_h__) -#define __CALogMacros_h__ - -//============================================================================= -// Log Macros -//============================================================================= - -#if CoreAudio_Debug - - #include "CADebugMacros.h" - #include "CADebugPrintf.h" - #include - #include - - #define PrintLine(msg) DebugPrintfRtn(DebugPrintfFileComma "%s\n", (msg)) - - #define PrintBool(msg, b) DebugPrintfRtn(DebugPrintfFileComma "%s%s\n", (msg), (b) ? "true" : "false") - #define PrintIndexedBool(msg, i, b) DebugPrintfRtn(DebugPrintfFileComma " %s %ld: %s\n", (msg), (long)(i), (b) ? "true" : "false") - - #define PrintToggle(msg, b) DebugPrintfRtn(DebugPrintfFileComma "%s%s\n", (msg), (b) ? "on" : "off") - #define PrintIndexedToggle(msg, i, b) DebugPrintfRtn(DebugPrintfFileComma " %s %ld: %s\n", (msg), (long)(i), (b) ? "on" : "off") - - #define PrintInt(msg, n) DebugPrintfRtn(DebugPrintfFileComma "%s%ld\n", (msg), (long)(n)) - #define PrintIndexedInt(msg, i, n) DebugPrintfRtn(DebugPrintfFileComma " %s %ld: %ld\n", (msg), (long)(i), (long)(n)) - - #define PrintHex(msg, n) DebugPrintfRtn(DebugPrintfFileComma "%s0x%lX\n", (msg), (unsigned long)(n)) - #define PrintIndexedHex(msg, i, n) DebugPrintfRtn(DebugPrintfFileComma " %s %ld: 0x%lX\n", (msg), (long)(i), (unsigned long)(n)) - - #define PrintFloat(msg, f) DebugPrintfRtn(DebugPrintfFileComma "%s%.6f\n", (msg), (f)) - #define PrintIndexedFloat(msg, i, f) DebugPrintfRtn(DebugPrintfFileComma " %s %ld: %.6f\n", (msg), (long)(i), (f)) - #define PrintFloatIndexedFloat(msg, i, f) DebugPrintfRtn(DebugPrintfFileComma " %s %.6f: %.6f\n", (msg), (i), (f)) - - #define PrintString(msg, s) DebugPrintfRtn(DebugPrintfFileComma "%s%s\n", (msg), (s)) - #define PrintIndexedString(msg, i, s) DebugPrintfRtn(DebugPrintfFileComma " %s %ld: %s\n", (msg), (long)(i), (s)) - - #define PrintPointer(msg, p) DebugPrintfRtn(DebugPrintfFileComma "%s%p\n", (msg), (p)) - #define PrintIndexedPointer(msg, i, p) DebugPrintfRtn(DebugPrintfFileComma " %s %ld: %p\n", (msg), (long)(i), (p)) - - #define Print4CharCode(msg, c) { \ - UInt32 __4CC_number = (c); \ - char __4CC_string[5] = CA4CCToCString(__4CC_number); \ - DebugPrintfRtn(DebugPrintfFileComma "%s'%s'\n", (msg), __4CC_string); \ - } - #define PrintIndexed4CharCode(msg, i, c) { \ - UInt32 __4CC_number = (c); \ - char __4CC_string[5] = CA4CCToCString(__4CC_number); \ - DebugPrintfRtn(DebugPrintfFileComma " %s %ld: '%s'\n", (msg), (long)(i), __4CC_string); \ - } - - #define ErrorLine(s) DebugPrintfRtn(DebugPrintfFileComma "%s\n", (s)) - #define OSErrorLine(s, e) { \ - OSStatus __err_number = (e); \ - char __err_string[5] = CA4CCToCString(__err_number); \ - DebugPrintfRtn(DebugPrintfFileComma "%s, OSStatus code: %s\n", (s), __err_string); \ - } - - #define MessageIfOSError(e, s) if((e) != 0) { OSErrorLine(s, e); } - #define MessageIfNULL(p, s) if((p) == 0) { ErrorLine(s); } - -#else - - #define PrintLine(msg) - - #define PrintBool(msg, b) (b) - #define PrintIndexedBool(msg, i, b) (b) - - #define PrintInt(msg, n) (n) - #define PrintIndexedInt(msg, i, n) (n) - - #define PrintHex(msg, n) (n) - #define PrintIndexedHex(msg, i, n) (n) - - #define PrintFloat(msg, f) (f) - #define PrintIndexedFloat(msg, i, f) (f) - #define PrintFloatIndexedFloat(msg, i, f) (f) - - #define PrintString(msg, s) (s) - #define PrintIndexedString(msg, i, s) (s) - - #define PrintPointer(msg, p) (p) - #define PrintIndexedPointer(msg, i, p) (p) - - #define Print4CharCode(msg, c) (c) - #define PrintIndexed4CharCode(msg, i, c) (c) - - #define ErrorLine(s) (s) - #define OSErrorLine(s, e) (e) - - #define MessageIfOSError(e, s) (e) - #define MessageIfNULL(p, s) (p) - -#endif // CoreAudio_Debug - -#endif diff --git a/src/CoreAudio/CoreAudioComponent/PublicUtility/CAMath.h b/src/CoreAudio/CoreAudioComponent/PublicUtility/CAMath.h deleted file mode 100644 index eb81f26e9..000000000 --- a/src/CoreAudio/CoreAudioComponent/PublicUtility/CAMath.h +++ /dev/null @@ -1,68 +0,0 @@ -/* - File: CAMath.h - Abstract: Part of CoreAudio Utility Classes - Version: 1.1 - - Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple - Inc. ("Apple") in consideration of your agreement to the following - terms, and your use, installation, modification or redistribution of - this Apple software constitutes acceptance of these terms. If you do - not agree with these terms, please do not use, install, modify or - redistribute this Apple software. - - In consideration of your agreement to abide by the following terms, and - subject to these terms, Apple grants you a personal, non-exclusive - license, under Apple's copyrights in this original Apple software (the - "Apple Software"), to use, reproduce, modify and redistribute the Apple - Software, with or without modifications, in source and/or binary forms; - provided that if you redistribute the Apple Software in its entirety and - without modifications, you must retain this notice and the following - text and disclaimers in all such redistributions of the Apple Software. - Neither the name, trademarks, service marks or logos of Apple Inc. may - be used to endorse or promote products derived from the Apple Software - without specific prior written permission from Apple. Except as - expressly stated in this notice, no other rights or licenses, express or - implied, are granted by Apple herein, including but not limited to any - patent rights that may be infringed by your derivative works or by other - works in which the Apple Software may be incorporated. - - The Apple Software is provided by Apple on an "AS IS" basis. APPLE - MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION - THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS - FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND - OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS. - - IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL - OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, - MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED - AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), - STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE - POSSIBILITY OF SUCH DAMAGE. - - Copyright (C) 2014 Apple Inc. All Rights Reserved. - -*/ -#ifndef __CAMath_h__ -#define __CAMath_h__ - -#if !defined(__COREAUDIO_USE_FLAT_INCLUDES__) - #include -#else - #include -#endif - -inline bool fiszero(Float64 f) { return (f == 0.); } -inline bool fiszero(Float32 f) { return (f == 0.f); } - -inline bool fnonzero(Float64 f) { return !fiszero(f); } -inline bool fnonzero(Float32 f) { return !fiszero(f); } - -inline bool fequal(const Float64 &a, const Float64 &b) { return a == b; } -inline bool fequal(const Float32 &a, const Float32 &b) { return a == b; } - -inline bool fnotequal(const Float64 &a, const Float64 &b) { return !fequal(a, b); } -inline bool fnotequal(const Float32 &a, const Float32 &b) { return !fequal(a, b); } - -#endif // __CAMath_h__ diff --git a/src/CoreAudio/CoreAudioComponent/PublicUtility/CAMutex.cpp b/src/CoreAudio/CoreAudioComponent/PublicUtility/CAMutex.cpp deleted file mode 100644 index 88cf9b0b0..000000000 --- a/src/CoreAudio/CoreAudioComponent/PublicUtility/CAMutex.cpp +++ /dev/null @@ -1,345 +0,0 @@ -/* - File: CAMutex.cpp - Abstract: CAMutex.h - Version: 1.1 - - Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple - Inc. ("Apple") in consideration of your agreement to the following - terms, and your use, installation, modification or redistribution of - this Apple software constitutes acceptance of these terms. If you do - not agree with these terms, please do not use, install, modify or - redistribute this Apple software. - - In consideration of your agreement to abide by the following terms, and - subject to these terms, Apple grants you a personal, non-exclusive - license, under Apple's copyrights in this original Apple software (the - "Apple Software"), to use, reproduce, modify and redistribute the Apple - Software, with or without modifications, in source and/or binary forms; - provided that if you redistribute the Apple Software in its entirety and - without modifications, you must retain this notice and the following - text and disclaimers in all such redistributions of the Apple Software. - Neither the name, trademarks, service marks or logos of Apple Inc. may - be used to endorse or promote products derived from the Apple Software - without specific prior written permission from Apple. Except as - expressly stated in this notice, no other rights or licenses, express or - implied, are granted by Apple herein, including but not limited to any - patent rights that may be infringed by your derivative works or by other - works in which the Apple Software may be incorporated. - - The Apple Software is provided by Apple on an "AS IS" basis. APPLE - MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION - THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS - FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND - OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS. - - IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL - OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, - MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED - AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), - STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE - POSSIBILITY OF SUCH DAMAGE. - - Copyright (C) 2014 Apple Inc. All Rights Reserved. - -*/ -//================================================================================================== -// Includes -//================================================================================================== - -// Self Include -#include "CAMutex.h" - -#if TARGET_OS_MAC - #include -#endif - -// PublicUtility Includes -#include "CADebugMacros.h" -#include "CAException.h" -#include "CAHostTimeBase.h" - -//================================================================================================== -// Logging -//================================================================================================== - -#if CoreAudio_Debug -// #define Log_Ownership 1 -// #define Log_Errors 1 -// #define Log_LongLatencies 1 -// #define LongLatencyThreshholdNS 1000000ULL // nanoseconds -#endif - -//================================================================================================== -// CAMutex -//================================================================================================== - -CAMutex::CAMutex(const char* inName) -: - mName(inName), - mOwner(0) -{ -#if TARGET_OS_MAC - OSStatus theError = pthread_mutex_init(&mMutex, NULL); - ThrowIf(theError != 0, CAException(theError), "CAMutex::CAMutex: Could not init the mutex"); - - #if Log_Ownership - DebugPrintfRtn(DebugPrintfFileComma "%p %.4f: CAMutex::CAMutex: creating %s, owner: %p\n", pthread_self(), ((Float64)(CAHostTimeBase::GetCurrentTimeInNanos()) / 1000000.0), mName, mOwner); - #endif -#elif TARGET_OS_WIN32 - mMutex = CreateMutex(NULL, false, NULL); - ThrowIfNULL(mMutex, CAException(GetLastError()), "CAMutex::CAMutex: could not create the mutex."); - - #if Log_Ownership - DebugPrintfRtn(DebugPrintfFileComma "%lu %.4f: CAMutex::CAMutex: creating %s, owner: %lu\n", GetCurrentThreadId(), ((Float64)(CAHostTimeBase::GetCurrentTimeInNanos()) / 1000000.0), mName, mOwner); - #endif -#endif -} - -CAMutex::~CAMutex() -{ -#if TARGET_OS_MAC - #if Log_Ownership - DebugPrintfRtn(DebugPrintfFileComma "%p %.4f: CAMutex::~CAMutex: destroying %s, owner: %p\n", pthread_self(), ((Float64)(CAHostTimeBase::GetCurrentTimeInNanos()) / 1000000.0), mName, mOwner); - #endif - pthread_mutex_destroy(&mMutex); -#elif TARGET_OS_WIN32 - #if Log_Ownership - DebugPrintfRtn(DebugPrintfFileComma "%lu %.4f: CAMutex::~CAMutex: destroying %s, owner: %lu\n", GetCurrentThreadId(), ((Float64)(CAHostTimeBase::GetCurrentTimeInNanos()) / 1000000.0), mName, mOwner); - #endif - if(mMutex != NULL) - { - CloseHandle(mMutex); - } -#endif -} - -bool CAMutex::Lock() -{ - bool theAnswer = false; - -#if TARGET_OS_MAC - pthread_t theCurrentThread = pthread_self(); - if(!pthread_equal(theCurrentThread, mOwner)) - { - #if Log_Ownership - DebugPrintfRtn(DebugPrintfFileComma "%p %.4f: CAMutex::Lock: thread %p is locking %s, owner: %p\n", theCurrentThread, ((Float64)(CAHostTimeBase::GetCurrentTimeInNanos()) / 1000000.0), theCurrentThread, mName, mOwner); - #endif - - #if Log_LongLatencies - UInt64 lockTryTime = CAHostTimeBase::GetCurrentTimeInNanos(); - #endif - - OSStatus theError = pthread_mutex_lock(&mMutex); - ThrowIf(theError != 0, CAException(theError), "CAMutex::Lock: Could not lock the mutex"); - mOwner = theCurrentThread; - theAnswer = true; - - #if Log_LongLatencies - UInt64 lockAcquireTime = CAHostTimeBase::GetCurrentTimeInNanos(); - if (lockAcquireTime - lockTryTime >= LongLatencyThresholdNS) - DebugPrintfRtn(DebugPrintfFileComma "Thread %p took %.6fs to acquire the lock %s\n", theCurrentThread, (lockAcquireTime - lockTryTime) * 1.0e-9 /* nanos to seconds */, mName); - #endif - - #if Log_Ownership - DebugPrintfRtn(DebugPrintfFileComma "%p %.4f: CAMutex::Lock: thread %p has locked %s, owner: %p\n", pthread_self(), ((Float64)(CAHostTimeBase::GetCurrentTimeInNanos()) / 1000000.0), pthread_self(), mName, mOwner); - #endif - } -#elif TARGET_OS_WIN32 - if(mOwner != GetCurrentThreadId()) - { - #if Log_Ownership - DebugPrintfRtn(DebugPrintfFileComma "%lu %.4f: CAMutex::Lock: thread %lu is locking %s, owner: %lu\n", GetCurrentThreadId(), ((Float64)(CAHostTimeBase::GetCurrentTimeInNanos()) / 1000000.0), GetCurrentThreadId(), mName, mOwner); - #endif - - OSStatus theError = WaitForSingleObject(mMutex, INFINITE); - ThrowIfError(theError, CAException(theError), "CAMutex::Lock: could not lock the mutex"); - mOwner = GetCurrentThreadId(); - theAnswer = true; - - #if Log_Ownership - DebugPrintfRtn(DebugPrintfFileComma "%lu %.4f: CAMutex::Lock: thread %lu has locked %s, owner: %lu\n", GetCurrentThreadId(), ((Float64)(CAHostTimeBase::GetCurrentTimeInNanos()) / 1000000.0), GetCurrentThreadId(), mName, mOwner); - #endif - } -#endif - - return theAnswer; -} - -void CAMutex::Unlock() -{ -#if TARGET_OS_MAC - if(pthread_equal(pthread_self(), mOwner)) - { - #if Log_Ownership - DebugPrintfRtn(DebugPrintfFileComma "%p %.4f: CAMutex::Unlock: thread %p is unlocking %s, owner: %p\n", pthread_self(), ((Float64)(CAHostTimeBase::GetCurrentTimeInNanos()) / 1000000.0), pthread_self(), mName, mOwner); - #endif - - mOwner = 0; - OSStatus theError = pthread_mutex_unlock(&mMutex); - ThrowIf(theError != 0, CAException(theError), "CAMutex::Unlock: Could not unlock the mutex"); - - #if Log_Ownership - DebugPrintfRtn(DebugPrintfFileComma "%p %.4f: CAMutex::Unlock: thread %p has unlocked %s, owner: %p\n", pthread_self(), ((Float64)(CAHostTimeBase::GetCurrentTimeInNanos()) / 1000000.0), pthread_self(), mName, mOwner); - #endif - } - else - { - DebugMessage("CAMutex::Unlock: A thread is attempting to unlock a Mutex it doesn't own"); - } -#elif TARGET_OS_WIN32 - if(mOwner == GetCurrentThreadId()) - { - #if Log_Ownership - DebugPrintfRtn(DebugPrintfFileComma "%lu %.4f: CAMutex::Unlock: thread %lu is unlocking %s, owner: %lu\n", GetCurrentThreadId(), ((Float64)(CAHostTimeBase::GetCurrentTimeInNanos()) / 1000000.0), GetCurrentThreadId(), mName, mOwner); - #endif - - mOwner = 0; - bool wasReleased = ReleaseMutex(mMutex); - ThrowIf(!wasReleased, CAException(GetLastError()), "CAMutex::Unlock: Could not unlock the mutex"); - - #if Log_Ownership - DebugPrintfRtn(DebugPrintfFileComma "%lu %.4f: CAMutex::Unlock: thread %lu has unlocked %s, owner: %lu\n", GetCurrentThreadId(), ((Float64)(CAHostTimeBase::GetCurrentTimeInNanos()) / 1000000.0), GetCurrentThreadId(), mName, mOwner); - #endif - } - else - { - DebugMessage("CAMutex::Unlock: A thread is attempting to unlock a Mutex it doesn't own"); - } -#endif -} - -bool CAMutex::Try(bool& outWasLocked) -{ - bool theAnswer = false; - outWasLocked = false; - -#if TARGET_OS_MAC - pthread_t theCurrentThread = pthread_self(); - if(!pthread_equal(theCurrentThread, mOwner)) - { - // this means the current thread doesn't already own the lock - #if Log_Ownership - DebugPrintfRtn(DebugPrintfFileComma "%p %.4f: CAMutex::Try: thread %p is try-locking %s, owner: %p\n", theCurrentThread, ((Float64)(CAHostTimeBase::GetCurrentTimeInNanos()) / 1000000.0), theCurrentThread, mName, mOwner); - #endif - - // go ahead and call trylock to see if we can lock it. - int theError = pthread_mutex_trylock(&mMutex); - if(theError == 0) - { - // return value of 0 means we successfully locked the lock - mOwner = theCurrentThread; - theAnswer = true; - outWasLocked = true; - - #if Log_Ownership - DebugPrintfRtn(DebugPrintfFileComma "%p %.4f: CAMutex::Try: thread %p has locked %s, owner: %p\n", theCurrentThread, ((Float64)(CAHostTimeBase::GetCurrentTimeInNanos()) / 1000000.0), theCurrentThread, mName, mOwner); - #endif - } - else if(theError == EBUSY) - { - // return value of EBUSY means that the lock was already locked by another thread - theAnswer = false; - outWasLocked = false; - - #if Log_Ownership - DebugPrintfRtn(DebugPrintfFileComma "%p %.4f: CAMutex::Try: thread %p failed to lock %s, owner: %p\n", theCurrentThread, ((Float64)(CAHostTimeBase::GetCurrentTimeInNanos()) / 1000000.0), theCurrentThread, mName, mOwner); - #endif - } - else - { - // any other return value means something really bad happenned - ThrowIfError(theError, CAException(theError), "CAMutex::Try: call to pthread_mutex_trylock failed"); - } - } - else - { - // this means the current thread already owns the lock - theAnswer = true; - outWasLocked = false; - } -#elif TARGET_OS_WIN32 - if(mOwner != GetCurrentThreadId()) - { - // this means the current thread doesn't own the lock - #if Log_Ownership - DebugPrintfRtn(DebugPrintfFileComma "%lu %.4f: CAMutex::Try: thread %lu is try-locking %s, owner: %lu\n", GetCurrentThreadId(), ((Float64)(CAHostTimeBase::GetCurrentTimeInNanos()) / 1000000.0), GetCurrentThreadId(), mName, mOwner); - #endif - - // try to acquire the mutex - OSStatus theError = WaitForSingleObject(mMutex, 0); - if(theError == WAIT_OBJECT_0) - { - // this means we successfully locked the lock - mOwner = GetCurrentThreadId(); - theAnswer = true; - outWasLocked = true; - - #if Log_Ownership - DebugPrintfRtn(DebugPrintfFileComma "%lu %.4f: CAMutex::Try: thread %lu has locked %s, owner: %lu\n", GetCurrentThreadId(), ((Float64)(CAHostTimeBase::GetCurrentTimeInNanos()) / 1000000.0), GetCurrentThreadId(), mName, mOwner); - #endif - } - else if(theError == WAIT_TIMEOUT) - { - // this means that the lock was already locked by another thread - theAnswer = false; - outWasLocked = false; - - #if Log_Ownership - DebugPrintfRtn(DebugPrintfFileComma "%lu %.4f: CAMutex::Try: thread %lu failed to lock %s, owner: %lu\n", GetCurrentThreadId(), ((Float64)(CAHostTimeBase::GetCurrentTimeInNanos()) / 1000000.0), GetCurrentThreadId(), mName, mOwner); - #endif - } - else - { - // any other return value means something really bad happenned - ThrowIfError(theError, CAException(GetLastError()), "CAMutex::Try: call to lock the mutex failed"); - } - } - else - { - // this means the current thread already owns the lock - theAnswer = true; - outWasLocked = false; - } -#endif - - return theAnswer; -} - -bool CAMutex::IsFree() const -{ - return mOwner == 0; -} - -bool CAMutex::IsOwnedByCurrentThread() const -{ - bool theAnswer = true; - -#if TARGET_OS_MAC - theAnswer = pthread_equal(pthread_self(), mOwner); -#elif TARGET_OS_WIN32 - theAnswer = (mOwner == GetCurrentThreadId()); -#endif - - return theAnswer; -} - - -CAMutex::Unlocker::Unlocker(CAMutex& inMutex) -: mMutex(inMutex), - mNeedsLock(false) -{ - Assert(mMutex.IsOwnedByCurrentThread(), "Major problem: Unlocker attempted to unlock a mutex not owned by the current thread!"); - - mMutex.Unlock(); - mNeedsLock = true; -} - -CAMutex::Unlocker::~Unlocker() -{ - if(mNeedsLock) - { - mMutex.Lock(); - } -} diff --git a/src/CoreAudio/CoreAudioComponent/PublicUtility/CAMutex.h b/src/CoreAudio/CoreAudioComponent/PublicUtility/CAMutex.h deleted file mode 100644 index 093066b40..000000000 --- a/src/CoreAudio/CoreAudioComponent/PublicUtility/CAMutex.h +++ /dev/null @@ -1,163 +0,0 @@ -/* - File: CAMutex.h - Abstract: Part of CoreAudio Utility Classes - Version: 1.1 - - Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple - Inc. ("Apple") in consideration of your agreement to the following - terms, and your use, installation, modification or redistribution of - this Apple software constitutes acceptance of these terms. If you do - not agree with these terms, please do not use, install, modify or - redistribute this Apple software. - - In consideration of your agreement to abide by the following terms, and - subject to these terms, Apple grants you a personal, non-exclusive - license, under Apple's copyrights in this original Apple software (the - "Apple Software"), to use, reproduce, modify and redistribute the Apple - Software, with or without modifications, in source and/or binary forms; - provided that if you redistribute the Apple Software in its entirety and - without modifications, you must retain this notice and the following - text and disclaimers in all such redistributions of the Apple Software. - Neither the name, trademarks, service marks or logos of Apple Inc. may - be used to endorse or promote products derived from the Apple Software - without specific prior written permission from Apple. Except as - expressly stated in this notice, no other rights or licenses, express or - implied, are granted by Apple herein, including but not limited to any - patent rights that may be infringed by your derivative works or by other - works in which the Apple Software may be incorporated. - - The Apple Software is provided by Apple on an "AS IS" basis. APPLE - MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION - THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS - FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND - OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS. - - IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL - OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, - MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED - AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), - STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE - POSSIBILITY OF SUCH DAMAGE. - - Copyright (C) 2014 Apple Inc. All Rights Reserved. - -*/ -#ifndef __CAMutex_h__ -#define __CAMutex_h__ - -//================================================================================================== -// Includes -//================================================================================================== - -// System Includes -#if !defined(__COREAUDIO_USE_FLAT_INCLUDES__) - #include -#else - #include -#endif - -#if TARGET_OS_MAC - #include -#elif TARGET_OS_WIN32 - #include -#else - #error Unsupported operating system -#endif - -//================================================================================================== -// A recursive mutex. -//================================================================================================== - -class CAMutex -{ -// Construction/Destruction -public: - CAMutex(const char* inName); - virtual ~CAMutex(); - -// Actions -public: - virtual bool Lock(); - virtual void Unlock(); - virtual bool Try(bool& outWasLocked); // returns true if lock is free, false if not - - virtual bool IsFree() const; - virtual bool IsOwnedByCurrentThread() const; - -// Implementation -protected: - const char* mName; -#if TARGET_OS_MAC - pthread_t mOwner; - pthread_mutex_t mMutex; -#elif TARGET_OS_WIN32 - UInt32 mOwner; - HANDLE mMutex; -#endif - -// Helper class to manage taking and releasing recursively -public: - class Locker - { - - // Construction/Destruction - public: - Locker(CAMutex& inMutex) : mMutex(&inMutex), mNeedsRelease(false) { mNeedsRelease = mMutex->Lock(); } - Locker(CAMutex* inMutex) : mMutex(inMutex), mNeedsRelease(false) { mNeedsRelease = (mMutex != NULL && mMutex->Lock()); } - // in this case the mutex can be null - ~Locker() { if(mNeedsRelease) { mMutex->Unlock(); } } - - - private: - Locker(const Locker&); - Locker& operator=(const Locker&); - - // Implementation - private: - CAMutex* mMutex; - bool mNeedsRelease; - - }; - -// Unlocker - class Unlocker - { - public: - Unlocker(CAMutex& inMutex); - ~Unlocker(); - - private: - CAMutex& mMutex; - bool mNeedsLock; - - // Hidden definitions of copy ctor, assignment operator - Unlocker(const Unlocker& copy); // Not implemented - Unlocker& operator=(const Unlocker& copy); // Not implemented - }; - -// you can use this with Try - if you take the lock in try, pass in the outWasLocked var - class Tryer { - - // Construction/Destruction - public: - Tryer (CAMutex &mutex) : mMutex(mutex), mNeedsRelease(false), mHasLock(false) { mHasLock = mMutex.Try (mNeedsRelease); } - ~Tryer () { if (mNeedsRelease) mMutex.Unlock(); } - - bool HasLock () const { return mHasLock; } - - private: - Tryer(const Tryer&); - Tryer& operator=(const Tryer&); - - // Implementation - private: - CAMutex & mMutex; - bool mNeedsRelease; - bool mHasLock; - }; -}; - - -#endif // __CAMutex_h__ diff --git a/src/CoreAudio/CoreAudioComponent/PublicUtility/CAReferenceCounted.h b/src/CoreAudio/CoreAudioComponent/PublicUtility/CAReferenceCounted.h deleted file mode 100644 index f00fc6167..000000000 --- a/src/CoreAudio/CoreAudioComponent/PublicUtility/CAReferenceCounted.h +++ /dev/null @@ -1,97 +0,0 @@ -/* - File: CAReferenceCounted.h - Abstract: Part of CoreAudio Utility Classes - Version: 1.1 - - Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple - Inc. ("Apple") in consideration of your agreement to the following - terms, and your use, installation, modification or redistribution of - this Apple software constitutes acceptance of these terms. If you do - not agree with these terms, please do not use, install, modify or - redistribute this Apple software. - - In consideration of your agreement to abide by the following terms, and - subject to these terms, Apple grants you a personal, non-exclusive - license, under Apple's copyrights in this original Apple software (the - "Apple Software"), to use, reproduce, modify and redistribute the Apple - Software, with or without modifications, in source and/or binary forms; - provided that if you redistribute the Apple Software in its entirety and - without modifications, you must retain this notice and the following - text and disclaimers in all such redistributions of the Apple Software. - Neither the name, trademarks, service marks or logos of Apple Inc. may - be used to endorse or promote products derived from the Apple Software - without specific prior written permission from Apple. Except as - expressly stated in this notice, no other rights or licenses, express or - implied, are granted by Apple herein, including but not limited to any - patent rights that may be infringed by your derivative works or by other - works in which the Apple Software may be incorporated. - - The Apple Software is provided by Apple on an "AS IS" basis. APPLE - MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION - THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS - FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND - OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS. - - IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL - OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, - MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED - AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), - STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE - POSSIBILITY OF SUCH DAMAGE. - - Copyright (C) 2014 Apple Inc. All Rights Reserved. - -*/ -#ifndef __CAReferenceCounted_h__ -#define __CAReferenceCounted_h__ - -#include "CAAtomic.h" - -// base class for reference-counted objects -class CAReferenceCounted { -public: - CAReferenceCounted() : mRefCount(1) {} - - void retain() { CAAtomicIncrement32(&mRefCount); } - - void release() - { - SInt32 rc = CAAtomicDecrement32(&mRefCount); - if (rc == 0) { - releaseObject(); - } - } - - - class Retainer { - public: - Retainer(CAReferenceCounted *obj) : mObject(obj) { mObject->retain(); } - ~Retainer() { mObject->release(); } - - private: - CAReferenceCounted * mObject; - }; - -protected: - virtual ~CAReferenceCounted() { } - - virtual void releaseObject () - { - delete this; - } - -#if DEBUG -public: -#endif - SInt32 GetReferenceCount() const { return mRefCount; } -private: - SInt32 mRefCount; - - CAReferenceCounted(const CAReferenceCounted &a); - CAReferenceCounted &operator=(const CAReferenceCounted &a); -}; - - -#endif // __CAReferenceCounted_h__ diff --git a/src/CoreAudio/CoreAudioComponent/PublicUtility/CAStreamBasicDescription.cpp b/src/CoreAudio/CoreAudioComponent/PublicUtility/CAStreamBasicDescription.cpp deleted file mode 100644 index d56947ab5..000000000 --- a/src/CoreAudio/CoreAudioComponent/PublicUtility/CAStreamBasicDescription.cpp +++ /dev/null @@ -1,879 +0,0 @@ -/* - File: CAStreamBasicDescription.cpp - Abstract: CAStreamBasicDescription.h - Version: 1.1 - - Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple - Inc. ("Apple") in consideration of your agreement to the following - terms, and your use, installation, modification or redistribution of - this Apple software constitutes acceptance of these terms. If you do - not agree with these terms, please do not use, install, modify or - redistribute this Apple software. - - In consideration of your agreement to abide by the following terms, and - subject to these terms, Apple grants you a personal, non-exclusive - license, under Apple's copyrights in this original Apple software (the - "Apple Software"), to use, reproduce, modify and redistribute the Apple - Software, with or without modifications, in source and/or binary forms; - provided that if you redistribute the Apple Software in its entirety and - without modifications, you must retain this notice and the following - text and disclaimers in all such redistributions of the Apple Software. - Neither the name, trademarks, service marks or logos of Apple Inc. may - be used to endorse or promote products derived from the Apple Software - without specific prior written permission from Apple. Except as - expressly stated in this notice, no other rights or licenses, express or - implied, are granted by Apple herein, including but not limited to any - patent rights that may be infringed by your derivative works or by other - works in which the Apple Software may be incorporated. - - The Apple Software is provided by Apple on an "AS IS" basis. APPLE - MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION - THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS - FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND - OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS. - - IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL - OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, - MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED - AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), - STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE - POSSIBILITY OF SUCH DAMAGE. - - Copyright (C) 2014 Apple Inc. All Rights Reserved. - -*/ -#include "CAStreamBasicDescription.h" -#include "CAMath.h" - -#if !defined(__COREAUDIO_USE_FLAT_INCLUDES__) - #include -#else - #include -#endif - -#pragma mark This file needs to compile on earlier versions of the OS, so please keep that in mind when editing it - -char *CAStringForOSType (OSType t, char *writeLocation, size_t bufsize) -{ - if (bufsize > 0) { - char *p = writeLocation, *pend = writeLocation + bufsize; - union { UInt32 i; unsigned char str[4]; } u; - unsigned char *q = u.str; - u.i = CFSwapInt32HostToBig(t); - - bool hasNonPrint = false; - for (int i = 0; i < 4; ++i) { - if (!(isprint(*q) && *q != '\\')) { - hasNonPrint = true; - break; - } - q++; - } - q = u.str; - - if (hasNonPrint) - p += snprintf (p, pend - p, "0x"); - else if (p < pend) - *p++ = '\''; - - for (int i = 0; i < 4 && p < pend; ++i) { - if (hasNonPrint) { - p += snprintf(p, pend - p, "%02X", *q++); - } else { - *p++ = *q++; - } - } - if (!hasNonPrint && p < pend) - *p++ = '\''; - if (p >= pend) p -= 1; - *p = '\0'; - } - return writeLocation; -} - - -const AudioStreamBasicDescription CAStreamBasicDescription::sEmpty = { 0.0, 0, 0, 0, 0, 0, 0, 0, 0 }; - -CAStreamBasicDescription::CAStreamBasicDescription() -{ - memset (this, 0, sizeof(AudioStreamBasicDescription)); -} - -CAStreamBasicDescription::CAStreamBasicDescription(const AudioStreamBasicDescription &desc) -{ - SetFrom(desc); -} - - -CAStreamBasicDescription::CAStreamBasicDescription(double inSampleRate, UInt32 inFormatID, - UInt32 inBytesPerPacket, UInt32 inFramesPerPacket, - UInt32 inBytesPerFrame, UInt32 inChannelsPerFrame, - UInt32 inBitsPerChannel, UInt32 inFormatFlags) -{ - mSampleRate = inSampleRate; - mFormatID = inFormatID; - mBytesPerPacket = inBytesPerPacket; - mFramesPerPacket = inFramesPerPacket; - mBytesPerFrame = inBytesPerFrame; - mChannelsPerFrame = inChannelsPerFrame; - mBitsPerChannel = inBitsPerChannel; - mFormatFlags = inFormatFlags; - mReserved = 0; -} - -char *CAStreamBasicDescription::AsString(char *buf, size_t _bufsize, bool brief /*=false*/) const -{ - int bufsize = (int)_bufsize; // must be signed to protect against overflow - char *theBuffer = buf; - int nc; - char formatID[24]; - CAStringForOSType(mFormatID, formatID, sizeof(formatID)); - if (brief) { - CommonPCMFormat com; - bool interleaved; - if (IdentifyCommonPCMFormat(com, &interleaved) && com != kPCMFormatOther) { - const char *desc; - switch (com) { - case kPCMFormatInt16: - desc = "Int16"; - break; - case kPCMFormatFixed824: - desc = "Int8.24"; - break; - case kPCMFormatFloat32: - desc = "Float32"; - break; - case kPCMFormatFloat64: - desc = "Float64"; - break; - default: - desc = NULL; - break; - } - if (desc) { - const char *inter =""; - if (mChannelsPerFrame > 1) - inter = !interleaved ? ", non-inter" : ", inter"; - snprintf(buf, static_cast(bufsize), "%2d ch, %6.0f Hz, %s%s", (int)mChannelsPerFrame, mSampleRate, desc, inter); - return theBuffer; - } - } - if (mChannelsPerFrame == 0 && mSampleRate == 0.0 && mFormatID == 0) { - snprintf(buf, static_cast(bufsize), "%2d ch, %6.0f Hz", (int)mChannelsPerFrame, mSampleRate); - return theBuffer; - } - } - - nc = snprintf(buf, static_cast(bufsize), "%2d ch, %6.0f Hz, %s (0x%08X) ", (int)NumberChannels(), mSampleRate, formatID, (int)mFormatFlags); - buf += nc; if ((bufsize -= nc) <= 0) goto exit; - if (mFormatID == kAudioFormatLinearPCM) { - bool isInt = !(mFormatFlags & kLinearPCMFormatFlagIsFloat); - int wordSize = static_cast(SampleWordSize()); - const char *endian = (wordSize > 1) ? - ((mFormatFlags & kLinearPCMFormatFlagIsBigEndian) ? " big-endian" : " little-endian" ) : ""; - const char *sign = isInt ? - ((mFormatFlags & kLinearPCMFormatFlagIsSignedInteger) ? " signed" : " unsigned") : ""; - const char *floatInt = isInt ? "integer" : "float"; - char packed[32]; - if (wordSize > 0 && PackednessIsSignificant()) { - if (mFormatFlags & kLinearPCMFormatFlagIsPacked) - snprintf(packed, sizeof(packed), "packed in %d bytes", wordSize); - else - snprintf(packed, sizeof(packed), "unpacked in %d bytes", wordSize); - } else - packed[0] = '\0'; - const char *align = (wordSize > 0 && AlignmentIsSignificant()) ? - ((mFormatFlags & kLinearPCMFormatFlagIsAlignedHigh) ? " high-aligned" : " low-aligned") : ""; - const char *deinter = (mFormatFlags & kAudioFormatFlagIsNonInterleaved) ? ", deinterleaved" : ""; - const char *commaSpace = (packed[0]!='\0') || (align[0]!='\0') ? ", " : ""; - char bitdepth[20]; - - int fracbits = (mFormatFlags & kLinearPCMFormatFlagsSampleFractionMask) >> kLinearPCMFormatFlagsSampleFractionShift; - if (fracbits > 0) - snprintf(bitdepth, sizeof(bitdepth), "%d.%d", (int)mBitsPerChannel - fracbits, fracbits); - else - snprintf(bitdepth, sizeof(bitdepth), "%d", (int)mBitsPerChannel); - - /*nc =*/ snprintf(buf, static_cast(bufsize), "%s-bit%s%s %s%s%s%s%s", - bitdepth, endian, sign, floatInt, - commaSpace, packed, align, deinter); - // buf += nc; if ((bufsize -= nc) <= 0) goto exit; - } else if (mFormatID == kAudioFormatAppleLossless) { - int sourceBits = 0; - switch (mFormatFlags) - { - case 1: // kAppleLosslessFormatFlag_16BitSourceData - sourceBits = 16; - break; - case 2: // kAppleLosslessFormatFlag_20BitSourceData - sourceBits = 20; - break; - case 3: // kAppleLosslessFormatFlag_24BitSourceData - sourceBits = 24; - break; - case 4: // kAppleLosslessFormatFlag_32BitSourceData - sourceBits = 32; - break; - } - if (sourceBits) - nc = snprintf(buf, static_cast(bufsize), "from %d-bit source, ", sourceBits); - else - nc = snprintf(buf, static_cast(bufsize), "from UNKNOWN source bit depth, "); - buf += nc; if ((bufsize -= nc) <= 0) goto exit; - /*nc =*/ snprintf(buf, static_cast(bufsize), "%d frames/packet", (int)mFramesPerPacket); - // buf += nc; if ((bufsize -= nc) <= 0) goto exit; - } - else - /*nc =*/ snprintf(buf, static_cast(bufsize), "%d bits/channel, %d bytes/packet, %d frames/packet, %d bytes/frame", - (int)mBitsPerChannel, (int)mBytesPerPacket, (int)mFramesPerPacket, (int)mBytesPerFrame); -exit: - return theBuffer; -} - -void CAStreamBasicDescription::NormalizeLinearPCMFormat(AudioStreamBasicDescription& ioDescription) -{ - // the only thing that changes is to make mixable linear PCM into the canonical linear PCM format - if((ioDescription.mFormatID == kAudioFormatLinearPCM) && ((ioDescription.mFormatFlags & kIsNonMixableFlag) == 0)) - { - // the canonical linear PCM format - ioDescription.mFormatFlags = kAudioFormatFlagsCanonical; - ioDescription.mBytesPerPacket = SizeOf32(AudioSampleType) * ioDescription.mChannelsPerFrame; - ioDescription.mFramesPerPacket = 1; - ioDescription.mBytesPerFrame = SizeOf32(AudioSampleType) * ioDescription.mChannelsPerFrame; - ioDescription.mBitsPerChannel = 8 * SizeOf32(AudioSampleType); - } -} - -void CAStreamBasicDescription::NormalizeLinearPCMFormat(bool inNativeEndian, AudioStreamBasicDescription& ioDescription) -{ - // the only thing that changes is to make mixable linear PCM into the canonical linear PCM format - if((ioDescription.mFormatID == kAudioFormatLinearPCM) && ((ioDescription.mFormatFlags & kIsNonMixableFlag) == 0)) - { - // the canonical linear PCM format - ioDescription.mFormatFlags = kAudioFormatFlagIsFloat | kAudioFormatFlagIsPacked; - if(inNativeEndian) - { -#if TARGET_RT_BIG_ENDIAN - ioDescription.mFormatFlags |= kAudioFormatFlagIsBigEndian; -#endif - } - else - { -#if TARGET_RT_LITTLE_ENDIAN - ioDescription.mFormatFlags |= kAudioFormatFlagIsBigEndian; -#endif - } - ioDescription.mBytesPerPacket = SizeOf32(AudioSampleType) * ioDescription.mChannelsPerFrame; - ioDescription.mFramesPerPacket = 1; - ioDescription.mBytesPerFrame = SizeOf32(AudioSampleType) * ioDescription.mChannelsPerFrame; - ioDescription.mBitsPerChannel = 8 * SizeOf32(AudioSampleType); - } -} - -void CAStreamBasicDescription::ResetFormat(AudioStreamBasicDescription& ioDescription) -{ - ioDescription.mSampleRate = 0; - ioDescription.mFormatID = 0; - ioDescription.mBytesPerPacket = 0; - ioDescription.mFramesPerPacket = 0; - ioDescription.mBytesPerFrame = 0; - ioDescription.mChannelsPerFrame = 0; - ioDescription.mBitsPerChannel = 0; - ioDescription.mFormatFlags = 0; -} - -void CAStreamBasicDescription::FillOutFormat(AudioStreamBasicDescription& ioDescription, const AudioStreamBasicDescription& inTemplateDescription) -{ - if(fiszero(ioDescription.mSampleRate)) - { - ioDescription.mSampleRate = inTemplateDescription.mSampleRate; - } - if(ioDescription.mFormatID == 0) - { - ioDescription.mFormatID = inTemplateDescription.mFormatID; - } - if(ioDescription.mFormatFlags == 0) - { - ioDescription.mFormatFlags = inTemplateDescription.mFormatFlags; - } - if(ioDescription.mBytesPerPacket == 0) - { - ioDescription.mBytesPerPacket = inTemplateDescription.mBytesPerPacket; - } - if(ioDescription.mFramesPerPacket == 0) - { - ioDescription.mFramesPerPacket = inTemplateDescription.mFramesPerPacket; - } - if(ioDescription.mBytesPerFrame == 0) - { - ioDescription.mBytesPerFrame = inTemplateDescription.mBytesPerFrame; - } - if(ioDescription.mChannelsPerFrame == 0) - { - ioDescription.mChannelsPerFrame = inTemplateDescription.mChannelsPerFrame; - } - if(ioDescription.mBitsPerChannel == 0) - { - ioDescription.mBitsPerChannel = inTemplateDescription.mBitsPerChannel; - } -} - -void CAStreamBasicDescription::GetSimpleName(const AudioStreamBasicDescription& inDescription, char* outName, UInt32 inMaxNameLength, bool inAbbreviate, bool inIncludeSampleRate) -{ - if(inIncludeSampleRate) - { - int theCharactersWritten = snprintf(outName, inMaxNameLength, "%.0f ", inDescription.mSampleRate); - outName += theCharactersWritten; - inMaxNameLength -= static_cast(theCharactersWritten); - } - - switch(inDescription.mFormatID) - { - case kAudioFormatLinearPCM: - { - const char* theEndianString = NULL; - if((inDescription.mFormatFlags & kAudioFormatFlagIsBigEndian) != 0) - { - #if TARGET_RT_LITTLE_ENDIAN - theEndianString = "Big Endian"; - #endif - } - else - { - #if TARGET_RT_BIG_ENDIAN - theEndianString = "Little Endian"; - #endif - } - - const char* theKindString = NULL; - if((inDescription.mFormatFlags & kAudioFormatFlagIsFloat) != 0) - { - theKindString = (inAbbreviate ? "Float" : "Floating Point"); - } - else if((inDescription.mFormatFlags & kAudioFormatFlagIsSignedInteger) != 0) - { - theKindString = (inAbbreviate ? "SInt" : "Signed Integer"); - } - else - { - theKindString = (inAbbreviate ? "UInt" : "Unsigned Integer"); - } - - const char* thePackingString = NULL; - if((inDescription.mFormatFlags & kAudioFormatFlagIsPacked) == 0) - { - if((inDescription.mFormatFlags & kAudioFormatFlagIsAlignedHigh) != 0) - { - thePackingString = "High"; - } - else - { - thePackingString = "Low"; - } - } - - const char* theMixabilityString = NULL; - if((inDescription.mFormatFlags & kIsNonMixableFlag) == 0) - { - theMixabilityString = "Mixable"; - } - else - { - theMixabilityString = "Unmixable"; - } - - if(inAbbreviate) - { - if(theEndianString != NULL) - { - if(thePackingString != NULL) - { - snprintf(outName, inMaxNameLength, "%s %d Ch %s %s %s%d/%s%d", theMixabilityString, (int)inDescription.mChannelsPerFrame, theEndianString, thePackingString, theKindString, (int)inDescription.mBitsPerChannel, theKindString, (int)(inDescription.mBytesPerFrame / inDescription.mChannelsPerFrame) * 8); - } - else - { - snprintf(outName, inMaxNameLength, "%s %d Ch %s %s%d", theMixabilityString, (int)inDescription.mChannelsPerFrame, theEndianString, theKindString, (int)inDescription.mBitsPerChannel); - } - } - else - { - if(thePackingString != NULL) - { - snprintf(outName, inMaxNameLength, "%s %d Ch %s %s%d/%s%d", theMixabilityString, (int)inDescription.mChannelsPerFrame, thePackingString, theKindString, (int)inDescription.mBitsPerChannel, theKindString, (int)((inDescription.mBytesPerFrame / inDescription.mChannelsPerFrame) * 8)); - } - else - { - snprintf(outName, inMaxNameLength, "%s %d Ch %s%d", theMixabilityString, (int)inDescription.mChannelsPerFrame, theKindString, (int)inDescription.mBitsPerChannel); - } - } - } - else - { - if(theEndianString != NULL) - { - if(thePackingString != NULL) - { - snprintf(outName, inMaxNameLength, "%s %d Channel %d Bit %s %s Aligned %s in %d Bits", theMixabilityString, (int)inDescription.mChannelsPerFrame, (int)inDescription.mBitsPerChannel, theEndianString, theKindString, thePackingString, (int)(inDescription.mBytesPerFrame / inDescription.mChannelsPerFrame) * 8); - } - else - { - snprintf(outName, inMaxNameLength, "%s %d Channel %d Bit %s %s", theMixabilityString, (int)inDescription.mChannelsPerFrame, (int)inDescription.mBitsPerChannel, theEndianString, theKindString); - } - } - else - { - if(thePackingString != NULL) - { - snprintf(outName, inMaxNameLength, "%s %d Channel %d Bit %s Aligned %s in %d Bits", theMixabilityString, (int)inDescription.mChannelsPerFrame, (int)inDescription.mBitsPerChannel, theKindString, thePackingString, (int)(inDescription.mBytesPerFrame / inDescription.mChannelsPerFrame) * 8); - } - else - { - snprintf(outName, inMaxNameLength, "%s %d Channel %d Bit %s", theMixabilityString, (int)inDescription.mChannelsPerFrame, (int)inDescription.mBitsPerChannel, theKindString); - } - } - } - } - break; - - case kAudioFormatAC3: - strlcpy(outName, "AC-3", sizeof(outName)); - break; - - case kAudioFormat60958AC3: - strlcpy(outName, "AC-3 for SPDIF", sizeof(outName)); - break; - - default: - CACopy4CCToCString(outName, inDescription.mFormatID); - break; - }; -} - -#if CoreAudio_Debug -#include "CALogMacros.h" - -void CAStreamBasicDescription::PrintToLog(const AudioStreamBasicDescription& inDesc) -{ - PrintFloat (" Sample Rate: ", inDesc.mSampleRate); - Print4CharCode (" Format ID: ", inDesc.mFormatID); - PrintHex (" Format Flags: ", inDesc.mFormatFlags); - PrintInt (" Bytes per Packet: ", inDesc.mBytesPerPacket); - PrintInt (" Frames per Packet: ", inDesc.mFramesPerPacket); - PrintInt (" Bytes per Frame: ", inDesc.mBytesPerFrame); - PrintInt (" Channels per Frame: ", inDesc.mChannelsPerFrame); - PrintInt (" Bits per Channel: ", inDesc.mBitsPerChannel); -} -#endif - -bool operator<(const AudioStreamBasicDescription& x, const AudioStreamBasicDescription& y) -{ - bool theAnswer = false; - bool isDone = false; - - // note that if either side is 0, that field is skipped - - // format ID is the first order sort - if((!isDone) && ((x.mFormatID != 0) && (y.mFormatID != 0))) - { - if(x.mFormatID != y.mFormatID) - { - // formats are sorted numerically except that linear - // PCM is always first - if(x.mFormatID == kAudioFormatLinearPCM) - { - theAnswer = true; - } - else if(y.mFormatID == kAudioFormatLinearPCM) - { - theAnswer = false; - } - else - { - theAnswer = x.mFormatID < y.mFormatID; - } - isDone = true; - } - } - - - // mixable is always better than non-mixable for linear PCM and should be the second order sort item - if((!isDone) && ((x.mFormatID == kAudioFormatLinearPCM) && (y.mFormatID == kAudioFormatLinearPCM))) - { - if(((x.mFormatFlags & kIsNonMixableFlag) == 0) && ((y.mFormatFlags & kIsNonMixableFlag) != 0)) - { - theAnswer = true; - isDone = true; - } - else if(((x.mFormatFlags & kIsNonMixableFlag) != 0) && ((y.mFormatFlags & kIsNonMixableFlag) == 0)) - { - theAnswer = false; - isDone = true; - } - } - - // floating point vs integer for linear PCM only - if((!isDone) && ((x.mFormatID == kAudioFormatLinearPCM) && (y.mFormatID == kAudioFormatLinearPCM))) - { - if((x.mFormatFlags & kAudioFormatFlagIsFloat) != (y.mFormatFlags & kAudioFormatFlagIsFloat)) - { - // floating point is better than integer - theAnswer = y.mFormatFlags & kAudioFormatFlagIsFloat; - isDone = true; - } - } - - // bit depth - if((!isDone) && ((x.mBitsPerChannel != 0) && (y.mBitsPerChannel != 0))) - { - if(x.mBitsPerChannel != y.mBitsPerChannel) - { - // deeper bit depths are higher quality - theAnswer = x.mBitsPerChannel < y.mBitsPerChannel; - isDone = true; - } - } - - // sample rate - if((!isDone) && fnonzero(x.mSampleRate) && fnonzero(y.mSampleRate)) - { - if(fnotequal(x.mSampleRate, y.mSampleRate)) - { - // higher sample rates are higher quality - theAnswer = x.mSampleRate < y.mSampleRate; - isDone = true; - } - } - - // number of channels - if((!isDone) && ((x.mChannelsPerFrame != 0) && (y.mChannelsPerFrame != 0))) - { - if(x.mChannelsPerFrame != y.mChannelsPerFrame) - { - // more channels is higher quality - theAnswer = x.mChannelsPerFrame < y.mChannelsPerFrame; - //isDone = true; - } - } - - return theAnswer; -} - -void CAStreamBasicDescription::ModifyFormatFlagsForMatching(const AudioStreamBasicDescription& x, const AudioStreamBasicDescription& y, UInt32& xFlags, UInt32& yFlags, bool converterOnly ) -{ - // match wildcards - if (x.mFormatID == 0 || y.mFormatID == 0 || xFlags == 0 || yFlags == 0) - { - // Obliterate all flags. - xFlags = yFlags = 0; - return; - } - - if (x.mFormatID == kAudioFormatLinearPCM) { - // knock off the all clear flag - xFlags = xFlags & ~kAudioFormatFlagsAreAllClear; - yFlags = yFlags & ~kAudioFormatFlagsAreAllClear; - - // if both kAudioFormatFlagIsPacked bits are set, then we don't care about the kAudioFormatFlagIsAlignedHigh bit. - if (xFlags & yFlags & kAudioFormatFlagIsPacked) { - xFlags = xFlags & ~static_cast(kAudioFormatFlagIsAlignedHigh); - yFlags = yFlags & ~static_cast(kAudioFormatFlagIsAlignedHigh); - } - - // if both kAudioFormatFlagIsFloat bits are set, then we don't care about the kAudioFormatFlagIsSignedInteger bit. - if (xFlags & yFlags & kAudioFormatFlagIsFloat) { - xFlags = xFlags & ~static_cast(kAudioFormatFlagIsSignedInteger); - yFlags = yFlags & ~static_cast(kAudioFormatFlagIsSignedInteger); - } - - // if the bit depth is 8 bits or less and the format is packed, we don't care about endianness - if((x.mBitsPerChannel <= 8) && ((xFlags & kAudioFormatFlagIsPacked) == kAudioFormatFlagIsPacked)) - { - xFlags = xFlags & ~static_cast(kAudioFormatFlagIsBigEndian); - } - if((y.mBitsPerChannel <= 8) && ((yFlags & kAudioFormatFlagIsPacked) == kAudioFormatFlagIsPacked)) - { - yFlags = yFlags & ~static_cast(kAudioFormatFlagIsBigEndian); - } - - // if the number of channels is 1, we don't care about non-interleavedness - if (x.mChannelsPerFrame == 1 && y.mChannelsPerFrame == 1) { - xFlags &= ~static_cast(kLinearPCMFormatFlagIsNonInterleaved); - yFlags &= ~static_cast(kLinearPCMFormatFlagIsNonInterleaved); - } - - if (converterOnly) { - CAStreamBasicDescription cas_x = CAStreamBasicDescription(x); - CAStreamBasicDescription cas_y = CAStreamBasicDescription(y); - if (!cas_x.PackednessIsSignificant() && !cas_y.PackednessIsSignificant()) { - xFlags &= ~static_cast(kAudioFormatFlagIsPacked); - yFlags &= ~static_cast(kAudioFormatFlagIsPacked); - } - if (!cas_x.AlignmentIsSignificant() && !cas_y.AlignmentIsSignificant()) { - xFlags &= ~static_cast(kAudioFormatFlagIsAlignedHigh); - yFlags &= ~static_cast(kAudioFormatFlagIsAlignedHigh); - } - // We don't care about whether the streams are mixable in this case - xFlags &= ~static_cast(kAudioFormatFlagIsNonMixable); - yFlags &= ~static_cast(kAudioFormatFlagIsNonMixable); - } - } -} - -static bool MatchFormatFlags(const AudioStreamBasicDescription& x, const AudioStreamBasicDescription& y) -{ - UInt32 xFlags = x.mFormatFlags; - UInt32 yFlags = y.mFormatFlags; - - CAStreamBasicDescription::ModifyFormatFlagsForMatching(x, y, xFlags, yFlags, false); - return xFlags == yFlags; -} - -bool operator==(const AudioStreamBasicDescription& x, const AudioStreamBasicDescription& y) -{ - // the semantics for equality are: - // 1) Values must match exactly -- except for PCM format flags, see above. - // 2) wildcard's are ignored in the comparison - -#define MATCH(name) ((x.name) == 0 || (y.name) == 0 || (x.name) == (y.name)) - - return - // check all but the format flags - CAStreamBasicDescription::FlagIndependentEquivalence(x, y) - // check the format flags - && MatchFormatFlags(x, y); -} - -bool CAStreamBasicDescription::FlagIndependentEquivalence(const AudioStreamBasicDescription &x, const AudioStreamBasicDescription &y) -{ - return - // check the sample rate - (fiszero(x.mSampleRate) || fiszero(y.mSampleRate) || fequal(x.mSampleRate, y.mSampleRate)) - - // check the format ids - && MATCH(mFormatID) - - // check the bytes per packet - && MATCH(mBytesPerPacket) - - // check the frames per packet - && MATCH(mFramesPerPacket) - - // check the bytes per frame - && MATCH(mBytesPerFrame) - - // check the channels per frame - && MATCH(mChannelsPerFrame) - - // check the channels per frame - && MATCH(mBitsPerChannel) ; -} - -bool CAStreamBasicDescription::IsEqual(const AudioStreamBasicDescription &other, bool interpretingWildcards) const -{ - if (interpretingWildcards) - return *this == other; - return memcmp(this, &other, offsetof(AudioStreamBasicDescription, mReserved)) == 0; -} - -bool CAStreamBasicDescription::IsFunctionallyEquivalent(const AudioStreamBasicDescription &x, const AudioStreamBasicDescription &y) -{ - UInt32 xFlags = x.mFormatFlags, yFlags = y.mFormatFlags; - CAStreamBasicDescription::ModifyFormatFlagsForMatching(x, y, xFlags, yFlags, true); - - return - // check all but the format flags - CAStreamBasicDescription::FlagIndependentEquivalence(x, y) - // check the format flags with converter focus - && (xFlags == yFlags); - -} - -bool SanityCheck(const AudioStreamBasicDescription& x) -{ - // This function returns false if there are sufficiently insane values in any field. - // It is very conservative so even some very unlikely values will pass. - // This is just meant to catch the case where the data from a file is corrupted. - - return - (x.mSampleRate >= 0.) - && (x.mSampleRate < 3e6) // SACD sample rate is 2.8224 MHz - && (x.mBytesPerPacket < 1000000) - && (x.mFramesPerPacket < 1000000) - && (x.mBytesPerFrame < 1000000) - && (x.mChannelsPerFrame <= 1024) - && (x.mBitsPerChannel <= 1024) - && (x.mFormatID != 0) - && !(x.mFormatID == kAudioFormatLinearPCM && (x.mFramesPerPacket != 1 || x.mBytesPerPacket != x.mBytesPerFrame)); -} - -bool CAStreamBasicDescription::FromText(const char *inTextDesc, AudioStreamBasicDescription &fmt) -{ - const char *p = inTextDesc; - - memset(&fmt, 0, sizeof(fmt)); - - bool isPCM = true; // until proven otherwise - UInt32 pcmFlags = kAudioFormatFlagIsPacked | kAudioFormatFlagIsSignedInteger; - - if (p[0] == '-') // previously we required a leading dash on PCM formats - ++p; - - if (p[0] == 'B' && p[1] == 'E') { - pcmFlags |= kLinearPCMFormatFlagIsBigEndian; - p += 2; - } else if (p[0] == 'L' && p[1] == 'E') { - p += 2; - } else { - // default is native-endian -#if TARGET_RT_BIG_ENDIAN - pcmFlags |= kLinearPCMFormatFlagIsBigEndian; -#endif - } - if (p[0] == 'F') { - pcmFlags = (pcmFlags & ~static_cast(kAudioFormatFlagIsSignedInteger)) | kAudioFormatFlagIsFloat; - ++p; - } else { - if (p[0] == 'U') { - pcmFlags &= ~static_cast(kAudioFormatFlagIsSignedInteger); - ++p; - } - if (p[0] == 'I') - ++p; - else { - // it's not PCM; presumably some other format (NOT VALIDATED; use AudioFormat for that) - isPCM = false; - p = inTextDesc; // go back to the beginning - char buf[4] = { ' ',' ',' ',' ' }; - for (int i = 0; i < 4; ++i) { - if (*p != '\\') { - if ((buf[i] = *p++) == '\0') { - // special-case for 'aac' - if (i != 3) return false; - --p; // keep pointing at the terminating null - buf[i] = ' '; - break; - } - } else { - // "\xNN" is a hex byte - if (*++p != 'x') return false; - int x; - if (sscanf(++p, "%02X", &x) != 1) return false; - buf[i] = static_cast(x); - p += 2; - } - } - - if (strchr("-@/#", buf[3])) { - // further special-casing for 'aac' - buf[3] = ' '; - --p; - } - - memcpy(&fmt.mFormatID, buf, 4); - fmt.mFormatID = CFSwapInt32BigToHost(fmt.mFormatID); - } - } - - if (isPCM) { - fmt.mFormatID = kAudioFormatLinearPCM; - fmt.mFormatFlags = pcmFlags; - fmt.mFramesPerPacket = 1; - fmt.mChannelsPerFrame = 1; - UInt32 bitdepth = 0, fracbits = 0; - while (isdigit(*p)) - bitdepth = 10 * bitdepth + static_cast(*p++ - '0'); - if (*p == '.') { - ++p; - if (!isdigit(*p)) { - fprintf(stderr, "Expected fractional bits following '.'\n"); - goto Bail; - } - while (isdigit(*p)) - fracbits = 10 * fracbits + static_cast(*p++ - '0'); - bitdepth += fracbits; - fmt.mFormatFlags |= (fracbits << kLinearPCMFormatFlagsSampleFractionShift); - } - fmt.mBitsPerChannel = bitdepth; - fmt.mBytesPerPacket = fmt.mBytesPerFrame = (bitdepth + 7) / 8; - if (bitdepth & 7) { - // assume unpacked. (packed odd bit depths are describable but not supported in AudioConverter.) - fmt.mFormatFlags &= ~static_cast(kLinearPCMFormatFlagIsPacked); - // alignment matters; default to high-aligned. use ':L_' for low. - fmt.mFormatFlags |= kLinearPCMFormatFlagIsAlignedHigh; - } - } - if (*p == '@') { - ++p; - while (isdigit(*p)) - fmt.mSampleRate = 10 * fmt.mSampleRate + (*p++ - '0'); - } - if (*p == '/') { - UInt32 flags = 0; - while (true) { - char c = *++p; - if (c >= '0' && c <= '9') - flags = (flags << 4) | static_cast(c - '0'); - else if (c >= 'A' && c <= 'F') - flags = (flags << 4) | static_cast(c - 'A' + 10); - else if (c >= 'a' && c <= 'f') - flags = (flags << 4) | static_cast(c - 'a' + 10); - else break; - } - fmt.mFormatFlags = flags; - } - if (*p == '#') { - ++p; - while (isdigit(*p)) - fmt.mFramesPerPacket = 10 * fmt.mFramesPerPacket + static_cast(*p++ - '0'); - } - if (*p == ':') { - ++p; - fmt.mFormatFlags &= ~static_cast(kLinearPCMFormatFlagIsPacked); - if (*p == 'L') - fmt.mFormatFlags &= ~static_cast(kLinearPCMFormatFlagIsAlignedHigh); - else if (*p == 'H') - fmt.mFormatFlags |= kLinearPCMFormatFlagIsAlignedHigh; - else - goto Bail; - ++p; - UInt32 bytesPerFrame = 0; - while (isdigit(*p)) - bytesPerFrame = 10 * bytesPerFrame + static_cast(*p++ - '0'); - fmt.mBytesPerFrame = fmt.mBytesPerPacket = bytesPerFrame; - } - if (*p == ',') { - ++p; - int ch = 0; - while (isdigit(*p)) - ch = 10 * ch + (*p++ - '0'); - fmt.mChannelsPerFrame = static_cast(ch); - if (*p == 'D') { - ++p; - if (fmt.mFormatID != kAudioFormatLinearPCM) { - fprintf(stderr, "non-interleaved flag invalid for non-PCM formats\n"); - goto Bail; - } - fmt.mFormatFlags |= kAudioFormatFlagIsNonInterleaved; - } else { - if (*p == 'I') ++p; // default - if (fmt.mFormatID == kAudioFormatLinearPCM) - fmt.mBytesPerPacket = fmt.mBytesPerFrame *= static_cast(ch); - } - } - if (*p != '\0') { - fprintf(stderr, "extra characters at end of format string: %s\n", p); - goto Bail; - } - return true; - -Bail: - fprintf(stderr, "Invalid format string: %s\n", inTextDesc); - fprintf(stderr, "Syntax of format strings is: \n"); - return false; -} - -const char *CAStreamBasicDescription::sTextParsingUsageString = - "format[@sample_rate_hz][/format_flags][#frames_per_packet][:LHbytesPerFrame][,channelsDI].\n" - "Format for PCM is [-][BE|LE]{F|I|UI}{bitdepth}; else a 4-char format code (e.g. aac, alac).\n"; diff --git a/src/CoreAudio/CoreAudioComponent/PublicUtility/CAStreamBasicDescription.h b/src/CoreAudio/CoreAudioComponent/PublicUtility/CAStreamBasicDescription.h deleted file mode 100644 index 8b81dba69..000000000 --- a/src/CoreAudio/CoreAudioComponent/PublicUtility/CAStreamBasicDescription.h +++ /dev/null @@ -1,424 +0,0 @@ -/* - File: CAStreamBasicDescription.h - Abstract: Part of CoreAudio Utility Classes - Version: 1.1 - - Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple - Inc. ("Apple") in consideration of your agreement to the following - terms, and your use, installation, modification or redistribution of - this Apple software constitutes acceptance of these terms. If you do - not agree with these terms, please do not use, install, modify or - redistribute this Apple software. - - In consideration of your agreement to abide by the following terms, and - subject to these terms, Apple grants you a personal, non-exclusive - license, under Apple's copyrights in this original Apple software (the - "Apple Software"), to use, reproduce, modify and redistribute the Apple - Software, with or without modifications, in source and/or binary forms; - provided that if you redistribute the Apple Software in its entirety and - without modifications, you must retain this notice and the following - text and disclaimers in all such redistributions of the Apple Software. - Neither the name, trademarks, service marks or logos of Apple Inc. may - be used to endorse or promote products derived from the Apple Software - without specific prior written permission from Apple. Except as - expressly stated in this notice, no other rights or licenses, express or - implied, are granted by Apple herein, including but not limited to any - patent rights that may be infringed by your derivative works or by other - works in which the Apple Software may be incorporated. - - The Apple Software is provided by Apple on an "AS IS" basis. APPLE - MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION - THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS - FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND - OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS. - - IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL - OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, - MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED - AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), - STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE - POSSIBILITY OF SUCH DAMAGE. - - Copyright (C) 2014 Apple Inc. All Rights Reserved. - -*/ -#ifndef __CAStreamBasicDescription_h__ -#define __CAStreamBasicDescription_h__ - -#if !defined(__COREAUDIO_USE_FLAT_INCLUDES__) - #include - #include -#else - #include "CoreAudioTypes.h" - #include "CoreFoundation.h" -#endif - -#include "CADebugMacros.h" -#include // for memset, memcpy -#include // for FILE * - -#pragma mark This file needs to compile on more earlier versions of the OS, so please keep that in mind when editing it - -extern char *CAStringForOSType (OSType t, char *writeLocation, size_t bufsize); - -// define Leopard specific symbols for backward compatibility if applicable -#if COREAUDIOTYPES_VERSION < 1050 -typedef Float32 AudioSampleType; -enum { kAudioFormatFlagsCanonical = kAudioFormatFlagIsFloat | kAudioFormatFlagsNativeEndian | kAudioFormatFlagIsPacked }; -#endif -#if COREAUDIOTYPES_VERSION < 1051 -typedef Float32 AudioUnitSampleType; -enum { - kLinearPCMFormatFlagsSampleFractionShift = 7, - kLinearPCMFormatFlagsSampleFractionMask = (0x3F << kLinearPCMFormatFlagsSampleFractionShift), -}; -#endif - -// define the IsMixable format flag for all versions of the system -#if (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_3) - enum { kIsNonMixableFlag = kAudioFormatFlagIsNonMixable }; -#else - enum { kIsNonMixableFlag = (1L << 6) }; -#endif - -//============================================================================= -// CAStreamBasicDescription -// -// This is a wrapper class for the AudioStreamBasicDescription struct. -// It adds a number of convenience routines, but otherwise adds nothing -// to the footprint of the original struct. -//============================================================================= -class CAStreamBasicDescription : - public AudioStreamBasicDescription -{ - -// Constants -public: - static const AudioStreamBasicDescription sEmpty; - - enum CommonPCMFormat { - kPCMFormatOther = 0, - kPCMFormatFloat32 = 1, - kPCMFormatInt16 = 2, - kPCMFormatFixed824 = 3, - kPCMFormatFloat64 = 4 - }; - -// Construction/Destruction -public: - CAStreamBasicDescription(); - - CAStreamBasicDescription(const AudioStreamBasicDescription &desc); - - CAStreamBasicDescription( double inSampleRate, UInt32 inFormatID, - UInt32 inBytesPerPacket, UInt32 inFramesPerPacket, - UInt32 inBytesPerFrame, UInt32 inChannelsPerFrame, - UInt32 inBitsPerChannel, UInt32 inFormatFlags); - - CAStreamBasicDescription( double inSampleRate, UInt32 inNumChannels, CommonPCMFormat pcmf, bool inIsInterleaved) { - unsigned wordsize; - - mSampleRate = inSampleRate; - mFormatID = kAudioFormatLinearPCM; - mFormatFlags = kAudioFormatFlagsNativeEndian | kAudioFormatFlagIsPacked; - mFramesPerPacket = 1; - mChannelsPerFrame = inNumChannels; - mBytesPerFrame = mBytesPerPacket = 0; - mReserved = 0; - - switch (pcmf) { - default: - return; - case kPCMFormatFloat32: - wordsize = 4; - mFormatFlags |= kAudioFormatFlagIsFloat; - break; - case kPCMFormatFloat64: - wordsize = 8; - mFormatFlags |= kAudioFormatFlagIsFloat; - break; - case kPCMFormatInt16: - wordsize = 2; - mFormatFlags |= kAudioFormatFlagIsSignedInteger; - break; - case kPCMFormatFixed824: - wordsize = 4; - mFormatFlags |= kAudioFormatFlagIsSignedInteger | (24 << kLinearPCMFormatFlagsSampleFractionShift); - break; - } - mBitsPerChannel = wordsize * 8; - if (inIsInterleaved) - mBytesPerFrame = mBytesPerPacket = wordsize * inNumChannels; - else { - mFormatFlags |= kAudioFormatFlagIsNonInterleaved; - mBytesPerFrame = mBytesPerPacket = wordsize; - } - } - -// Assignment - CAStreamBasicDescription& operator=(const AudioStreamBasicDescription& v) { SetFrom(v); return *this; } - - void SetFrom(const AudioStreamBasicDescription &desc) - { - memcpy(this, &desc, sizeof(AudioStreamBasicDescription)); - } - - bool FromText(const char *inTextDesc) { return FromText(inTextDesc, *this); } - static bool FromText(const char *inTextDesc, AudioStreamBasicDescription &outDesc); - // return true if parsing was successful - - static const char *sTextParsingUsageString; - - // _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ - // - // interrogation - - bool IsPCM() const { return mFormatID == kAudioFormatLinearPCM; } - - bool PackednessIsSignificant() const - { - Assert(IsPCM(), "PackednessIsSignificant only applies for PCM"); - return (SampleWordSize() << 3) != mBitsPerChannel; - } - - bool AlignmentIsSignificant() const - { - return PackednessIsSignificant() || (mBitsPerChannel & 7) != 0; - } - - bool IsInterleaved() const - { - return !(mFormatFlags & kAudioFormatFlagIsNonInterleaved); - } - - bool IsSignedInteger() const - { - return IsPCM() && (mFormatFlags & kAudioFormatFlagIsSignedInteger); - } - - bool IsFloat() const - { - return IsPCM() && (mFormatFlags & kAudioFormatFlagIsFloat); - } - - bool IsNativeEndian() const - { - return (mFormatFlags & kAudioFormatFlagIsBigEndian) == kAudioFormatFlagsNativeEndian; - } - - // for sanity with interleaved/deinterleaved possibilities, never access mChannelsPerFrame, use these: - UInt32 NumberInterleavedChannels() const { return IsInterleaved() ? mChannelsPerFrame : 1; } - UInt32 NumberChannelStreams() const { return IsInterleaved() ? 1 : mChannelsPerFrame; } - UInt32 NumberChannels() const { return mChannelsPerFrame; } - UInt32 SampleWordSize() const { - return (mBytesPerFrame > 0 && NumberInterleavedChannels()) ? mBytesPerFrame / NumberInterleavedChannels() : 0; - } - - UInt32 FramesToBytes(UInt32 nframes) const { return nframes * mBytesPerFrame; } - UInt32 BytesToFrames(UInt32 nbytes) const { - Assert(mBytesPerFrame > 0, "bytesPerFrame must be > 0 in BytesToFrames"); - return nbytes / mBytesPerFrame; - } - - bool SameChannelsAndInterleaving(const CAStreamBasicDescription &a) const - { - return this->NumberChannels() == a.NumberChannels() && this->IsInterleaved() == a.IsInterleaved(); - } - - bool IdentifyCommonPCMFormat(CommonPCMFormat &outFormat, bool *outIsInterleaved=NULL) const - { // return true if it's a valid PCM format. - - outFormat = kPCMFormatOther; - // trap out patently invalid formats. - if (mFormatID != kAudioFormatLinearPCM || mFramesPerPacket != 1 || mBytesPerFrame != mBytesPerPacket || mBitsPerChannel/8 > mBytesPerFrame || mChannelsPerFrame == 0) - return false; - bool interleaved = (mFormatFlags & kAudioFormatFlagIsNonInterleaved) == 0; - if (outIsInterleaved != NULL) *outIsInterleaved = interleaved; - unsigned wordsize = mBytesPerFrame; - if (interleaved) { - if (wordsize % mChannelsPerFrame != 0) return false; - wordsize /= mChannelsPerFrame; - } - - if ((mFormatFlags & kAudioFormatFlagIsBigEndian) == kAudioFormatFlagsNativeEndian - && wordsize * 8 == mBitsPerChannel) { - // packed and native endian, good - if (mFormatFlags & kLinearPCMFormatFlagIsFloat) { - // float: reject nonsense bits - if (mFormatFlags & (kLinearPCMFormatFlagIsSignedInteger | kLinearPCMFormatFlagsSampleFractionMask)) - return false; - if (wordsize == 4) - outFormat = kPCMFormatFloat32; - if (wordsize == 8) - outFormat = kPCMFormatFloat64; - } else if (mFormatFlags & kLinearPCMFormatFlagIsSignedInteger) { - // signed int - unsigned fracbits = (mFormatFlags & kLinearPCMFormatFlagsSampleFractionMask) >> kLinearPCMFormatFlagsSampleFractionShift; - if (wordsize == 4 && fracbits == 24) - outFormat = kPCMFormatFixed824; - else if (wordsize == 2 && fracbits == 0) - outFormat = kPCMFormatInt16; - } - } - return true; - } - - bool IsCommonFloat32(bool *outIsInterleaved=NULL) const { - CommonPCMFormat fmt; - return IdentifyCommonPCMFormat(fmt, outIsInterleaved) && fmt == kPCMFormatFloat32; - } - bool IsCommonFloat64(bool *outIsInterleaved=NULL) const { - CommonPCMFormat fmt; - return IdentifyCommonPCMFormat(fmt, outIsInterleaved) && fmt == kPCMFormatFloat64; - } - bool IsCommonFixed824(bool *outIsInterleaved=NULL) const { - CommonPCMFormat fmt; - return IdentifyCommonPCMFormat(fmt, outIsInterleaved) && fmt == kPCMFormatFixed824; - } - bool IsCommonInt16(bool *outIsInterleaved=NULL) const { - CommonPCMFormat fmt; - return IdentifyCommonPCMFormat(fmt, outIsInterleaved) && fmt == kPCMFormatInt16; - } - - // _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ - // - // manipulation - - void SetCanonical(UInt32 nChannels, bool interleaved) - // note: leaves sample rate untouched - { - mFormatID = kAudioFormatLinearPCM; - UInt32 sampleSize = SizeOf32(AudioSampleType); - mFormatFlags = kAudioFormatFlagsCanonical; - mBitsPerChannel = 8 * sampleSize; - mChannelsPerFrame = nChannels; - mFramesPerPacket = 1; - if (interleaved) - mBytesPerPacket = mBytesPerFrame = nChannels * sampleSize; - else { - mBytesPerPacket = mBytesPerFrame = sampleSize; - mFormatFlags |= kAudioFormatFlagIsNonInterleaved; - } - } - - bool IsCanonical() const - { - if (mFormatID != kAudioFormatLinearPCM) return false; - UInt32 reqFormatFlags; - UInt32 flagsMask = (kLinearPCMFormatFlagIsFloat | kLinearPCMFormatFlagIsBigEndian | kLinearPCMFormatFlagIsSignedInteger | kLinearPCMFormatFlagIsPacked | kLinearPCMFormatFlagsSampleFractionMask); - bool interleaved = (mFormatFlags & kAudioFormatFlagIsNonInterleaved) == 0; - unsigned sampleSize = SizeOf32(AudioSampleType); - reqFormatFlags = kAudioFormatFlagsCanonical; - UInt32 reqFrameSize = interleaved ? (mChannelsPerFrame * sampleSize) : sampleSize; - - return ((mFormatFlags & flagsMask) == reqFormatFlags - && mBitsPerChannel == 8 * sampleSize - && mFramesPerPacket == 1 - && mBytesPerFrame == reqFrameSize - && mBytesPerPacket == reqFrameSize); - } - - void SetAUCanonical(UInt32 nChannels, bool interleaved) - { - mFormatID = kAudioFormatLinearPCM; -#if CA_PREFER_FIXED_POINT - mFormatFlags = kAudioFormatFlagsCanonical | (kAudioUnitSampleFractionBits << kLinearPCMFormatFlagsSampleFractionShift); -#else - mFormatFlags = kAudioFormatFlagsCanonical; -#endif - mChannelsPerFrame = nChannels; - mFramesPerPacket = 1; - mBitsPerChannel = 8 * SizeOf32(AudioUnitSampleType); - if (interleaved) - mBytesPerPacket = mBytesPerFrame = nChannels * SizeOf32(AudioUnitSampleType); - else { - mBytesPerPacket = mBytesPerFrame = SizeOf32(AudioUnitSampleType); - mFormatFlags |= kAudioFormatFlagIsNonInterleaved; - } - } - - void ChangeNumberChannels(UInt32 nChannels, bool interleaved) - // alter an existing format - { - Assert(IsPCM(), "ChangeNumberChannels only works for PCM formats"); - UInt32 wordSize = SampleWordSize(); // get this before changing ANYTHING - if (wordSize == 0) - wordSize = (mBitsPerChannel + 7) / 8; - mChannelsPerFrame = nChannels; - mFramesPerPacket = 1; - if (interleaved) { - mBytesPerPacket = mBytesPerFrame = nChannels * wordSize; - mFormatFlags &= ~static_cast(kAudioFormatFlagIsNonInterleaved); - } else { - mBytesPerPacket = mBytesPerFrame = wordSize; - mFormatFlags |= kAudioFormatFlagIsNonInterleaved; - } - } - - // _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ - // - // other - - bool IsEqual(const AudioStreamBasicDescription &other, bool interpretingWildcards=true) const; - static bool FlagIndependentEquivalence(const AudioStreamBasicDescription &x, const AudioStreamBasicDescription &y); - static bool IsFunctionallyEquivalent(const AudioStreamBasicDescription &x, const AudioStreamBasicDescription &y); - - void Print() const { - Print (stdout); - } - - void Print(FILE* file) const { - PrintFormat (file, "", "AudioStreamBasicDescription:"); - } - - void PrintFormat(FILE *f, const char *indent, const char *name) const { - char buf[256]; - fprintf(f, "%s%s %s\n", indent, name, AsString(buf, sizeof(buf))); - } - - void PrintFormat2(FILE *f, const char *indent, const char *name) const { // no trailing newline - char buf[256]; - fprintf(f, "%s%s %s", indent, name, AsString(buf, sizeof(buf))); - } - - char * AsString(char *buf, size_t bufsize, bool brief=false) const; - - static void Print (const AudioStreamBasicDescription &inDesc) - { - CAStreamBasicDescription desc(inDesc); - desc.Print (); - } - - OSStatus Save(CFPropertyListRef *outData) const; - - OSStatus Restore(CFPropertyListRef &inData); - -// Operations - static bool IsMixable(const AudioStreamBasicDescription& inDescription) { return (inDescription.mFormatID == kAudioFormatLinearPCM) && ((inDescription.mFormatFlags & kIsNonMixableFlag) == 0); } - static void NormalizeLinearPCMFormat(AudioStreamBasicDescription& ioDescription); - static void NormalizeLinearPCMFormat(bool inNativeEndian, AudioStreamBasicDescription& ioDescription); - static void ResetFormat(AudioStreamBasicDescription& ioDescription); - static void FillOutFormat(AudioStreamBasicDescription& ioDescription, const AudioStreamBasicDescription& inTemplateDescription); - static void GetSimpleName(const AudioStreamBasicDescription& inDescription, char* outName, UInt32 inMaxNameLength, bool inAbbreviate, bool inIncludeSampleRate = false); - static void ModifyFormatFlagsForMatching(const AudioStreamBasicDescription& x, const AudioStreamBasicDescription& y, UInt32& xFlags, UInt32& yFlags, bool converterOnly); - -#if CoreAudio_Debug - static void PrintToLog(const AudioStreamBasicDescription& inDesc); -#endif -}; - -bool operator<(const AudioStreamBasicDescription& x, const AudioStreamBasicDescription& y); -bool operator==(const AudioStreamBasicDescription& x, const AudioStreamBasicDescription& y); -#if TARGET_OS_MAC || (TARGET_OS_WIN32 && (_MSC_VER > 600)) -inline bool operator!=(const AudioStreamBasicDescription& x, const AudioStreamBasicDescription& y) { return !(x == y); } -inline bool operator<=(const AudioStreamBasicDescription& x, const AudioStreamBasicDescription& y) { return (x < y) || (x == y); } -inline bool operator>=(const AudioStreamBasicDescription& x, const AudioStreamBasicDescription& y) { return !(x < y); } -inline bool operator>(const AudioStreamBasicDescription& x, const AudioStreamBasicDescription& y) { return !((x < y) || (x == y)); } -#endif - -bool SanityCheck(const AudioStreamBasicDescription& x); - - -#endif // __CAStreamBasicDescription_h__ diff --git a/src/CoreAudio/CoreAudioComponent/PublicUtility/CAThreadSafeList.h b/src/CoreAudio/CoreAudioComponent/PublicUtility/CAThreadSafeList.h deleted file mode 100644 index d0b739147..000000000 --- a/src/CoreAudio/CoreAudioComponent/PublicUtility/CAThreadSafeList.h +++ /dev/null @@ -1,233 +0,0 @@ -/* - File: CAThreadSafeList.h - Abstract: Part of CoreAudio Utility Classes - Version: 1.1 - - Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple - Inc. ("Apple") in consideration of your agreement to the following - terms, and your use, installation, modification or redistribution of - this Apple software constitutes acceptance of these terms. If you do - not agree with these terms, please do not use, install, modify or - redistribute this Apple software. - - In consideration of your agreement to abide by the following terms, and - subject to these terms, Apple grants you a personal, non-exclusive - license, under Apple's copyrights in this original Apple software (the - "Apple Software"), to use, reproduce, modify and redistribute the Apple - Software, with or without modifications, in source and/or binary forms; - provided that if you redistribute the Apple Software in its entirety and - without modifications, you must retain this notice and the following - text and disclaimers in all such redistributions of the Apple Software. - Neither the name, trademarks, service marks or logos of Apple Inc. may - be used to endorse or promote products derived from the Apple Software - without specific prior written permission from Apple. Except as - expressly stated in this notice, no other rights or licenses, express or - implied, are granted by Apple herein, including but not limited to any - patent rights that may be infringed by your derivative works or by other - works in which the Apple Software may be incorporated. - - The Apple Software is provided by Apple on an "AS IS" basis. APPLE - MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION - THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS - FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND - OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS. - - IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL - OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, - MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED - AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), - STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE - POSSIBILITY OF SUCH DAMAGE. - - Copyright (C) 2014 Apple Inc. All Rights Reserved. - -*/ -#ifndef __CAThreadSafeList_h__ -#define __CAThreadSafeList_h__ - -#include "CAAtomicStack.h" - -// linked list of T's -// T must define operator == -template -class TThreadSafeList { -private: - enum EEventType { kAdd, kRemove, kClear }; - class Node { - public: - Node * mNext; - EEventType mEventType; - T mObject; - - Node *& next() { return mNext; } - }; - -public: - class iterator { - public: - iterator() { } - iterator(Node *n) : mNode(n) { } - - bool operator == (const iterator &other) const { return this->mNode == other.mNode; } - bool operator != (const iterator &other) const { return this->mNode != other.mNode; } - - T & operator * () const { return mNode->mObject; } - - iterator & operator ++ () { mNode = mNode->next(); return *this; } // preincrement - iterator operator ++ (int) { iterator tmp = *this; mNode = mNode->next(); return tmp; } // postincrement - - private: - Node * mNode; - }; - - TThreadSafeList() { } - ~TThreadSafeList() - { - mActiveList.free_all(); - mPendingList.free_all(); - mFreeList.free_all(); - } - - // These may be called on any thread - - void deferred_add(const T &obj) // can be called on any thread - { - Node *node = AllocNode(); - node->mEventType = kAdd; - node->mObject = obj; - mPendingList.push_atomic(node); - //mPendingList.dump("pending after add"); - } - - void deferred_remove(const T &obj) // can be called on any thread - { - Node *node = AllocNode(); - node->mEventType = kRemove; - node->mObject = obj; - mPendingList.push_atomic(node); - //mPendingList.dump("pending after remove"); - } - - void deferred_clear() // can be called on any thread - { - Node *node = AllocNode(); - node->mEventType = kClear; - mPendingList.push_atomic(node); - } - - // These must be called from only one thread - - void update() // must only be called from one thread - { - NodeStack reversed; - Node *event, *node, *next; - bool workDone = false; - - // reverse the events so they are in order - event = mPendingList.pop_all(); - while (event != NULL) { - next = event->mNext; - reversed.push_NA(event); - event = next; - workDone = true; - } - if (workDone) { - //reversed.dump("pending popped"); - //mActiveList.dump("active before update"); - - // now process them - while ((event = reversed.pop_NA()) != NULL) { - switch (event->mEventType) { - case kAdd: - { - Node **pnode; - bool needToInsert = true; - for (pnode = mActiveList.phead(); *pnode != NULL; pnode = &node->mNext) { - node = *pnode; - if (node->mObject == event->mObject) { - //printf("already active!!!\n"); - FreeNode(event); - needToInsert = false; - break; - } - } - if (needToInsert) { - // link the new event in at the end of the active list - *pnode = event; - event->mNext = NULL; - } - } - break; - case kRemove: - // find matching node in the active list, remove it - for (Node **pnode = mActiveList.phead(); *pnode != NULL; ) { - node = *pnode; - if (node->mObject == event->mObject) { - *pnode = node->mNext; // remove from linked list - FreeNode(node); - break; - } - pnode = &node->mNext; - } - // dispose the request node - FreeNode(event); - break; - case kClear: - for (node = mActiveList.head(); node != NULL; ) { - next = node->mNext; - FreeNode(node); - node = next; - } - FreeNode(event); - break; - default: - //printf("invalid node type %d!\n", event->mEventType); - break; - } - } - //mActiveList.dump("active after update"); - } - } - - iterator begin() const { - //mActiveList.dump("active at begin"); - return iterator(mActiveList.head()); - } - iterator end() const { return iterator(NULL); } - - -private: - Node * AllocNode() - { - Node *node = mFreeList.pop_atomic(); - if (node == NULL) - node = (Node *)CA_malloc(sizeof(Node)); - return node; - } - - void FreeNode(Node *node) - { - mFreeList.push_atomic(node); - } - -private: - class NodeStack : public TAtomicStack { - public: - void free_all() { - Node *node; - while ((node = this->pop_NA()) != NULL) - free(node); - } - - Node ** phead() { return &this->mHead; } - Node * head() const { return this->mHead; } - }; - - NodeStack mActiveList; // what's actually in the container - only accessed on one thread - NodeStack mPendingList; // add or remove requests - threadsafe - NodeStack mFreeList; // free nodes for reuse - threadsafe -}; - -#endif // __CAThreadSafeList_h__ diff --git a/src/CoreAudio/CoreAudioComponent/PublicUtility/CAVectorUnit.cpp b/src/CoreAudio/CoreAudioComponent/PublicUtility/CAVectorUnit.cpp deleted file mode 100644 index 83bfb8c88..000000000 --- a/src/CoreAudio/CoreAudioComponent/PublicUtility/CAVectorUnit.cpp +++ /dev/null @@ -1,195 +0,0 @@ -/* - File: CAVectorUnit.cpp - Abstract: CAVectorUnit.h - Version: 1.1 - - Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple - Inc. ("Apple") in consideration of your agreement to the following - terms, and your use, installation, modification or redistribution of - this Apple software constitutes acceptance of these terms. If you do - not agree with these terms, please do not use, install, modify or - redistribute this Apple software. - - In consideration of your agreement to abide by the following terms, and - subject to these terms, Apple grants you a personal, non-exclusive - license, under Apple's copyrights in this original Apple software (the - "Apple Software"), to use, reproduce, modify and redistribute the Apple - Software, with or without modifications, in source and/or binary forms; - provided that if you redistribute the Apple Software in its entirety and - without modifications, you must retain this notice and the following - text and disclaimers in all such redistributions of the Apple Software. - Neither the name, trademarks, service marks or logos of Apple Inc. may - be used to endorse or promote products derived from the Apple Software - without specific prior written permission from Apple. Except as - expressly stated in this notice, no other rights or licenses, express or - implied, are granted by Apple herein, including but not limited to any - patent rights that may be infringed by your derivative works or by other - works in which the Apple Software may be incorporated. - - The Apple Software is provided by Apple on an "AS IS" basis. APPLE - MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION - THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS - FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND - OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS. - - IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL - OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, - MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED - AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), - STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE - POSSIBILITY OF SUCH DAMAGE. - - Copyright (C) 2014 Apple Inc. All Rights Reserved. - -*/ -#include "CAVectorUnit.h" - -#if !TARGET_OS_WIN32 - #include -#elif HAS_IPP - #include "ippdefs.h" - #include "ippcore.h" -#endif - -int gCAVectorUnitType = kVecUninitialized; - -#if TARGET_OS_WIN32 -// Use cpuid to check if SSE2 is available. -// Before calling this function make sure cpuid is available -static SInt32 IsSSE2Available() -{ - int return_value; - - { - int r_edx; - _asm - { - mov eax, 0x01 - cpuid - mov r_edx, edx - } - return_value = (r_edx >> 26) & 0x1; - } - return return_value; -} - -// Use cpuid to check if SSE3 is available. -// Before calling this function make sure cpuid is available -static SInt32 IsSSE3Available() -{ - SInt32 return_value; - - { - SInt32 r_ecx; - _asm - { - mov eax, 0x01 - cpuid - mov r_ecx, ecx - } - return_value = r_ecx & 0x1; - } - return return_value; -} - -// Return true if the cpuid instruction is available. -// The cpuid instruction is available if bit 21 in the EFLAGS register can be changed -// This function may not work on Intel CPUs prior to Pentium (didn't test) -static bool IsCpuidAvailable() -{ - SInt32 return_value = 0x0; - _asm{ - pushfd ; //push original EFLAGS - pop eax ; //get original EFLAGS - mov ecx, eax ; //save original EFLAGS - xor eax, 200000h ; //flip ID bit in EFLAGS - push eax ; //save new EFLAGS value on stack - popfd ; //replace current EFLAGS value - pushfd ; //get new EFLAGS - pop eax ; //store new EFLAGS in EAX - xor eax, ecx ; - je end_cpuid_identify ; //can't toggle ID bit - mov return_value, 0x1; -end_cpuid_identify: - nop; - } - return return_value; -} - -#endif - -SInt32 CAVectorUnit_Examine() -{ - int result = kVecNone; - -#if TARGET_OS_WIN32 -#if HAS_IPP - // Initialize the static IPP library! This needs to be done before - // any IPP function calls, otherwise we may have a performance penalty - int status = ippStaticInit(); - if ( status == ippStsNonIntelCpu ) - { - IppCpuType cpuType = ippGetCpuType(); - if ( cpuType >= ippCpuSSE || cpuType <= ippCpuSSE42 ) - ippStaticInitCpu( cpuType ); - } -#endif - { - // On Windows we use cpuid to detect the vector unit because it works on Intel and AMD. - // The IPP library does not detect SSE on AMD processors. - if (IsCpuidAvailable()) - { - if(IsSSE3Available()) - { - result = kVecSSE3; - } - else if(IsSSE2Available()) - { - result = kVecSSE2; - } - } - } -#elif TARGET_OS_MAC -#if DEBUG - if (getenv("CA_NoVector")) { - fprintf(stderr, "CA_NoVector set; Vector unit optimized routines will be bypassed\n"); - return result; - } - else -#endif - { - #if (TARGET_CPU_PPC || TARGET_CPU_PPC64) - int sels[2] = { CTL_HW, HW_VECTORUNIT }; - int vType = 0; //0 == scalar only - size_t length = sizeof(vType); - int error = sysctl(sels, 2, &vType, &length, NULL, 0); - if (!error && vType > 0) - result = kVecAltivec; - #elif (TARGET_CPU_X86 || TARGET_CPU_X86_64) - static const struct { const char* kName; const int kVectype; } kStringVectypes[] = { - { "hw.optional.avx1_0", kVecAVX1 }, { "hw.optional.sse3", kVecSSE3 }, { "hw.optional.sse2", kVecSSE2 } - }; - static const size_t kNumStringVectypes = sizeof(kStringVectypes)/sizeof(kStringVectypes[0]); - int i = 0, answer = 0; - while(i != kNumStringVectypes) - { - size_t length = sizeof(answer); - int error = sysctlbyname(kStringVectypes[i].kName, &answer, &length, NULL, 0); - if (!error && answer) - { - result = kStringVectypes[i].kVectype; - break; - } - ++i; - }; - #elif CA_ARM_NEON - result = kVecNeon; - #endif - } -#endif - gCAVectorUnitType = result; - return result; -} - diff --git a/src/CoreAudio/CoreAudioComponent/PublicUtility/CAVectorUnit.h b/src/CoreAudio/CoreAudioComponent/PublicUtility/CAVectorUnit.h deleted file mode 100644 index cf3a16c7a..000000000 --- a/src/CoreAudio/CoreAudioComponent/PublicUtility/CAVectorUnit.h +++ /dev/null @@ -1,101 +0,0 @@ -/* - File: CAVectorUnit.h - Abstract: Part of CoreAudio Utility Classes - Version: 1.1 - - Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple - Inc. ("Apple") in consideration of your agreement to the following - terms, and your use, installation, modification or redistribution of - this Apple software constitutes acceptance of these terms. If you do - not agree with these terms, please do not use, install, modify or - redistribute this Apple software. - - In consideration of your agreement to abide by the following terms, and - subject to these terms, Apple grants you a personal, non-exclusive - license, under Apple's copyrights in this original Apple software (the - "Apple Software"), to use, reproduce, modify and redistribute the Apple - Software, with or without modifications, in source and/or binary forms; - provided that if you redistribute the Apple Software in its entirety and - without modifications, you must retain this notice and the following - text and disclaimers in all such redistributions of the Apple Software. - Neither the name, trademarks, service marks or logos of Apple Inc. may - be used to endorse or promote products derived from the Apple Software - without specific prior written permission from Apple. Except as - expressly stated in this notice, no other rights or licenses, express or - implied, are granted by Apple herein, including but not limited to any - patent rights that may be infringed by your derivative works or by other - works in which the Apple Software may be incorporated. - - The Apple Software is provided by Apple on an "AS IS" basis. APPLE - MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION - THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS - FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND - OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS. - - IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL - OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, - MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED - AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), - STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE - POSSIBILITY OF SUCH DAMAGE. - - Copyright (C) 2014 Apple Inc. All Rights Reserved. - -*/ -#ifndef __CAVectorUnit_h__ -#define __CAVectorUnit_h__ - -#include -#include "CAVectorUnitTypes.h" -#include -#include - -#if !defined(__COREAUDIO_USE_FLAT_INCLUDES__) - #include -#else - #include "CFBase.h" -#endif - -// Unify checks for vector units. -// Allow setting an environment variable "CA_NoVector" to turn off vectorized code at runtime (very useful for performance testing). - -extern int gCAVectorUnitType; - -#ifdef __cplusplus -extern "C" { -#endif - -extern SInt32 CAVectorUnit_Examine(); // expensive. use GetType() for lazy initialization and caching. - -static inline SInt32 CAVectorUnit_GetType() -{ - int x = gCAVectorUnitType; - return (x != kVecUninitialized) ? x : CAVectorUnit_Examine(); -} - -static inline Boolean CAVectorUnit_HasVectorUnit() -{ - return CAVectorUnit_GetType() > kVecNone; -} - -#ifdef __cplusplus -} -#endif - - -#ifdef __cplusplus -class CAVectorUnit { -public: - static SInt32 GetVectorUnitType() { return CAVectorUnit_GetType(); } - static bool HasVectorUnit() { return GetVectorUnitType() > kVecNone; } - static bool HasAltivec() { return GetVectorUnitType() == kVecAltivec; } - static bool HasSSE2() { return GetVectorUnitType() >= kVecSSE2; } - static bool HasSSE3() { return GetVectorUnitType() >= kVecSSE3; } - static bool HasAVX1() { return GetVectorUnitType() >= kVecAVX1; } - static bool HasNeon() { return GetVectorUnitType() == kVecNeon; } -}; -#endif - -#endif // __CAVectorUnit_h__ diff --git a/src/CoreAudio/CoreAudioComponent/PublicUtility/CAVectorUnitTypes.h b/src/CoreAudio/CoreAudioComponent/PublicUtility/CAVectorUnitTypes.h deleted file mode 100644 index 85ff837af..000000000 --- a/src/CoreAudio/CoreAudioComponent/PublicUtility/CAVectorUnitTypes.h +++ /dev/null @@ -1,60 +0,0 @@ -/* - File: CAVectorUnitTypes.h - Abstract: Part of CoreAudio Utility Classes - Version: 1.1 - - Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple - Inc. ("Apple") in consideration of your agreement to the following - terms, and your use, installation, modification or redistribution of - this Apple software constitutes acceptance of these terms. If you do - not agree with these terms, please do not use, install, modify or - redistribute this Apple software. - - In consideration of your agreement to abide by the following terms, and - subject to these terms, Apple grants you a personal, non-exclusive - license, under Apple's copyrights in this original Apple software (the - "Apple Software"), to use, reproduce, modify and redistribute the Apple - Software, with or without modifications, in source and/or binary forms; - provided that if you redistribute the Apple Software in its entirety and - without modifications, you must retain this notice and the following - text and disclaimers in all such redistributions of the Apple Software. - Neither the name, trademarks, service marks or logos of Apple Inc. may - be used to endorse or promote products derived from the Apple Software - without specific prior written permission from Apple. Except as - expressly stated in this notice, no other rights or licenses, express or - implied, are granted by Apple herein, including but not limited to any - patent rights that may be infringed by your derivative works or by other - works in which the Apple Software may be incorporated. - - The Apple Software is provided by Apple on an "AS IS" basis. APPLE - MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION - THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS - FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND - OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS. - - IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL - OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, - MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED - AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), - STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE - POSSIBILITY OF SUCH DAMAGE. - - Copyright (C) 2014 Apple Inc. All Rights Reserved. - -*/ -#ifndef __CAVectorUnitTypes_h__ -#define __CAVectorUnitTypes_h__ - -enum { - kVecUninitialized = -1, - kVecNone = 0, - kVecAltivec = 1, - kVecSSE2 = 100, - kVecSSE3 = 101, - kVecAVX1 = 110, - kVecNeon = 200 -}; - -#endif diff --git a/src/CoreAudio/CoreAudioComponent/PublicUtility/CAXException.cpp b/src/CoreAudio/CoreAudioComponent/PublicUtility/CAXException.cpp deleted file mode 100644 index c2dbac5d6..000000000 --- a/src/CoreAudio/CoreAudioComponent/PublicUtility/CAXException.cpp +++ /dev/null @@ -1,49 +0,0 @@ -/* - File: CAXException.cpp - Abstract: CAXException.h - Version: 1.1 - - Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple - Inc. ("Apple") in consideration of your agreement to the following - terms, and your use, installation, modification or redistribution of - this Apple software constitutes acceptance of these terms. If you do - not agree with these terms, please do not use, install, modify or - redistribute this Apple software. - - In consideration of your agreement to abide by the following terms, and - subject to these terms, Apple grants you a personal, non-exclusive - license, under Apple's copyrights in this original Apple software (the - "Apple Software"), to use, reproduce, modify and redistribute the Apple - Software, with or without modifications, in source and/or binary forms; - provided that if you redistribute the Apple Software in its entirety and - without modifications, you must retain this notice and the following - text and disclaimers in all such redistributions of the Apple Software. - Neither the name, trademarks, service marks or logos of Apple Inc. may - be used to endorse or promote products derived from the Apple Software - without specific prior written permission from Apple. Except as - expressly stated in this notice, no other rights or licenses, express or - implied, are granted by Apple herein, including but not limited to any - patent rights that may be infringed by your derivative works or by other - works in which the Apple Software may be incorporated. - - The Apple Software is provided by Apple on an "AS IS" basis. APPLE - MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION - THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS - FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND - OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS. - - IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL - OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, - MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED - AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), - STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE - POSSIBILITY OF SUCH DAMAGE. - - Copyright (C) 2014 Apple Inc. All Rights Reserved. - -*/ -#include "CAXException.h" - -CAXException::WarningHandler CAXException::sWarningHandler = NULL; diff --git a/src/CoreAudio/CoreAudioComponent/PublicUtility/CAXException.h b/src/CoreAudio/CoreAudioComponent/PublicUtility/CAXException.h deleted file mode 100644 index 90dabe97d..000000000 --- a/src/CoreAudio/CoreAudioComponent/PublicUtility/CAXException.h +++ /dev/null @@ -1,361 +0,0 @@ -/* - File: CAXException.h - Abstract: Part of CoreAudio Utility Classes - Version: 1.1 - - Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple - Inc. ("Apple") in consideration of your agreement to the following - terms, and your use, installation, modification or redistribution of - this Apple software constitutes acceptance of these terms. If you do - not agree with these terms, please do not use, install, modify or - redistribute this Apple software. - - In consideration of your agreement to abide by the following terms, and - subject to these terms, Apple grants you a personal, non-exclusive - license, under Apple's copyrights in this original Apple software (the - "Apple Software"), to use, reproduce, modify and redistribute the Apple - Software, with or without modifications, in source and/or binary forms; - provided that if you redistribute the Apple Software in its entirety and - without modifications, you must retain this notice and the following - text and disclaimers in all such redistributions of the Apple Software. - Neither the name, trademarks, service marks or logos of Apple Inc. may - be used to endorse or promote products derived from the Apple Software - without specific prior written permission from Apple. Except as - expressly stated in this notice, no other rights or licenses, express or - implied, are granted by Apple herein, including but not limited to any - patent rights that may be infringed by your derivative works or by other - works in which the Apple Software may be incorporated. - - The Apple Software is provided by Apple on an "AS IS" basis. APPLE - MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION - THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS - FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND - OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS. - - IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL - OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, - MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED - AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), - STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE - POSSIBILITY OF SUCH DAMAGE. - - Copyright (C) 2014 Apple Inc. All Rights Reserved. - -*/ -#ifndef __CAXException_h__ -#define __CAXException_h__ - -#if !defined(__COREAUDIO_USE_FLAT_INCLUDES__) - #include -#else - #include - #include -#endif -#include "CADebugMacros.h" -#include -//#include -#include - - -class CAX4CCString { -public: - CAX4CCString(OSStatus error) { - // see if it appears to be a 4-char-code - UInt32 beErr = CFSwapInt32HostToBig(error); - char *str = mStr; - memcpy(str + 1, &beErr, 4); - if (isprint(str[1]) && isprint(str[2]) && isprint(str[3]) && isprint(str[4])) { - str[0] = str[5] = '\''; - str[6] = '\0'; - } else if (error > -200000 && error < 200000) - // no, format it as an integer - snprintf(str, sizeof(mStr), "%d", (int)error); - else - snprintf(str, sizeof(mStr), "0x%x", (int)error); - } - const char *get() const { return mStr; } - operator const char *() const { return mStr; } -private: - char mStr[16]; -}; - -class CAX4CCStringNoQuote { -public: - CAX4CCStringNoQuote(OSStatus error) { - // see if it appears to be a 4-char-code - UInt32 beErr = CFSwapInt32HostToBig(error); - char *str = mStr; - memcpy(str, &beErr, 4); - if (isprint(str[0]) && isprint(str[1]) && isprint(str[2]) && isprint(str[3])) { - str[4] = '\0'; - } else if (error > -200000 && error < 200000) - // no, format it as an integer - snprintf(str, sizeof(mStr), "%d", (int)error); - else - snprintf(str, sizeof(mStr), "0x%x", (int)error); - } - const char *get() const { return mStr; } - operator const char *() const { return mStr; } -private: - char mStr[16]; -}; - - -// An extended exception class that includes the name of the failed operation -class CAXException { -public: - CAXException(const char *operation, OSStatus err) : - mError(err) - { - if (operation == NULL) - mOperation[0] = '\0'; - else if (strlen(operation) >= sizeof(mOperation)) { - memcpy(mOperation, operation, sizeof(mOperation) - 1); - mOperation[sizeof(mOperation) - 1] = '\0'; - } else - - strlcpy(mOperation, operation, sizeof(mOperation)); - } - - char *FormatError(char *str, size_t strsize) const - { - return FormatError(str, strsize, mError); - } - - char mOperation[256]; - const OSStatus mError; - - // ------------------------------------------------- - - typedef void (*WarningHandler)(const char *msg, OSStatus err); - - static char *FormatError(char *str, size_t strsize, OSStatus error) - { - strlcpy(str, CAX4CCString(error), strsize); - return str; - } - - static void Warning(const char *s, OSStatus error) - { - if (sWarningHandler) - (*sWarningHandler)(s, error); - } - - static void SetWarningHandler(WarningHandler f) { sWarningHandler = f; } -private: - static WarningHandler sWarningHandler; -}; - -#if DEBUG || CoreAudio_Debug - #define XThrowIfError(error, operation) \ - do { \ - OSStatus __err = error; \ - if (__err) { \ - DebugMessageN4("%s:%d: about to throw %s: %s", __FILE__, __LINE__, CAX4CCString(__err).get(), operation);\ - __THROW_STOP; \ - throw CAXException(operation, __err); \ - } \ - } while (0) - - #define XThrowIf(condition, error, operation) \ - do { \ - if (condition) { \ - OSStatus __err = error; \ - DebugMessageN4("%s:%d: about to throw %s: %s", __FILE__, __LINE__, CAX4CCString(__err).get(), operation);\ - __THROW_STOP; \ - throw CAXException(operation, __err); \ - } \ - } while (0) - - #define XRequireNoError(error, label) \ - do { \ - OSStatus __err = error; \ - if (__err) { \ - DebugMessageN4("%s:%d: about to throw %s: %s", __FILE__, __LINE__, CAX4CCString(__err).get(), #error);\ - STOP; \ - goto label; \ - } \ - } while (0) - - #define XAssert(assertion) \ - do { \ - if (!(assertion)) { \ - DebugMessageN3("%s:%d: error: failed assertion: %s", __FILE__, __LINE__, #assertion); \ - __ASSERT_STOP; \ - } \ - } while (0) - - #define XAssertNoError(error) \ - do { \ - OSStatus __err = error; \ - if (__err) { \ - DebugMessageN4("%s:%d: error %s: %s", __FILE__, __LINE__, CAX4CCString(__err).get(), #error);\ - STOP; \ - } \ - } while (0) - - #define ca_require_noerr(errorCode, exceptionLabel) \ - do \ - { \ - int evalOnceErrorCode = (errorCode); \ - if ( __builtin_expect(0 != evalOnceErrorCode, 0) ) \ - { \ - DebugMessageN5("ca_require_noerr: [%s, %d] (goto %s;) %s:%d", \ - #errorCode, evalOnceErrorCode, \ - #exceptionLabel, \ - __FILE__, \ - __LINE__); \ - goto exceptionLabel; \ - } \ - } while ( 0 ) - - #define ca_verify_noerr(errorCode) \ - do \ - { \ - int evalOnceErrorCode = (errorCode); \ - if ( __builtin_expect(0 != evalOnceErrorCode, 0) ) \ - { \ - DebugMessageN4("ca_verify_noerr: [%s, %d] %s:%d", \ - #errorCode, evalOnceErrorCode, \ - __FILE__, \ - __LINE__); \ - } \ - } while ( 0 ) - - #define ca_debug_string(message) \ - do \ - { \ - DebugMessageN3("ca_debug_string: %s %s:%d", \ - message, \ - __FILE__, \ - __LINE__); \ - } while ( 0 ) - - - #define ca_verify(assertion) \ - do \ - { \ - if ( __builtin_expect(!(assertion), 0) ) \ - { \ - DebugMessageN3("ca_verify: %s %s:%d", \ - #assertion, \ - __FILE__, \ - __LINE__); \ - } \ - } while ( 0 ) - - #define ca_require(assertion, exceptionLabel) \ - do \ - { \ - if ( __builtin_expect(!(assertion), 0) ) \ - { \ - DebugMessageN4("ca_require: %s %s %s:%d", \ - #assertion, \ - #exceptionLabel, \ - __FILE__, \ - __LINE__); \ - goto exceptionLabel; \ - } \ - } while ( 0 ) - - #define ca_check(assertion) \ - do \ - { \ - if ( __builtin_expect(!(assertion), 0) ) \ - { \ - DebugMessageN3("ca_check: %s %s:%d", \ - #assertion, \ - __FILE__, \ - __LINE__); \ - } \ - } while ( 0 ) - -#else - #define XThrowIfError(error, operation) \ - do { \ - OSStatus __err = error; \ - if (__err) { \ - throw CAXException(operation, __err); \ - } \ - } while (0) - - #define XThrowIf(condition, error, operation) \ - do { \ - if (condition) { \ - OSStatus __err = error; \ - throw CAXException(operation, __err); \ - } \ - } while (0) - - #define XRequireNoError(error, label) \ - do { \ - OSStatus __err = error; \ - if (__err) { \ - goto label; \ - } \ - } while (0) - - #define XAssert(assertion) \ - do { \ - if (!(assertion)) { \ - } \ - } while (0) - - #define XAssertNoError(error) \ - do { \ - /*OSStatus __err =*/ error; \ - } while (0) - - #define ca_require_noerr(errorCode, exceptionLabel) \ - do \ - { \ - if ( __builtin_expect(0 != (errorCode), 0) ) \ - { \ - goto exceptionLabel; \ - } \ - } while ( 0 ) - - #define ca_verify_noerr(errorCode) \ - do \ - { \ - if ( 0 != (errorCode) ) \ - { \ - } \ - } while ( 0 ) - - #define ca_debug_string(message) - - #define ca_verify(assertion) \ - do \ - { \ - if ( !(assertion) ) \ - { \ - } \ - } while ( 0 ) - - #define ca_require(assertion, exceptionLabel) \ - do \ - { \ - if ( __builtin_expect(!(assertion), 0) ) \ - { \ - goto exceptionLabel; \ - } \ - } while ( 0 ) - - #define ca_check(assertion) \ - do \ - { \ - if ( !(assertion) ) \ - { \ - } \ - } while ( 0 ) - - -#endif - -#define XThrow(error, operation) XThrowIf(true, error, operation) -#define XThrowIfErr(error) XThrowIfError(error, #error) - -#endif // __CAXException_h__