diff options
Diffstat (limited to 'libs/backends/wavesaudio/wavesapi')
33 files changed, 0 insertions, 12043 deletions
diff --git a/libs/backends/wavesaudio/wavesapi/BasicTypes/WCFourCC.h b/libs/backends/wavesaudio/wavesapi/BasicTypes/WCFourCC.h deleted file mode 100644 index 571a2341be..0000000000 --- a/libs/backends/wavesaudio/wavesapi/BasicTypes/WCFourCC.h +++ /dev/null @@ -1,213 +0,0 @@ -/* - Copyright (C) 2014 Waves Audio Ltd. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. - -*/ - -#ifndef __WCFourCC_h__ - #define __WCFourCC_h__ - -/* Copy to include -#include "BasicTypes/WCFourCC.h" -*/ - -//#include "BasicTypes/WTByteOrder.h" -#include "WCFixedString.h" - - -// These are preprocessor macros rather than inline functions because most compilers can't -// resolve functions at compile-time. -#if _BYTEORDER_BIG_ENDIAN==1 - #define FOURCC_BIG(a, b, c, d) ((uint32_t(a)<<24)|(uint32_t(b)<<16)|(uint32_t(c)<< 8)|(uint32_t(d)<< 0)) - #define FOURCC_LITTLE(a, b, c, d) ((uint32_t(a)<< 0)|(uint32_t(b)<< 8)|(uint32_t(c)<<16)|(uint32_t(d)<<24)) - #define FOURCC_COMPILER(a, b, c, d) FOURCC_BIG(a,b,c,d) -#elif _BYTEORDER_BIG_ENDIAN==0 - #define FOURCC_BIG(a, b, c, d) ((uint32_t(a)<< 0)|(uint32_t(b)<< 8)|(uint32_t(c)<<16)|(uint32_t(d)<<24)) - #define FOURCC_LITTLE(a, b, c, d) ((uint32_t(a)<<24)|(uint32_t(b)<<16)|(uint32_t(c)<< 8)|(uint32_t(d)<< 0)) - #define FOURCC_COMPILER(a, b, c, d) FOURCC_LITTLE(a,b,c,d) -#else - #error _BYTEORDER_BIG_ENDIAN not defined proparly -#endif // _BYTEORDER_HPP_BIG_ENDIAN - -typedef uint32_t WTFourCharCode; - -#ifndef kEnableWCFourCCDebug - #define kEnableWCFourCCDebug 0 // set to 1 to enable debug members -#endif - - -class WCFourCC -{ -private: - template<class _iter> - static WTFourCharCode stored_from_iter(_iter& i) - { - return s_stored_byte_order==wvNS::wvBO::byte_order_big_endian ? FOURCC_BIG(i[0], i[1], i[2], i[3]) : FOURCC_LITTLE(i[0], i[1], i[2], i[3]); - } - -public: - - // static const WCFourCC kDefaultFourCC_prv; - - static WCFourCC kDefaultFourCC_prv() { return WCFourCC(); } - - // change this line will change the byte order in which WCFourCC keeps the four char code - static const wvNS::wvBO::byte_order_type s_stored_byte_order = wvNS::wvBO::compiler_byte_order; - - WCFourCC(const char a, const char b, const char c, const char d) : - m_stored_value(s_stored_byte_order==wvNS::wvBO::compiler_byte_order ? FOURCC_BIG(a,b,c,d) : FOURCC_LITTLE(a,b,c,d)) - { -#if kEnableWCFourCCDebug == 1 - m_c_str_stored_value[sizeof(WTFourCharCode)] = '\0'; -#endif - } - - WCFourCC() : - m_stored_value(FOURCC_BIG('?','?','?','?')) // since the four chars are the same, there is no need to choose between big & little - { -#if kEnableWCFourCCDebug == 1 - m_c_str_stored_value[sizeof(WTFourCharCode)] = '\0'; -#endif - } - - WCFourCC(const WTFourCharCode in_fourCharCode, const wvNS::wvBO::byte_order_type in_byteOrder = wvNS::wvBO::compiler_byte_order) : - m_stored_value(in_byteOrder==s_stored_byte_order ? in_fourCharCode : wvNS::wvBO::swap32(in_fourCharCode)) - { -#if kEnableWCFourCCDebug == 1 - m_c_str_stored_value[sizeof(WTFourCharCode)] = '\0'; -#endif - } - - explicit WCFourCC(const char* in_source_string) : - m_stored_value(stored_from_iter(in_source_string)) - { -#if kEnableWCFourCCDebug == 1 - m_c_str_stored_value[sizeof(WTFourCharCode)] = '\0'; -#endif - } - - explicit WCFourCC(const WCFixedStringBase& in_source_string) : - m_stored_value(stored_from_iter(in_source_string)) - { -#if kEnableWCFourCCDebug == 1 - m_c_str_stored_value[sizeof(WTFourCharCode)] = '\0'; -#endif - } - - WTFourCharCode GetAsSomeEndian(const wvNS::wvBO::byte_order_type in_byteOrder) const - { - return s_stored_byte_order==in_byteOrder ? m_stored_value : wvNS::wvBO::swap32(m_stored_value); - } - - WTFourCharCode GetAsBigEndian() const - { - return s_stored_byte_order==wvNS::wvBO::byte_order_big_endian ? m_stored_value : wvNS::wvBO::swap32(m_stored_value); - } - - WTFourCharCode GetAsLittleEndian() const - { - return s_stored_byte_order==wvNS::wvBO::byte_order_little_endian ? m_stored_value : wvNS::wvBO::swap32(m_stored_value); - } - - WTFourCharCode GetAsCompilerEndian() const - { - return s_stored_byte_order==wvNS::wvBO::compiler_byte_order ? m_stored_value : wvNS::wvBO::swap32(m_stored_value); - } - - WTFourCharCode GetAsStored() const - { - return m_stored_value; - } - - char operator[](const unsigned int in_character_index) const - { - return char(m_stored_value >> (8 * (s_stored_byte_order==wvNS::wvBO::compiler_byte_order ? 3-in_character_index : in_character_index))); - } - - char& operator[](const unsigned int in_character_index) - { - return reinterpret_cast<char*>(&m_stored_value)[s_stored_byte_order==wvNS::wvBO::byte_order_little_endian ? 3-in_character_index : in_character_index]; - } - - static size_t size() - { - return sizeof(WTFourCharCode); - } - - static size_t max_size() - { - return size(); - } - - static size_t capacity() - { - return size(); - } - - WCFixedString4 GetString() const - { - WCFixedString4 retVal; - retVal << operator[](0) << operator[](1) << operator[](2) << operator[](3); - - return retVal; - } - -#if kEnableWCFourCCDebug == 1 - const char* c_str() const - { - return m_c_str_stored_value; - } -#endif - -protected: - -private: -#if kEnableWCFourCCDebug == 1 - union - { -#endif - WTFourCharCode m_stored_value; -#if kEnableWCFourCCDebug == 1 - char m_c_str_stored_value[sizeof(WTFourCharCode)+1]; - }; -#endif - - WCFourCC& operator=(const WTFourCharCode); // we want initialization from literal to be dome through the constructor -}; - -inline bool operator<(const WCFourCC in_left, const WCFourCC in_right) -{ - return in_left.GetAsSomeEndian(WCFourCC::s_stored_byte_order) < in_right.GetAsSomeEndian(WCFourCC::s_stored_byte_order); -} -inline bool operator==(const WCFourCC in_left, const WCFourCC in_right) -{ - return in_left.GetAsSomeEndian(WCFourCC::s_stored_byte_order) == in_right.GetAsSomeEndian(WCFourCC::s_stored_byte_order); -} - -inline bool operator!=(const WCFourCC in_left, const WCFourCC in_right) -{ - return ! operator==(in_left, in_right); -} - - -#define kDefaultFourCC WCFourCC::kDefaultFourCC_prv() - -static const WCFourCC kZeroFourCC(0, wvNS::wvBO::compiler_byte_order); - -#endif //#if !defined(__WCFourCC_h__) - - - diff --git a/libs/backends/wavesaudio/wavesapi/BasicTypes/WTByteOrder.h b/libs/backends/wavesaudio/wavesapi/BasicTypes/WTByteOrder.h deleted file mode 100644 index c217fa7a1c..0000000000 --- a/libs/backends/wavesaudio/wavesapi/BasicTypes/WTByteOrder.h +++ /dev/null @@ -1,223 +0,0 @@ -/* - Copyright (C) 2014 Waves Audio Ltd. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. - -*/ - -#if !defined(__WTByteOrder_h__) -#define __WTByteOrder_h__ - -/* Copy to include -#include "BasicTypes/WTByteOrder.h" -*/ - -#include "WavesPublicAPI/wstdint.h" -#include "BasicTypes/WUDefines.h" - -// Stuff concerning little/big endian and the conversion between them. -// most of the code here was copied from NetShell with some modifications -// Written by Udi on Nov-2005 -// Adjusted to Cross platform by Shai Mar-2006 - -// Macros to determine endian. __BIG_ENDIAN__ & __LITTLE_ENDIAN__ should come from the compiler. -// We try to set the macro _BYTEORDER_BIG_ENDIAN to 1 if big-endian or to 0 if little-endian. - -// if the compiler properly has set either __BIG_ENDIAN__ or __LITTLE_ENDIAN__ -#if defined(__BIG_ENDIAN__) || defined(__LITTLE_ENDIAN__) -#if defined(__BIG_ENDIAN__) && defined(__LITTLE_ENDIAN__) //if both defined, check them as booleans -#if __BIG_ENDIAN__ && !__LITTLE_ENDIAN__ -#define _BYTEORDER_BIG_ENDIAN 1 -#elif !__BIG_ENDIAN__ && __LITTLE_ENDIAN__ -#define _BYTEORDER_BIG_ENDIAN 0 -#else -#error I am confused. Is this big-endian or little-endian? -#endif // stupid compiler defines both __LITTLE_ENDIAN__ and __BIG_ENDIAN__ -#elif defined(__BIG_ENDIAN__) -#define _BYTEORDER_BIG_ENDIAN 1 -#else -#define _BYTEORDER_BIG_ENDIAN 0 -#endif // big/little switch -#else // if the compiler proparly has NOT set either __BIG_ENDIAN__ or __LITTLE_ENDIAN__ -// http://msdn.microsoft.com/en-us/library/b0084kay.aspx for all preprocessor defs. _M_X64: 64 bit. _M_IA64: Itanium 64bit -#if defined(__i386__) || defined(__i386) || defined(_M_IX86) || defined(__INTEL__) || defined(__x86_64__) || defined(_M_X64) || defined(_M_IA64) -#define _BYTEORDER_BIG_ENDIAN 0 -#elif defined(_M_PPC) || defined(__POWERPC__ ) || defined(__ppc__) -#define _BYTEORDER_BIG_ENDIAN 1 -#else -#error Cannot detect compiler byte-order. Please add a test for your compiler appropriate symbol to this header file. -#endif // symbol search -#endif // standard preprocessor symbol found - -// code to determine which assembly code we can use -#if defined(_MSC_VER) && defined(_M_IX86) -#define _BYTEORDER_ASM_MSVC_I386 1 // Windows -#elif defined(__GNUC__) && defined(__i386__) -#define _BYTEORDER_ASM_GNUC_I386 1 // Linux, or MacOS with MacIntel on Xcode -#define _BYTEORDER_ASM_NONE 1 // Currently we have no assebley for GNU i386, so use the C version -#elif defined(__GNUC__) && defined(__POWERPC__) -#define _BYTEORDER_ASM_GNUC_PPC 1 // MacOS with PPC on Xcode -#define _BYTEORDER_ASM_NONE 1 // Currently we have no assebley for GNU PPC, so use the C version -#else -#define _BYTEORDER_ASM_NONE 1 // don't know the compiler and processor, use C implementation -#endif - -namespace wvNS { - -namespace wvBO // namespace Waves::ByteOrder -{ - typedef int byte_order_type; // we use int rather than enum because some compilers cannot resolve enum constants at compile-time. There are only two options anyway :-) - static const byte_order_type byte_order_little_endian = 0; - static const byte_order_type byte_order_big_endian = 1; - - - // We try to use this static const rather than preprocessor symbols in our code wherever possible. -#if _BYTEORDER_BIG_ENDIAN == 1 - static const byte_order_type compiler_byte_order = byte_order_big_endian; -#else - static const byte_order_type compiler_byte_order = byte_order_little_endian; -#endif - - - //--------------------------------------------------------------------------------- - // swap functions - best if implemented in inline assembly code - // The following are very slow swappers when compiled, do not use in loops -#if _BYTEORDER_ASM_MSVC_I386 - - // assembly implementation for Intel386 on Visual Studio - inline uint16_t swap16(uint16_t x) - { - __asm MOV AX,x; - __asm XCHG AL,AH; - __asm MOV x,AX; - return x; - } - - inline uint32_t swap32(uint32_t x) - { - __asm MOV EAX,x; - __asm BSWAP EAX; - __asm MOV x,EAX; - return x; - } - inline uint64_t swap64(uint64_t x) // TODO: To be replaced - { - return - ((x>>7*8)&0xFF)<<0*8 | ((x>>6*8)&0xFF)<<1*8 | ((x>>5*8)&0xFF)<<2*8 | ((x>>4*8)&0xFF)<<3*8 | - ((x>>3*8)&0xFF)<<4*8 | ((x>>2*8)&0xFF)<<5*8 | ((x>>1*8)&0xFF)<<6*8 | ((x>>0*8)&0xFF)<<7*8 ; - } - - /* the ASM code for swap64 does not compile - inline uint64_t swap64(uint64_t x) - { - __asm MOV EBX, OFFSET x; - __asm MOV EAX, [EBX]; - __asm MOV EDX, [EBX+4]; - __asm BSWAP EAX; - __asm BSWAP EDX; - __asm MOV [EBX],EDX; - __asm MOV [EBX+4],EAX; - return x; - } - */ -#endif // _BYTEORDER_ASM_MSVC_I386 - -#if _BYTEORDER_ASM_GNUC_I386 - // assembly implementation for Intel386 on GCC (Linux) - // TODO -#endif // _BYTEORDER_ASM_GNUC_I386 - -#if _BYTEORDER_ASM_GNUC_PPC - // assembly implementation for PowerPC on GCC (XCode) - // TODO -#endif // _BYTEORDER_ASM_GNUC_PPC - -#if _BYTEORDER_ASM_NONE - inline uint16_t swap16(uint16_t x) { return (x>>8) | ((x&0xFF)<<8); } - inline uint32_t swap32(uint32_t x) { return (x&0xFF)<<24 | (x&0xFF00)<<8 | (x&0xFF0000)>>8 | (x&0xFF000000)>>24; } - inline uint64_t swap64(uint64_t x) - { - return - ((x>>7*8)&0xFF)<<0*8 | ((x>>6*8)&0xFF)<<1*8 | ((x>>5*8)&0xFF)<<2*8 | ((x>>4*8)&0xFF)<<3*8 | - ((x>>3*8)&0xFF)<<4*8 | ((x>>2*8)&0xFF)<<5*8 | ((x>>1*8)&0xFF)<<6*8 | ((x>>0*8)&0xFF)<<7*8 ; - } -#endif // _BYTEORDER_ASM_NONE - - - - - //--------------------------------------------------------------------------------- - - // order conversion functions - // may want to overload for float and double as well. - // overload for signed ints is ambiguous and should be done only if no other choice exists. - // - - - - - - - - - - - - - - - - - - - - - inline uint16_t compiler_to_big_16(uint16_t x) - { - return compiler_byte_order==byte_order_big_endian ? x : swap16(x); - } - inline uint16_t big_to_compiler_16(uint16_t x) - { - return compiler_byte_order==byte_order_big_endian ? x : swap16(x); - } - inline uint16_t compiler_to_little_16(uint16_t x) - { - return compiler_byte_order==byte_order_little_endian ? x : swap16(x); - } - inline uint16_t little_to_compiler_16(uint16_t x) - { - return compiler_byte_order==byte_order_little_endian ? x : swap16(x); - } - // - - - - - - - - - - - - - - - - - - - - - inline uint32_t compiler_to_big_32(uint32_t x) - { - return compiler_byte_order==byte_order_big_endian ? x : swap32(x); - } - inline uint32_t big_to_compiler_32(uint32_t x) - { - return compiler_byte_order==byte_order_big_endian ? x : swap32(x); - } - inline uint32_t compiler_to_little_32(uint32_t x) - { - return compiler_byte_order==byte_order_little_endian ? x : swap32(x); - } - inline uint32_t little_to_compiler_32(uint32_t x) - { - return compiler_byte_order==byte_order_little_endian ? x : swap32(x); - } - // - - - - - - - - - - - - - - - - - - - - - inline uint64_t compiler_to_big_64(uint64_t x) - { - return compiler_byte_order==byte_order_big_endian ? x : swap64(x); - } - inline uint64_t big_to_compiler_64(uint64_t x) - { - return compiler_byte_order==byte_order_big_endian ? x : swap64(x); - } - inline uint64_t compiler_to_little_64(uint64_t x) - { - return compiler_byte_order==byte_order_little_endian ? x : swap64(x); - } - inline uint64_t little_to_compiler_64(uint64_t x) - { - return compiler_byte_order==byte_order_little_endian ? x : swap64(x); - } - -} // namespace wvBO - -} // namespace wvNS { - -#endif // #if !defined(__WTByteOrder_h__) - diff --git a/libs/backends/wavesaudio/wavesapi/BasicTypes/WUComPtr.h b/libs/backends/wavesaudio/wavesapi/BasicTypes/WUComPtr.h deleted file mode 100644 index e8e633d927..0000000000 --- a/libs/backends/wavesaudio/wavesapi/BasicTypes/WUComPtr.h +++ /dev/null @@ -1,118 +0,0 @@ -/* - Copyright (C) 2014 Waves Audio Ltd. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. - -*/ - -#ifndef __WUComPtr_h__ -#define __WUComPtr_h__ - -/* Copy to include -#include "BasicTypes/WUComPtr.h" -*/ - -#include "WavesPublicAPI/wstdint.h" - -typedef int32_t wvComPtr[2]; - -// ConvertDPtr has the exact format of a vfp callback function, but it is a local function, native only. -// It converts a pointer in either 32 bits or 64 bits to a place-holder of 64 bits in coefs/states/external memory. -// pData is expected to point to a pre-allocate space enough for storing a pointer (posibly two single-precision coefs). -// Since pointers are not transferable between hardwares, at preset time no need for a shell callback. -// We keep this as a cALGORITHM for compatibility with the rest of the convert functions -//================================================================================ -inline uint32_t vfpConvertDPtr(const void* InPointer, void* pData) -//================================================================================ -{ - uint64_t *pL = (uint64_t *)pData; - *pL = (uint64_t)InPointer; - return (uint32_t)sizeof(uint64_t); -} - - -/* -{ - // data in that struct must be the same type of the Coefs/States type! - int32_t LSW; // Least significant word - int32_t MSW; // Most significant word -}; - -inline wvComPtr PackToComPtr(const intptr_t in_PtrToPack) -// take ptr that hosted in intptr_t type -// and pack it to wvComPtr container type (MSW and LSW of 32bit each) -{ - wvComPtr retVal; - int64_t t_PtrToPack = static_cast<int64_t>(in_PtrToPack); - // This packing is xPlatform coding for x32 and x64 - // #ifdef for x64 - intptr_t is 64 bit - retVal.LSW = static_cast<int32_t>(t_PtrToPack & intptr_t(0xFFFFFFFF)); - retVal.MSW = (static_cast<int32_t>(t_PtrToPack>>32)); - - // #ifdef for x32 - intptr_t is 32 bit -// retVal.LSW = int32_t(in_PtrToPack); -// retVal.MSW = 0; - - return retVal; -} - -inline intptr_t UnpackComPtr( const wvComPtr in_ComPtrToUnpack) -// take wvComPtr with MSW and LSW of 32bit each -// and unpack it to intptr_t type -{ - intptr_t retVal; - - // This unpacking is xPlatform coding for x32 and x64 - // #ifdef for x64 - intptr_t is 64 bit so use intptr_t instead of int64_t - int64_t PtrAt64 = static_cast<int64_t>(in_ComPtrToUnpack.MSW); - PtrAt64 <<= 32; - PtrAt64 |= static_cast<int64_t>(in_ComPtrToUnpack.LSW); - retVal = static_cast<intptr_t>(PtrAt64); - - - // #ifdef for x32 - intptr_t is 32 bit -// retVal = static_cast<intptr_t>(retVal.LSW); - - return retVal; -} - - -////////////////////////////////////////////////////////////////////////// -inline uint32_t ComPtr_to_DSP( const intptr_t PtrToConvert, char* pDataStruct ) -{ - - *(reinterpret_cast<wvComPtr *>(pDataStruct)) = PackToComPtr(PtrToConvert); - - return uint32_t(sizeof(wvComPtr)); -} -////////////////////////////////////////////////////////////////////////// - -////////////////////////////////////////////////////////////////////////// -inline uint32_t DSP_to_ComPtr( const char* pDataStruct, intptr_t *ThePtr) -// pDataStruct is pointing to wvComPtr in the Coefs/States -// the function reconstruct the pointer into ThePtr -{ - - *ThePtr = UnpackComPtr(*(reinterpret_cast<const wvComPtr *>(pDataStruct))); - - return uint32_t(sizeof(wvComPtr)); -} -////////////////////////////////////////////////////////////////////////// -*/ - -#endif //#if !defined(__WUComPtr_h__) - - - diff --git a/libs/backends/wavesaudio/wavesapi/BasicTypes/WUDefines.h b/libs/backends/wavesaudio/wavesapi/BasicTypes/WUDefines.h deleted file mode 100644 index 293f3bd247..0000000000 --- a/libs/backends/wavesaudio/wavesapi/BasicTypes/WUDefines.h +++ /dev/null @@ -1,176 +0,0 @@ -/* - Copyright (C) 2014 Waves Audio Ltd. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. - -*/ - -#ifndef __WUDefines_h__ - #define __WUDefines_h__ - -/*Copy to include -#include "BasicTypes/WUDefines.h" -*/ - -#include "1.0/WavesPublicAPI_Defines.h" - -// When changing wvNS value also do the same change in Objective_C_MangledNames.h -// because CWSAUCocoaViewFactoryAsString is hard coded there -#define wvNS wvWavesV9_3 -#ifdef __APPLE__ - #define ObjCNameSpace(__className__) wvWavesV9_3_ ## __className__ -#endif - -#ifdef INSIDE_NETSHELL - #define DllExport -#else - #define DllExport WPAPI_DllExport -#endif - -#define __CDECL __WPAPI_CDECL -#define __STDCALL __WPAPI_STDCALL - - -#ifndef NULL - #define NULL (0) -#endif - -#ifndef nil - #define nil NULL -#endif - -#define PASCAL_MAC_ONLY #error do not use PASCAL_MAC_ONLY. See defintions in WavesFTT.h for replacment. -#define CALLCON #error do not use CALLCON. See defintions in WavesFTT.h for replacment. -#define FUNCEXP #error do not use FUNCEXP. See defintions in WavesFTT.h for replacment. - -#define WUNUSED_PARAM(__SOME_UNUSED_PARAM__) ((void)__SOME_UNUSED_PARAM__) - -#ifdef __APPLE__ - const char* const OS_NAME = "Mac"; - - #define WIN_ONLY(__Something_only_for_windows__) - #define MAC_ONLY(__Something_only_for_mac__) __Something_only_for_mac__ - - #if defined(i386) || defined(__i386) || defined(__i386__) - #define kNumArchBits 32 - #endif - #if defined(__x86_64) || defined(__x86_64__) - #define kNumArchBits 64 - #endif - - #if (__i386 || __x86_64) && !defined(__LITTLE_ENDIAN__) - #define __LITTLE_ENDIAN__ - #endif - #if !(__i386 || __x86_64) && !defined(__BIG_ENDIAN__) - #define __BIG_ENDIAN__ - #endif - #ifdef __GNUC__ - #define STD_EXCEPT_WIN std - #define FAR - #define PASCAL - // #define HINSTANCE void* - #define WINAPI - - #else - - #define DllExport_WinOnly - #define STD_EXCEPT_WIN std - #define FAR - #define PASCAL // windows' pascal - #define HINSTANCE void* - #define WINAPI - - #endif - #define THROW_SPEC(THROW_OBJ) throw (THROW_OBJ) - - #define WUNUSED_PARAM_ON_MAC(__SOME_UNUSED_PARAM__) WUNUSED_PARAM(__SOME_UNUSED_PARAM__) - #define WUNUSED_PARAM_ON_WIN(__SOME_UNUSED_PARAM__) -#endif - - -#ifdef PLATFORM_WINDOWS - const char* const OS_NAME = "Win"; - - #define WIN_ONLY(__Something_only_for_windows__) __Something_only_for_windows__ - #define MAC_ONLY(__Something_only_for_mac__) - - #if defined(_M_X64) - #define kNumArchBits 64 - #else // not sure what are the VisualStudio macros for 32 bits - #define kNumArchBits 32 - #endif - - #define DllExport_WinOnly DllExport // help solve window specific link errors - #define STD_EXCEPT_WIN - - #if !defined(__MINGW64__) - #define round(x) (floor(x+0.5)) - #endif - - #define __LITTLE_ENDIAN__ - #define THROW_SPEC(THROW_OBJ) throw (...) - - #define WUNUSED_PARAM_ON_MAC(__SOME_UNUSED_PARAM__) - #define WUNUSED_PARAM_ON_WIN(__SOME_UNUSED_PARAM__) WUNUSED_PARAM(__SOME_UNUSED_PARAM__) - -#endif - -#ifdef __linux__ - const char* const OS_NAME = "Linux"; - - #define WIN_ONLY(__Something_only_for_windows__) - #define MAC_ONLY(__Something_only_for_mac__) - - #define DllExport_WinOnly - #define STD_EXCEPT_WIN std - #define FAR - #define PASCAL - // #define HINSTANCE void* - #define WINAPI - #if __i386 && !defined(__LITTLE_ENDIAN__) - #define __LITTLE_ENDIAN__ - #endif - #if !__i386 && !defined(__BIG_ENDIAN__) - #define __BIG_ENDIAN__ - #endif - #define THROW_SPEC(THROW_OBJ) throw (THROW_OBJ) - - #if defined(__x86_64) || defined(__LP64__) - #error "64 bit not suported yet on linux" - #else - #define kNumArchBits 32 - #endif -#endif - -#ifndef _WU_DECL - #define _WU_DECL __CDECL // the default is calling model is cdecl, but you can also set this macro from the outside to something different -#endif - -#ifndef _XML_DECL - #define _XML_DECL __CDECL // the default is calling model is cdecl, but you can also set this macro from the outside to something different -#endif - -#ifndef kNumArchBits - #error Macro kNumArchBits was not defined -#endif - -#if kNumArchBits == 64 - const char* const kNumArchBits_c_str = "64"; -#endif -#if kNumArchBits == 32 - const char* const kNumArchBits_c_str = "32"; -#endif - -#endif //__WUDefines_h__ diff --git a/libs/backends/wavesaudio/wavesapi/BasicTypes/WUMathConsts.h b/libs/backends/wavesaudio/wavesapi/BasicTypes/WUMathConsts.h deleted file mode 100644 index 6ee16c2ad6..0000000000 --- a/libs/backends/wavesaudio/wavesapi/BasicTypes/WUMathConsts.h +++ /dev/null @@ -1,48 +0,0 @@ -/* - Copyright (C) 2014 Waves Audio Ltd. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. - -*/ - -#ifndef __WUMathConsts_h__ - #define __WUMathConsts_h__ - -/* Copy to include: -#include "BasicTypes/WUMathConsts.h" -*/ - -const float kfPI = 3.1415926535898f; // PI, single precision -const double kdPI = 3.1415926535897932384626433832795; // PI, double precision - -const float kf2PI = 6.2831853071796f; // 2*PI -const double kd2PI = 6.283185307179586476925286766559; // 2*PI - -const float kfhalfPI = 1.5707963267949f; // 0.5*PI -const double kdhalfPI = 1.57079632679489661923; // 0.5*PI - -const double kdLn2 = 0.69314718055994530942; // natural log(2.0) -const double kdOneOverLn2 = 1.4426950408889634073599246810019; // natural (1.0/log(2.0)) - for multiply log() to get it as with base 2 - -const double kdLog2 = 0.301029995663981; // log10(2.0) -const double kdOneOverLog2 = 3.321928094887363; // (1.0/log10(2.0)) - for multiply log() to get it as with base 2 - -const double kdExponent = 2.718281828459045235360287471352; // e - -const double kdSqrt2 = 1.41421356237309504880; // sqrt(2) - - - -#endif //__WUMathConsts_h__ diff --git a/libs/backends/wavesaudio/wavesapi/BasicTypes/WUTypes.h b/libs/backends/wavesaudio/wavesapi/BasicTypes/WUTypes.h deleted file mode 100644 index 8c6ac71cfc..0000000000 --- a/libs/backends/wavesaudio/wavesapi/BasicTypes/WUTypes.h +++ /dev/null @@ -1,266 +0,0 @@ -/* - Copyright (C) 2014 Waves Audio Ltd. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. - -*/ - -#ifndef __WUTypes_h__ - #define __WUTypes_h__ - -/* Copy to include: -#include "BasicTypes/WUTypes.h" -*/ - -#include "WavesPublicAPI/WTErr.h" -#include "WavesPublicAPI/wstdint.h" -#include "BasicTypes/WUDefines.h" -#include "BasicTypes/WCFourCC.h" // declares WTFourCharCode & WCFourCC -#include "BasicTypes/WUComPtr.h" // Communication Ptr for x64 compatibility -#include "WCFixedString.h" -#include <ctime> -#include <vector> -/******************************************************************************** - Atoms -*********************************************************************************/ - -#define WTSInt64 "WTSInt64 is obsolete, please use int64_t instead"; -#define WTUInt64 "WTUInt64 is obsolete, please use uint64_t instead"; -#define WTSInt32 "WTSInt32 is obsolete, please use int32_t instead"; -#define WTUInt32 "WTUInt32 is obsolete, please use uint32_t instead"; -#define WTSInt16 "WTSInt16 is obsolete, please use int16_t instead"; -#define WTUInt16 "WTUInt16 is obsolete, please use uint16_t instead"; -#define WTSInt8 "WTSInt8 is obsolete, please use int8_t instead"; -#define WTUInt8 "WTUInt8 is obsolete, please use uint8_t instead"; -#define WTFloat32 "WTFloat32 is obsolete, please use float instead"; -#define WTByte "WTByte is obsolete, please use uint8_t instead"; - -/******************************************************************************** - Consts -*********************************************************************************/ -//#define PI 3.1415926535897 // ... Was moved to WUMathConsts.h under the name kPI -const uint32_t kDefaultCircleSlices = 100; - - -/******************************************************************************** - Utilities -*********************************************************************************/ - -// SCOPED_ENUM is a macro that defines an enum inside a class with a given name, thus declaring the enum values -// inside a named scope. This allows declaring: -// SCOPED_ENUM(SomeType) -// { -// Val1, -// Val2, -// Val3 -// } -// SCOPED_ENUM_END -// And then you can reference SomeType::Val1, SomeType::Val2, SomeType::Val3 for the various values, unlike -// a regular enum on which Val1, Val2 and Val3 would become global names. -// Additionally, you get SomeType::Type to specify the type of the whole enum in case you want to transfer it to -// a function. -// Don't forget to close the enum with SCOPED_ENUM_END, otherwise you'll get bogus compilation errors. -// This requirement can probably be removed some day, but it will make the SCOPED_ENUM macro much less readable... -#define SCOPED_ENUM(name) \ -class name \ -{ \ -public: enum Type - -#define SCOPED_ENUM_END ;}; - - -//******************************************************************************** -// Files - -//! file (and resource container) opening permissions -// Note: When opening with eFMWriteOnly on existing file, writing to the file will append, not overwrite, Shai, 9/8/2007. -enum WEPermitions{ eFMReadOnly, eFMWriteOnly, eFMReadWrite}; - -// File cursor positions -enum WEPositionMode{eFMFileBegin, eFMFileCurrent, eFMFileEnd}; - -// File creation types -enum WECreateFlags { - eFMCreateFile_DontOverrideIfAlreadyExists, // Create a new file , If the file exists leaves the existing data intact - eFMCreateFile_FailIfAlreadyExists, // Attempt to create a new file, if file already exists - fail. - eFMCreateFile_OverrideIfAlreadyExists // Create a new file , If the file exists, overwrite the file and clear the existing data -}; - - -enum WEFoldersDomain{ - eSystemDomain, - eLocalDomain, - eUserDomain, - - eNumberOfFoldersDomains -}; -enum WEArchBits{ - e32Bits, - e64Bits, - eNumberOfArchBits -}; - -enum WESystemFolders{ - eSystemFolder, - eDesktopFolder, - ePreferencesFolder, - eWavesPreferencesFolder, //deprecated use eWavesPreferencesFolder2 - eTemporaryFolder, - eTrashFolder, - eCurrentFolder, - eRootFolder, - eLibrariesFolder, - eAudioComponentsFolder, // MacOS only - eCacheFolder, - eWavesCacheFolder, - eAppDataFolder, - eWavesAppDataFolder, - eSharedUserDataFolder, - eWavesSharedUserDataFolder, - eWavesScanViewFolder, - - eWavesPreferencesFolder2, // Mac: "/Users/username/Library/Preferences/Waves Audio" - // Win: "C:\Users\username\AppData\Roaming\Waves Audio\Preferences" - - eNumberOfSystemFolders -}; - -//******************************************************************************** -// Process - -#ifdef __APPLE__ - typedef uint32_t WTProcessID; // actually pid_t which is __darwin_pid_t which is __uint32_t -#endif -#ifdef PLATFORM_WINDOWS - typedef int WTProcessID; -#endif -#ifdef __linux__ - typedef uint32_t WTProcessID; -#endif - -enum WEManagerInitOptions -{ - eUnknown_ManagerInitOption, - eMacOS_Carbon_Runtime, - eMacOS_Cocoa_Runtime, - eLinuxOS_gtk_Runtime, - eLinuxOS_X_Runtime, - eWindowsOS_GoodOld_Runtime, // good old windows API - eWindowsOS_DotNET_Runtime, - eVerticalFliped_Graphics, - eInit_RM, - eInit_GMConfig, - eInit_PVM, - eInit_UM, - eInit_BKG -}; -#ifdef __APPLE__ - #if __LP64__ || NS_BUILD_32_LIKE_64 // in 64bit (or when NS_BUILD_32_LIKE_64 is specified) we decline Carbon implementation. - const WEManagerInitOptions eDefaultRuntime = eMacOS_Cocoa_Runtime; - #else - const WEManagerInitOptions eDefaultRuntime = eMacOS_Carbon_Runtime; - #endif -#endif -#ifdef PLATFORM_WINDOWS - const WEManagerInitOptions eDefaultRuntime = eWindowsOS_GoodOld_Runtime; -#endif -#ifdef __linux__ - const WEManagerInitOptions eDefaultRuntime = eLinuxOS_gtk_Runtime; -#endif - - -//******************************************************************************** -// Files - -const uint32_t kMaxPathLength = 1023; // maximum length of a path -const uint32_t kMaxFileNameLength = 255; // maximum length of a file name including extension -typedef WCFixedString<kMaxPathLength> WTPathString; -typedef WCFixedString<kMaxFileNameLength> WTFileNameString; - -typedef uint64_t WTFileSize; -const WTFileSize kIllegalFileSize = (WTFileSize)-1; - -typedef off_t WTFileOffset; - -typedef std::time_t WTFileTime; -const WTFileTime kIllegalFileTime = (WTFileTime)-1; - -typedef struct WTPathType* WTPathRef; // represents a path, path need not exists -typedef struct WTOpenFileType* WTOpenFileRef; // represents a real, open file -typedef struct WTNativeDLLRefType* WTNativeDLLRef; // define WTNativeDLLRef as a unique type CFBundleRef on Mac, HINSTANCE on Windows -const WTNativeDLLRef kIllegalNativeDLLRef = 0; -//******************************************************************************** -// Resources - -const size_t kMaxResTypeLength = 31; -typedef WCFixedString31 WTResType; -typedef short WTResID; -const WTResID kIllegalResID = -1; - - -typedef struct WTResContainerType* WTResContainerRef; -typedef struct WTResourceType* WTResRef; -const WTResContainerRef kIllegalContainerRef = 0; -const WTResRef kIllegalResourceRef = 0; - -#ifdef __APPLE__ - typedef struct WTNativeResourceType* WTNativeResourceRef; // for use when need to have access to the native resource without going though resource manager caching anf conversion. - const WTNativeResourceRef kIllegalNativeResourceRef = 0; -#endif -#ifdef PLATFORM_WINDOWS - typedef struct WTNativeResourceType* WTNativeResourceRef; //HGLOBAL // for use when need to have access to the native resource without going though resource manager caching anf conversion. - const WTNativeResourceRef kIllegalNativeResourceRef = 0; -#endif -#ifdef __linux__ -typedef void* WTNativeResourceRef; // WTOpenFileRef // for use when need to have access to the native resource without going though resource manager caching anf conversion. - const WTNativeResourceRef kIllegalNativeResourceRef = 0; -#endif - -//******************************************************************************** -// OpenGL - -typedef struct WCOGLContext* WCOGLContextRef; -typedef struct WCOGLTexture* WCOGLTextureRef; -typedef struct WSPluginView* WCPluginViewRef; -typedef struct WSMenu* WCMenuRef; -typedef struct WCPluginNativeView* WCPluginNativeViewRef; - -const WCOGLContextRef kIllegalOGLContextRef = 0; -const WCOGLTextureRef kIllegalOGLTextureRef = 0; -const WCPluginViewRef kIllegalPluginViewRef = 0; -const WCMenuRef kIllegalWCMenuRef = 0; - -const intptr_t kIllegalTexturesMaster = -1; - - -typedef unsigned int WTTextureRef; -const WTTextureRef kIllegalTextureRef = 0; - -// type for storing pointer to functions. Used to avoid warning such as "C++ forbids conversion between pointer to function and pointer to object" -typedef void (*DUMMY_FUNC_PTR)(void); - -// type for a generic callback function with one parameter -typedef intptr_t (*CALLBACK_1_PARAM_FUNC_PTR)(intptr_t); - -////////////////////////////////////////////////////////////// -// Timer -typedef intptr_t WTTimerRef; -const WTTimerRef kIllegalTimerRef = 0; -typedef void (*WTTimerCallback)(intptr_t); - -// generic type for OS native pointer -typedef void* WTPtr; - -#endif //__WUTypes_h__ diff --git a/libs/backends/wavesaudio/wavesapi/MiscUtils/MinMaxUtilities.h b/libs/backends/wavesaudio/wavesapi/MiscUtils/MinMaxUtilities.h deleted file mode 100644 index 4260f680a5..0000000000 --- a/libs/backends/wavesaudio/wavesapi/MiscUtils/MinMaxUtilities.h +++ /dev/null @@ -1,133 +0,0 @@ -/* - Copyright (C) 2014 Waves Audio Ltd. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. - -*/ - -#ifndef __MinMaxUtilities_h__ -#define __MinMaxUtilities_h__ - -/* copy to include -#include "MiscUtils/MinMaxUtilities.h" -*/ - -#include "BasicTypes/WUDefines.h" -#include "BasicTypes/WUMathConsts.h" -#include "WavesPublicAPI/wstdint.h" - -#ifdef __GNUC__ -#undef round -#endif - -// New accelerated templates -#if defined ( __cplusplus ) && !defined (__WUMinMax) -#define __WUMinMax // Also defined in Nativepr.h - - -template<class T> inline T WUMin(const T &a, const T &b) {return (a < b) ? a : b;} // requires only < to be defined for T -template<class T> inline T WUMax(const T &a,const T &b) {return (a < b) ? b : a;} // requires only < to be defined for T -template<class T> inline T WUMinMax(const T &Smallest, const T &Biggest, const T &Val) // requires only < to be defined for T -{ - return ((Val < Smallest) ? Smallest : ((Biggest < Val) ? Biggest : Val)); -} -/* -// Min and Max - template<class T> inline T WUMin(T a,T b) {return (a < b) ? a : b;} // requires only < to be defined for T - template<class T> inline T WUMax(T a,T b) {return (a < b) ? b : a;} // requires only < to be defined for T - template<class T> inline T WUMinMax(T SMALLEST, T BIGGEST, T X) // requires only < to be defined for T - { - return ((X < SMALLEST) ? SMALLEST : ((BIGGEST < X) ? BIGGEST : X)); - } - */ -// Absolute value - -#ifdef PLATFORM_WINDOWS - #include <math.h> - -#ifndef __GNUC__ -#define __abs(x) abs(x) -#define __labs(x) labs(x) -#define __fabs(x) fabs(x) -#endif - -#endif - -#ifdef __GNUC__ - #include <iostream> // why don't know makes it work need to check - #include <cstdlib> - #include <cmath> - -#define __abs(x) std::abs(x) -#define __labs(x) std::labs(x) -#define __fabs(x) std::fabs(x) -#endif - #ifdef __APPLE__ - #ifdef __GNUC__ - #include <iostream> // why don't know makes it work need to check - #include <cmath> -#define __abs(x) std::abs(x) -#define __labs(x) std::labs(x) -#define __fabs(x) std::fabs(x) - #endif - #endif - -// log2: on Windows there's no proper definition for log2, whereas on other platform there is. - #ifndef WUlog2 - #if defined(PLATFORM_WINDOWS) - #define WUlog2(x) (kdOneOverLog2 * log10((x))) - #else - #define WUlog2(x) log2(x) - #endif - #endif - -template <class T> inline T WUAbs(const T &xA) -{ - return (xA > T(0))? xA: -xA; -} - -template <> inline int WUAbs(const int &xA) -{ - return __abs(xA); -} - -//template <> inline int32_t WUAbs(const int32_t &xA)// 64BitConversion -//{ -// return __labs(xA); -//} - -template <> inline float WUAbs(const float &xA) -{ - return (float) __fabs(xA); -} - -template <> inline double WUAbs(const double &xA) -{ - return __fabs(xA); -} - -#endif - -int32_t DllExport WURand(intptr_t in_Seed); -int32_t DllExport WURand(); -int32_t DllExport rand_gen_formula(int32_t rndSeed); - -template <class T> inline bool WUIsEqualWithTolerance(const T &xA, const T &xB, const T &xTolerance) -{ - return (WUAbs(xA - xB) < xTolerance) ? true : false; -} - - -#endif diff --git a/libs/backends/wavesaudio/wavesapi/MiscUtils/UMicroseconds.cpp b/libs/backends/wavesaudio/wavesapi/MiscUtils/UMicroseconds.cpp deleted file mode 100644 index c51d1910b0..0000000000 --- a/libs/backends/wavesaudio/wavesapi/MiscUtils/UMicroseconds.cpp +++ /dev/null @@ -1,77 +0,0 @@ -#ifdef PLATFORM_WINDOWS - #include "IncludeWindows.h" -#endif -#if defined(__linux__) || defined(__APPLE__) - #include <sys/time.h> -#endif - -#include "UMicroseconds.h" - -namespace wvNS { -UMicroseconds& UMicroseconds::ReadTime() -{ - // Note: g_get_monotonic_time() may be a viable alternative - // (it is on Linux and OSX); if not, this code should really go into libpbd -#ifdef PLATFORM_WINDOWS - LARGE_INTEGER Frequency, Count ; - - QueryPerformanceFrequency(&Frequency) ; - QueryPerformanceCounter(&Count); - theTime = uint64_t((Count.QuadPart * 1000000.0 / Frequency.QuadPart)); - -#elif defined __MACH__ // OSX, BSD.. - - clock_serv_t cclock; - mach_timespec_t mts; - host_get_clock_service(mach_host_self(), SYSTEM_CLOCK, &cclock); - clock_get_time(cclock, &mts); - mach_port_deallocate(mach_task_self(), cclock); - theTime = (uint64_t)mts.tv_sec * 1e6 + (uint64_t)mts.tv_nsec / 1000; - -#else // Linux, POSIX - - struct timespec *ts - clock_gettime(CLOCK_MONOTONIC, ts); - theTime = (uint64_t)ts.tv_sec * 1e6 + (uint64_t)buf.tv_nsec / 1000; - -#endif - - return *this; -} -/* - Removed in favor of the posix implementation. -#ifdef __APPLE__ - uint32_t UMicroseconds::hi() {return reinterpret_cast<UnsignedWide*>(&theTime)->hi;} - uint32_t UMicroseconds::lo() {return reinterpret_cast<UnsignedWide*>(&theTime)->lo;} -#endif -*/ -void UMicrosecondsAccumulator::Start() -{ - m_start_time.ReadTime(); -} - -void UMicrosecondsAccumulator::Stop() -{ - UMicroseconds stop_time; - - m_accumulator += stop_time.GetNativeTime() - m_start_time.GetNativeTime(); -} - -void UMicrosecondsAccumulator::Clear() -{ - m_start_time = 0; - m_accumulator = 0; -} - -UMicroseconds UMicrosecondsAccumulator::GetAccumulatedTime() const -{ - return m_accumulator; -} - -UMicrosecondsAccumulator& UMicrosecondsAccumulator::operator+=(const UMicrosecondsAccumulator& inaccum_to_add) -{ - m_accumulator += inaccum_to_add.GetAccumulatedTime(); - return *this; -} - -} // namespace wvNS { diff --git a/libs/backends/wavesaudio/wavesapi/MiscUtils/UMicroseconds.h b/libs/backends/wavesaudio/wavesapi/MiscUtils/UMicroseconds.h deleted file mode 100644 index af1eb8e37f..0000000000 --- a/libs/backends/wavesaudio/wavesapi/MiscUtils/UMicroseconds.h +++ /dev/null @@ -1,124 +0,0 @@ -/* - Copyright (C) 2014 Waves Audio Ltd. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. - -*/ - -#ifndef __UMicroseconds_h__ - #define __UMicroseconds_h__ - -/* Copy to include -#include "UMicroseconds.h" -*/ - - - -#include "BasicTypes/WUDefines.h" -#include "BasicTypes/WUTypes.h" - -namespace wvNS { -// a wraper for Microseconds function from Timer.h -class DllExport UMicroseconds -{ -public: - -#ifdef PLATFORM_WINDOWS - typedef int64_t TimeKeeper; -#endif -#ifdef __APPLE__ - typedef uint64_t TimeKeeper; -#endif -#ifdef __linux__ - typedef uint64_t TimeKeeper; -#endif - -private: - TimeKeeper theTime; - -public: - - UMicroseconds() - { - ReadTime(); - } - - UMicroseconds(const TimeKeeper in_initVal) : theTime(in_initVal) {} - - UMicroseconds(const UMicroseconds& inUM) : theTime(inUM.theTime) {} - UMicroseconds& operator=(const UMicroseconds& inUM) {theTime = inUM.theTime; return *this;} - UMicroseconds& operator+=(const TimeKeeper in_timeToAdd) {theTime += in_timeToAdd; return *this;} - - UMicroseconds& ReadTime(); - - TimeKeeper GetNativeTime() const {return theTime;} - operator uint64_t () {return static_cast<uint64_t>(theTime);} - operator double () const {return static_cast<const double>(theTime);} - - double Seconds() const {return static_cast<double>(theTime) / double(1000000);} - double MilliSeconds() const {return static_cast<double>(theTime) / double(1000);} - double MicroSeconds() const {return static_cast<double>(theTime);} - -#ifdef __APPLE__ - uint32_t hi(); - uint32_t lo(); -#endif -}; - -inline UMicroseconds operator-(const UMicroseconds& in_one, const UMicroseconds& in_two) -{ - UMicroseconds retVal(in_one.GetNativeTime() - in_two.GetNativeTime()); - return retVal; -} - -class UMicrosecondsAccumulator -{ -public: - UMicrosecondsAccumulator() : m_start_time(0), m_accumulator(0) {} - - void Start(); - void Stop(); - void Clear(); - - UMicroseconds GetAccumulatedTime() const; - - UMicrosecondsAccumulator& operator+=(const UMicrosecondsAccumulator&); - -protected: - UMicroseconds m_start_time; - UMicroseconds m_accumulator; -}; - -inline UMicroseconds operator-(const UMicrosecondsAccumulator& in_one, const UMicrosecondsAccumulator& in_two) -{ - UMicroseconds retVal(in_one.GetAccumulatedTime() - in_two.GetAccumulatedTime()); - return retVal; -} - -//=========================================================================================// -inline void MicrosecondDelay(double amt) -//=========================================================================================// -{ - UMicroseconds than; - UMicroseconds now; - - do - { - now.ReadTime(); - } while ((now.MicroSeconds() - than.MicroSeconds()) < amt); -} - -} // namespace wvNS { -#endif //#ifndef __UMicroseconds_h__ diff --git a/libs/backends/wavesaudio/wavesapi/MiscUtils/WCFixedString.h b/libs/backends/wavesaudio/wavesapi/MiscUtils/WCFixedString.h deleted file mode 100644 index d127e0116a..0000000000 --- a/libs/backends/wavesaudio/wavesapi/MiscUtils/WCFixedString.h +++ /dev/null @@ -1,904 +0,0 @@ -/* - Copyright (C) 2014 Waves Audio Ltd. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. - -*/ - -#ifndef __WCFixedString_h__ - #define __WCFixedString_h__ - -/* Copy to include. -#include "WCFixedString.h" -*/ -// do not #include anything else here but standard C++ library files, this file should be free from any and all depandencies -// do not put any DEBUG_s or TRACE_s in this file, since it is used in BgkConsole functions - -#include <algorithm> -#include <cctype> -#include <cstring> -#include <cstdio> - -#ifdef __APPLE__ -#include <strings.h> -#endif - -#include "BasicTypes/WUDefines.h" -#include "BasicTypes/WTByteOrder.h" -#include "WavesPublicAPI/wstdint.h" -#include "MiscUtils/MinMaxUtilities.h" - -// use this macro instead of std :: string to mark the that use of std :: string could not be replaced -// by WFixedString. -#define std_string_approved std::string - -#ifdef __POSIX__ -const char* const kStrNewLine = "\n"; -#endif -#ifdef PLATFORM_WINDOWS -const char* const kStrNewLine = "\r\n"; -#endif - -class DllExport WCFixedStringBase -{ -public: - typedef size_t pos_t; - typedef intptr_t spos_t; // signed position, defined to intptr_t because Windows does not have ssize_t - static const pos_t npos = UINTPTR_MAX; // Same as size_max - - WCFixedStringBase(char* const in_begin, const size_t in_MaxFixedStringLength) : - m_begin(in_begin), - m_MaxFixedStringLength(in_MaxFixedStringLength), - m_end(in_begin) - { - *m_end = '\0'; - } - - inline WCFixedStringBase& operator=(const WCFixedStringBase& in_fixedStrToAssign) - { - if (this != &in_fixedStrToAssign) - { - clear(); - operator<<(in_fixedStrToAssign); - } - - return *this; - } - - inline WCFixedStringBase& operator=(const char* in_CStrToAssign) - { - clear(); - operator<<(in_CStrToAssign); - - return *this; - } - - inline WCFixedStringBase& operator=(const char in_charToAssign) - { - clear(); - operator<<(in_charToAssign); - - return *this; - } - - char operator[](const pos_t in_index) const - { - if (in_index < m_MaxFixedStringLength) - return m_begin[in_index]; - else - return m_begin[m_MaxFixedStringLength]; // in_index was too big - } - - char& operator[](const pos_t in_index) - { - if (in_index < m_MaxFixedStringLength) - return m_begin[in_index]; - else - return m_begin[m_MaxFixedStringLength]; // in_index was too big - } - - inline size_t resize(const size_t in_newSize) - { - m_end = m_begin + WUMin<size_t>(in_newSize, m_MaxFixedStringLength); - *m_end = '\0'; - return size(); - } - - size_t max_size() - { - return m_MaxFixedStringLength; - } - - size_t capacity() - { - return m_MaxFixedStringLength; - } - - - inline char * peek() - { - return m_begin; - } - - inline const char * c_str() const - { - *m_end = '\0'; - return m_begin; - } - - inline void clear() - { - m_end = m_begin; - *m_end = '\0'; - } - - inline size_t size() const - { - return m_end - m_begin; - } - - inline char* begin() const - { - return m_begin; - } - - inline char* end() const - { - return m_end; - } - - inline size_t length() const - { - return size(); - } - - inline bool empty() const - { - return m_begin == m_end; - } - - inline void reverse(char* in_left, char* in_right) - { - char* left = in_left; - char* right = in_right; - while (left < right) - { - char temp = *--right; - *right = *left; - *left++ = temp; - } - } - - inline void reverse() - { - reverse(m_begin, m_end); - } - - inline void to_lower() - { - char* pToDo = m_begin; - - while (pToDo < m_end) - { - *pToDo = static_cast<char>(std::tolower(*pToDo)); - ++pToDo; - } - } - - inline void to_upper() - { - char* pToDo = m_begin; - - while (pToDo < m_end) - { - *pToDo = static_cast<char>(std::toupper(*pToDo)); - ++pToDo; - } - } - - // append a single char in_count times - inline void append(const char in_charToAppend, const size_t in_count) - { - size_t counter = 0; - while ((m_end < m_begin+m_MaxFixedStringLength) && counter++ < in_count) - *m_end++ = in_charToAppend; -#if kEnableDebug == 1 - if (counter < in_count) // if there wasn't enough room for some appended chars - { - m_begin[0] = '@'; // mark the string as overflowed - } -#endif - *m_end = '\0'; - } - - inline void append(const char* in_chars) - { - operator<<(in_chars); - } - - // append "iterator style" - inline void append(const char* in_chars_begin, const char* in_chars_end) - { - const char* curr_char = in_chars_begin; - while ((m_end < m_begin+m_MaxFixedStringLength) && curr_char < in_chars_end && *curr_char != '\0') - *m_end++ = *curr_char++; - -#if kEnableDebug == 1 - if (curr_char < in_chars_end) // if there wasn't enough room for some appended chars - { - m_begin[0] = '@'; // mark the string as overflowed - } -#endif - *m_end = '\0'; - } - - // append from a char* in_count chars, (no \0 is required to terminate the input string) - inline void append(const char* in_chars_begin, const size_t in_count) - { - append(in_chars_begin, in_chars_begin + in_count); - } - - // assign from a char* in_count chars, (no \0 is required to terminate the input string) - inline void assign(const char* in_chars_begin, const size_t in_count) - { - clear(); - append(in_chars_begin, in_chars_begin + in_count); - } - - // assign from a char* , (a \0 is required to terminate the input string) - inline void assign(const char* in_chars_ptr) - { - clear(); - operator<<(in_chars_ptr); - } - - // assign from a char* to a char* - inline void assign(const char* in_begin, const char* in_end) - { - assign(in_begin, size_t(in_end - in_begin)); - } - - inline void append_double_with_precision(const double in_double, const int in_precision) - { - const unsigned int tempBufSize = 32; - char buf[tempBufSize]; - - #ifdef PLATFORM_WINDOWS - _snprintf_s(buf, tempBufSize, tempBufSize - 1, "%.*f", in_precision, in_double); - #endif - #ifdef __APPLE__ - std::snprintf(buf, tempBufSize, "%.*f", in_precision, in_double); - #endif - #ifdef __linux__ - snprintf(buf, tempBufSize, "%.*f", in_precision, in_double); - #endif - - operator<<(buf); - } - - inline void append_uint(const uint64_t in_uint, const int_fast16_t in_base = 10) - { - uint_fast64_t num = in_uint; - - char* lasr_char_before = m_end; - - do { - char remainder(static_cast<char>(num % in_base)); - - if ( remainder < 10 ) - operator<<(char(remainder + '0')); - else - operator<<(char(remainder - 10 + 'A')); - - num /= in_base; - } while (num != 0); - - reverse(lasr_char_before, m_end); - } - - inline void append_hex_binary(const uint8_t* in_binary, const size_t in_size) - { - static const char hexdigits[] = "0123456789ABCDEF"; - -#if _BYTEORDER_BIG_ENDIAN==1 - for (size_t ibyte = 0; ibyte < in_size; ++ibyte) -#elif _BYTEORDER_BIG_ENDIAN==0 - for (size_t ibyte = in_size; ibyte > 0; --ibyte) -#endif - { - operator<<(hexdigits[in_binary[ibyte - 1] >> 4]); - operator<<(hexdigits[in_binary[ibyte - 1] & 0x0F]); - } - } - - inline WCFixedStringBase& operator<<(const char in_charToAppend) - { - if (m_end < m_begin+m_MaxFixedStringLength) - *m_end++ = in_charToAppend; -#if kEnableDebug == 1 - else // if there wasn't enough room for the appended char - { - m_begin[0] = '@'; // mark the string as overflowed - } -#endif - - *m_end = '\0'; - - return *this; - } - - inline WCFixedStringBase& operator<<(const char* const in_strToAppend) - { - if (0 != in_strToAppend) - { - const char* pSource = in_strToAppend; - - while (*pSource != '\0' && m_end < m_begin+m_MaxFixedStringLength) - *m_end++ = *pSource++; - -#if kEnableDebug == 1 - if (*pSource != '\0') // if there wasn't enough room for some appended chars - { - m_begin[0] = '@'; // mark the string as overflowed - } -#endif - *m_end = '\0'; - } - - return *this; - } - - WCFixedStringBase& operator<<(const uint64_t in_uint) - { - append_uint(in_uint, 10); - - return *this; - } - - - // Warning prevention: the operator<< function overload for unsigneds used to create lots - // of warnings once size_t usage was becoming widespread. So for each OS we define only - // those overloads that are actually needed. On Windows 32 bit we still get - // 'warning C4267: 'argument' : conversion from 'size_t' to 'const unsigned int', possible loss of data' - // warning which we do not know how to solve yet. The function DummyFunctionsForWarningTest - // in file WCFixedStringStream.cpp calls all combinations of operator<<(unsigned something) - // And should produce no warnings - (except the C4267 on windows). -#if defined(__APPLE__) // both 32 & 64 bit - WCFixedStringBase& operator<<(const size_t in_uint) { - return operator<<(static_cast<unsigned long long>(in_uint)); - } -#endif -// WCFixedStringBase& operator<<(const unsigned char in_uint) { -// return operator<<(static_cast<const unsigned long long>(in_uint)); -// } -// -// WCFixedStringBase& operator<<(const size_t in_uint) { -// return operator<<(static_cast<const uint64_t>(in_uint)); -// } -// -#if defined(__APPLE__) || defined(PLATFORM_WINDOWS) || defined(__linux__) // both 32 & 64 bit - WCFixedStringBase& operator<<(const unsigned int in_uint) { - return operator<<(static_cast<uint64_t>(in_uint)); - } -#endif -// -#if defined(PLATFORM_WINDOWS) || defined(__linux__) // both 32 & 64 bit - WCFixedStringBase& operator<<(const unsigned long in_uint) { - return operator<<(static_cast<uint64_t>(in_uint)); - } -#endif - - WCFixedStringBase& operator<<(const long long in_int) - { - if (in_int < 0) - operator<<('-'); -#ifdef PLATFORM_WINDOWS -// uintmax_t unsigned_in_num = _abs64(in_int); - uintmax_t unsigned_in_num = in_int < 0 ? static_cast<uintmax_t>(-in_int) : static_cast<uintmax_t>(in_int); -#else - uintmax_t unsigned_in_num = std::abs(in_int); -#endif - append_uint(unsigned_in_num, 10); - - return *this; - } - - WCFixedStringBase& operator<<(const short in_int) { - return operator<<(static_cast<int64_t>(in_int)); - } - - WCFixedStringBase& operator<<(const int in_int) { - return operator<<(static_cast<int64_t>(in_int)); - } - - WCFixedStringBase& operator<<(const long in_int) { - return operator<<(static_cast<int64_t>(in_int)); - } - - WCFixedStringBase& operator<<(const double in_doubleToWrite) - { - append_double_with_precision(in_doubleToWrite, 10); - - return *this; - } - - WCFixedStringBase& operator<<(const float in_floatToWrite) - { - append_double_with_precision(double(in_floatToWrite), 5); - - return *this; - } - - inline WCFixedStringBase& operator<<(const WCFixedStringBase& in_fixedStrToAppend) - { - operator<<(in_fixedStrToAppend.c_str()); - - return *this; - } - - WCFixedStringBase& operator<< (bool abool) - { - return abool ? operator<<("true") : operator<<("false"); - } - - template<typename T> WCFixedStringBase& operator+=(T in_type) - { - return operator<<(in_type); - } - - ptrdiff_t compare(const char* in_to_compare) const - { - ptrdiff_t retVal = 1; - - if (0 != in_to_compare) - { - retVal = strcmp(c_str(), in_to_compare); - } - - return retVal; - } - - - ptrdiff_t compare(const WCFixedStringBase& in_to_compare) const - { - ptrdiff_t retVal = compare(in_to_compare.c_str()); - return retVal; - } - - ptrdiff_t case_insensitive_compare(const char* in_to_compare) const - { - ptrdiff_t retVal = 1; - - if (0 != in_to_compare) - { -#ifdef PLATFORM_WINDOWS - retVal = _stricmp(c_str(), in_to_compare); -#endif -#if defined(__linux__) || defined(__APPLE__) - retVal = strcasecmp(c_str(), in_to_compare); -#endif - } - - return retVal; - } - - ptrdiff_t case_insensitive_compare(const WCFixedStringBase& in_to_compare) const - { - ptrdiff_t retVal = case_insensitive_compare(in_to_compare.c_str()); - return retVal; - } - - pos_t find(const char in_char_to_find) const - { - const char* pCurrChar = m_begin; - while (pCurrChar < m_end && *pCurrChar != in_char_to_find) - ++pCurrChar; - - return (pCurrChar < m_end) ? (pCurrChar - m_begin) : npos; - } - - pos_t rfind(const char in_char_to_find) const - { - pos_t retVal = npos; - const char* pCurrChar = m_end; - - while (pCurrChar != m_begin) - { - --pCurrChar; - if (*pCurrChar == in_char_to_find) - { - retVal = pCurrChar - m_begin; - break; - } - } - - return retVal; - } - - pos_t find(const char* in_chars_to_find, const pos_t in_start_from = 0) const - { - pos_t retVal = npos; - size_t to_find_size = ::strlen(in_chars_to_find); - - if (to_find_size > 0 && to_find_size <= size() && in_start_from < size()) - { - const char* pCurrChar = m_begin + in_start_from; - while ((m_end - pCurrChar) >= (ptrdiff_t)to_find_size) - { - int found = ::memcmp(pCurrChar, in_chars_to_find, to_find_size); - if (0 == found) - { - retVal = (pCurrChar - m_begin); - break; - } - - ++pCurrChar; - } - } - - return retVal; - } - - pos_t rfind(const char* in_chars_to_find) const - { - pos_t retVal = npos; - size_t to_find_size = ::strlen(in_chars_to_find); - - if (to_find_size > 0 && to_find_size <= size()) - { - const char* pCurrChar = m_end - to_find_size; - while (m_begin <= pCurrChar) - { - int found = ::memcmp(pCurrChar, in_chars_to_find, to_find_size); - if (0 == found) - { - retVal = (pCurrChar - m_begin); - break; - } - - --pCurrChar; - } - } - - return retVal; - } - - pos_t find_case_insensitive(const char* in_chars_to_find, const pos_t in_start_from = 0) const - { - pos_t retVal = npos; - size_t to_find_size = ::strlen(in_chars_to_find); - - if (to_find_size > 0 && to_find_size <= size() && in_start_from < size()) - { - const char* pCurrChar = m_begin + in_start_from; - while ((m_end - pCurrChar) >= (ptrdiff_t)to_find_size) - { - size_t i; - for (i = 0; i < to_find_size; ++i) - { - if (tolower(*(pCurrChar+i)) != tolower(in_chars_to_find[i])) - break; - } - - if (i == to_find_size) - { - retVal = (pCurrChar - m_begin); - break; - } - - ++pCurrChar; - } - } - - return retVal; - } - - pos_t find_first_of(const char* in_possibe_chars_to_find, const pos_t in_start_from = 0) const - { - pos_t retVal = npos; - - if (in_start_from < size()) - { - const char* pFoundChar = strpbrk(m_begin + in_start_from, in_possibe_chars_to_find); - if (0 != pFoundChar) - { - retVal = (pFoundChar - m_begin); - } - } - - return retVal; - } - - pos_t find_last_of(const char* in_possibe_chars_to_find, const pos_t in_start_from = 0) const - { - pos_t retVal = npos; - - pos_t curr_location = in_start_from; - - while (size() > curr_location) - { - pos_t found = find_first_of(in_possibe_chars_to_find, curr_location); - if (npos != found) - { - retVal = found; - curr_location = found + 1; - } - else - break; - } - - return retVal; - } - - pos_t find_first_not_of(const char* in_acceptable_chars, const pos_t in_start_from = 0) const - { - pos_t retVal = npos; - - if (in_start_from < size()) - { - retVal = (strspn(m_begin + in_start_from, in_acceptable_chars)); - if (size() <= retVal + in_start_from) - { - retVal = npos; - } - else - { - retVal += in_start_from; - } - } - - return retVal; - } - - pos_t find_last_not_of(const char* in_acceptable_chars, const pos_t in_start_from = 0) const - { - pos_t retVal = npos; - - pos_t curr_location = in_start_from; - - while (size() > curr_location) - { - pos_t found = find_first_not_of(in_acceptable_chars, curr_location); - if (npos != found) - { - retVal = found; - curr_location = found + 1; - } - else - break; - } - - return retVal; - } - - // return true if in_begin_text is found at position 0 OR if in_begin_text is empty - bool begins_with(const char* in_begin_text) const - { - pos_t where = find(in_begin_text, 0); - bool retVal = (0 == where) || (0 == ::strlen(in_begin_text)); - return retVal; - } - - // return true if in_end_text is found at th end OR if in_end_text is empty - bool ends_with(const char* in_end_text) const - { - pos_t where = rfind(in_end_text); - bool retVal = ((size() - strlen(in_end_text)) == where) || (0 == ::strlen(in_end_text)); - return retVal; - } - - size_t replace(const char in_look_for, const char in_replace_with) - { - size_t retVal = 0; - - char* pCurrChar = m_begin; - while (pCurrChar < m_end) - { - if (*pCurrChar == in_look_for) - { - *pCurrChar = in_replace_with; - ++retVal; - } - ++pCurrChar; - } - - return retVal; - } - - // erase in_size chars starting from in_location - void erase(const pos_t in_location, const size_t in_num_chars = 1) - { - if (size() > in_location && in_num_chars > 0) - { - size_t actual_num_chars = WUMin(in_num_chars, size_t(size() - in_location)); - char* pTo = m_begin + in_location; - char* pFrom = pTo + actual_num_chars; - - while (pFrom < m_end) - *pTo++ = *pFrom++; - - resize(size() - actual_num_chars); - } - } - - // erase any char that appear in in_forbidden_chars - void erase_all_of(const char* in_forbidden_chars) - { - pos_t curr_location = 0; - - while (npos != curr_location) - { - curr_location = find_first_of(in_forbidden_chars, curr_location); - if (npos != curr_location) - erase(curr_location); - } - } - - // erase any char that do not appear in in_allowed_chars - void erase_all_not_of(const char* in_allowed_chars) - { - pos_t curr_location = 0; - - while (npos != curr_location) - { - curr_location = find_first_not_of(in_allowed_chars, curr_location); - if (npos != curr_location) - erase(curr_location); - } - } - - //! Copy the content of fixed string to a buffer appending a '\0' at the end. - //! If in_buffer_size is more than the allocated buffer size memory over write will happen! - void copy_to_buffer(const size_t in_buffer_size, char* out_buffer) - { - if (in_buffer_size > 0 && 0 != out_buffer) - { - char* cur_buffer = out_buffer; - const char* cur_fixed = m_begin; - const char* end_buffer = out_buffer + (WUMin<size_t>(in_buffer_size - 1, m_end - m_begin)); - while (cur_buffer < end_buffer) - *cur_buffer++ = *cur_fixed++; - - *cur_buffer = '\0'; - } - } - -protected: - ~WCFixedStringBase() {} - - char* const m_begin; - const size_t m_MaxFixedStringLength; - char* m_end; - -private: - WCFixedStringBase(); - WCFixedStringBase(const WCFixedStringBase& in_fixedStrToCopy); -#if 0 - : - m_begin(in_fixedStrToCopy.m_begin), - m_MaxFixedStringLength(in_fixedStrToCopy.m_MaxFixedStringLength), - m_end(in_fixedStrToCopy.m_end) - { - } -#endif -}; - -template<size_t kMaxFixedStringLength> class DllExport WCFixedString : public WCFixedStringBase -{ -public: - - inline WCFixedString() : - WCFixedStringBase(m_fixedString, kMaxFixedStringLength) - { - } - - inline WCFixedString(const char* const in_strToAssign) : - WCFixedStringBase(m_fixedString, kMaxFixedStringLength) - { - operator<<(in_strToAssign); - } - - inline WCFixedString(const WCFixedStringBase& in_fixedStrToAssign) : - WCFixedStringBase(m_fixedString, kMaxFixedStringLength) - { - operator<<(in_fixedStrToAssign); - } - - inline WCFixedString(const WCFixedString& in_fixedStrToAssign) : - WCFixedStringBase(m_fixedString, kMaxFixedStringLength) - { - operator<<(in_fixedStrToAssign); - } - - inline WCFixedString(const char in_char, const size_t in_count = 1) : - WCFixedStringBase(m_fixedString, kMaxFixedStringLength) - { - append(in_char, in_count); - } - - inline WCFixedString(const char* in_chars, const size_t in_count) : - WCFixedStringBase(m_fixedString, kMaxFixedStringLength) - { - append(in_chars, in_count); - } - - // substr now supports negative in_length, which means "from the end" so - // "abcdefg".substr(1, -1) == "bcdef" - inline const WCFixedString substr(const pos_t in_pos = 0, const spos_t in_length = kMaxFixedStringLength) const - { - pos_t adjusted_pos = WUMin<size_t>(in_pos, size()); - size_t adjusted_length = 0; - if (in_length < 0) - { - adjusted_length = size_t(WUMax<spos_t>(0, spos_t(size() - adjusted_pos) + in_length)); - } - else - adjusted_length = WUMin<size_t>(in_length, size() - adjusted_pos); - - WCFixedString retVal; - retVal.append(m_begin + adjusted_pos, adjusted_length); - - return retVal; - } - -protected: - - char m_fixedString[kMaxFixedStringLength + 1]; // the "+ 1" is so that *m_end is always valid, and we can put the '\0' there}; -}; - -inline bool operator==(const WCFixedStringBase& in_left, const WCFixedStringBase& in_right) -{ - return 0 == in_left.compare(in_right.c_str()); -} - -inline bool operator==(const WCFixedStringBase& in_left, const char* const in_right) -{ - return 0 == in_left.compare(in_right); -} - -inline bool operator!=(const WCFixedStringBase& in_left, const WCFixedStringBase& in_right) -{ - return 0 != in_left.compare(in_right.c_str()); -} - -inline bool operator!=(const WCFixedStringBase& in_left, const char* const in_right) -{ - return 0 != in_left.compare(in_right); -} - -// class WCFixedStringBase -typedef WCFixedString<4> WCFixedString4; -typedef WCFixedString<15> WCFixedString15; -typedef WCFixedString<31> WCFixedString31; -typedef WCFixedString<63> WCFixedString63; -typedef WCFixedString<127> WCFixedString127; -typedef WCFixedString<255> WCFixedString255; -typedef WCFixedString<511> WCFixedString511; -typedef WCFixedString<1023> WCFixedString1023; -typedef WCFixedString<2047> WCFixedString2047; - -template<size_t kSizeOfFirst, size_t kSizeOfSecond> - class WCFixedStringPair : public std::pair< WCFixedString<kSizeOfFirst>, WCFixedString<kSizeOfSecond> > -{ -public: - WCFixedStringPair(const char* const in_firstStr = 0, const char* const in_secondStr = 0) : - std::pair< WCFixedString<kSizeOfFirst>, WCFixedString<kSizeOfSecond> >(in_firstStr, in_secondStr) {} - WCFixedStringPair(const WCFixedStringBase& in_firstStr, const char* const in_secondStr = 0) : - std::pair< WCFixedString<kSizeOfFirst>, WCFixedString<kSizeOfSecond> >(in_firstStr, in_secondStr) {} - WCFixedStringPair(const WCFixedStringBase& in_firstStr, const WCFixedStringBase& in_secondStr) : - std::pair< WCFixedString<kSizeOfFirst>, WCFixedString<kSizeOfSecond> >(in_firstStr, in_secondStr) {} -}; - -#endif // #ifndef __WCFixedString_h__ diff --git a/libs/backends/wavesaudio/wavesapi/MiscUtils/WUErrors.h b/libs/backends/wavesaudio/wavesapi/MiscUtils/WUErrors.h deleted file mode 100644 index 007d32f433..0000000000 --- a/libs/backends/wavesaudio/wavesapi/MiscUtils/WUErrors.h +++ /dev/null @@ -1,336 +0,0 @@ -/* - Copyright (C) 2014 Waves Audio Ltd. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. - -*/ - -#ifndef __WUErrors_h__ - #define __WUErrors_h__ - -/* Copy to include: -#include "WUErrors.h" -*/ - -#include "BasicTypes/WUTypes.h" - -// General errors -//const WTErr eNoErr = 0; // moved to #include "WavesPublicAPI/WTErr.h" -const WTErr eGenericErr = -1; -const WTErr eUserCanceled = -2; -const WTErr eUnknownErr = -3; -const WTErr eExceptionErr = -4; -const WTErr eEndianError = -5; -const WTErr eThreadSafeError = -6; -const WTErr eSomeThingNotInitailzed = -7; -const WTErr eWrongObjectState = -8; //!< object was not in an acceptable state -const WTErr eUninitalized = -9; -const WTErr eDeprecated = -10; -const WTErr eCommandLineParameter = -11; -const WTErr eNotANumber = -12; //!< expected a number but none was found -const WTErr eNotJustANumber = -13; //!< expected a number and found one but also other stuff (e.g. "123XYZ") -const WTErr eNegativeNumber = -14; //!< expected a positive number and found a negative -const WTErr eTimeOut = -15; //!< something timed out -const WTErr eCoreAudioFailed = -16; //!< Error in a core audio call -const WTErr eSomeThingInitailzedTwice = -17; -const WTErr eGenerateHelpInfo = -18; -const WTErr eOutOfRangeNumber = -19; -const WTErr eMacOnlyCode = -20; -const WTErr eWinOnlyCode = -21; -const WTErr eAppLaunchFailed = -22; //!< failed to launch an application -const WTErr eAppTerminateFailed = -23; //!< failed to terminate an application -const WTErr eAppReturnedError = -24; //!< Non zero exit code from application -const WTErr eNotImplemented = -25; //!< Function is not implmemented -const WTErr eNotEmpty = -26; //!< Something was expected to be empty but is not -const WTErr eAsioFailed = -27; - -// File Manager errors -const WTErr eFMNoSuchVolume = -1001; -const WTErr eFMFileNotFound = -1002; -const WTErr eFMFileAllreadyExists = -1003; -const WTErr eFMAllreadyOpenWithWritePerm = -1004; -const WTErr eFMEndOfFile = -1005; -const WTErr eFMPermissionErr = -1006; -const WTErr eFMBusyErr = -1007; -const WTErr eFMOpenFailed = -1008; -const WTErr eFMTranslateFileNameFailed = -1009; -const WTErr eFMWTPathRefCreationFailed = -1010; -const WTErr eFMReadFailed = -1011; -const WTErr eFMIllegalPathRef = -1012; -const WTErr eFMFileNotOpened = -1013; -const WTErr eFMFileSizeTooBig = -1014; -const WTErr eFMNoSuchDomain = -1015; -const WTErr eFMNoSuchSystemFolder = -1016; -const WTErr eFMWrongParameters = -1017; -const WTErr eFMIsNotAFolder = -1018; -const WTErr eFMIsAFolder = -1019; -const WTErr eFMIsNotAFile = -1020; -const WTErr eFMIsAFile = -1021; -const WTErr eFMDeleteFailed = -1022; -const WTErr eFMCreateFailed = -1023; -const WTErr eFMPathTooLong = -1024; -const WTErr eFMIOError = -1025; -const WTErr eFMIllegalOpenFileRef = -1026; -const WTErr eFMDiskFull = -1027; -const WTErr eFMFileNotEmpty = -1028; -const WTErr eFMEndOfFolder = -1029; -const WTErr eFMSamePath = -1030; -const WTErr eFMPathTooShort = -1031; -const WTErr eFMIncompletePath = -1032; -const WTErr eFMIsNoAFileSystemLink = -1033; -const WTErr eFMSymlinkBroken = -1034; -const WTErr eFMMoveFailed = -1035; -const WTErr eFMWriteFailed = -1036; -const WTErr eFMTooManyOpenFiles = -1037; -const WTErr eFMTooManySymlinks = -1038; - -// System errors -const WTErr eGenericSystemError = -2000; -const WTErr eSysNoEnvironmentVariable = -2001; -const WTErr eDLLLoadingFailed = -2002; -const WTErr eFuncPoinerNotFound = -2003; -const WTErr eDLLNotFound = -2004; -const WTErr eBundleNotLoaded = -2005; -const WTErr eBundleCreateFailed = -2006; -const WTErr eBundleExecutableNotFound = -2007; -const WTErr eNotABundle = -2008; -const WTErr eInvalideDate = -2009; -const WTErr eNoNetDevice = -2010; -const WTErr eCacheCreatedFromResource = -2011; -const WTErr eNotAValidApplication = -2012; - -// Resource Manager errors -const WTErr eRMResNotFound = -3000; -const WTErr eRMResExists = -3001; //!< a resource exist even though it's not expected to -const WTErr eRMContainerNotFound = -3002; //!< The container was not found in the list of containers -const WTErr eRMResRefNotFound = -3003; //!< The resRef was not found in container's resource list -const WTErr eRMInvalidResRef = -3004; -const WTErr eRMInvalidResContainer = -3005; -const WTErr eRMInvalidNativeResContainer = -3006; -const WTErr eRMAttachResContainerFailed = -3007; -const WTErr eRMInvalidResID = -3008; -const WTErr eRMResUpdateFailed = -3009; - -// Graphic Manager & GUI errors -const WTErr eGMIsNotInitailzed = -3500; -const WTErr eGMInvalidImage = -3501; -const WTErr eGMGenericErr = -3502; -const WTErr eGMNoCurrentContext = -3503; -const WTErr eGUISkinNotFound = -3504; -const WTErr eGMNoVertices = -3505; -const WTErr eGMNoColors = -3506; -const WTErr eGMNoTexture = -3507; -const WTErr eGMIncompatibleOGLVersion = -3508; -const WTErr eGMNoDeviceContext = -3509; -const WTErr eGMNoPixelFormat = -3510; -const WTErr eGMNoOGLContext = -3511; -const WTErr eGMNoOGLContextSharing = -3512; -const WTErr eGMUnsupportedImageFormat = -3513; -const WTErr eGMUninitializedContext = -3514; -const WTErr eControlOutOfRange = -3515; -const WTErr eGMUninitializedFont = -3516; -const WTErr eGMInvalidFontDrawMethod = -3517; -const WTErr eGMUnreleasedTextures = -3518; -const WTErr eGMWrongThread = -3519; -const WTErr eGMDontCommitDraw = -3520; -// Errors in the -5000 -> -5999 are defined in Waves-incs.h - -// Memory errors -const WTErr eMemNewFailed = -4001; //!< Something = new CSomething, returned null -const WTErr eMemNewTPtrFailed = -4002; //!< NewTPtr or NewTPtrClear failed -const WTErr eMemNullPointer = -4003; //!< a null pointer was encountered where it should not -const WTErr eMemObjNotInitialized = -4004; -const WTErr eMemBuffTooShort = -4005; //!< the buffer in question did not have enough space for the operation -const WTErr eInstanciationFailed = -4006; -const WTErr eMemAddressSpaceError = -4007; //!< memory falls outside the legal address space -const WTErr eMemBadPointer = -4008; -const WTErr eMemOutOfMemory = -4009; - -// XML Errors -const WTErr eXMLParserFailed = -6001; -const WTErr eXMLTreeNotValid = -6002; -const WTErr eXMLTreeEmpty = -6003; -const WTErr eXMLElementMissing = -6004; -const WTErr eXMLElementUninitalized = -6005; //!< element was default constructed it has not element name, etc.. -const WTErr eXMLElementIncomplete = -6006; //!< XML parser did not complete building the element -const WTErr eXMLAttribMissing = -6007; - -// Preset errors -const WTErr ePresetFileProblem = -7860; -const WTErr eInvalidFileFormatProblem = -7861; -const WTErr ePresetLockedProblem = -7862; -const WTErr ePresetInfoNotFound = -7863; -const WTErr eDuplicatePluginSpecificTag = -7959; -const WTErr ePluginSpecifcNotExisting = -7960; -const WTErr eBuffSizeToSmall = -7961; -const WTErr eCreatingPopupWhereAnItemExists = -7962; -const WTErr eDeletePluginSpecifcFailed = -7963; -const WTErr eFactoryPresetNumOutOfRange = -7964; -const WTErr eNoFactoryPresets = -7965; -const WTErr eLoadPresetToPlugin_vec_empty = -7966; -const WTErr eFactoryPresetNotFound = -7967; -const WTErr eCantCreateUserPrefFile = -7968; -const WTErr eDataFormatNotSupported = -7969; -const WTErr eCantLoadProcessFunction = -7970; -const WTErr eIllegalChunkIndex = -7971; -const WTErr eIllegalChunkID = -7972; -const WTErr eIllegalChunkVersion = -7973; - - -// Shell errors -const WTErr eNotAPluginFile = -8001; -const WTErr eFaildToLoadPluginDLL = -8002; -const WTErr eNoPluginManager = -8003; -const WTErr eGetAvailablePluginsFailed = -8004; -const WTErr eNoPluginsAvailable = -8005; -const WTErr ePluginSubComponentNotFound = -8006; -const WTErr ePluginOpenFailed = -8007; -const WTErr eSubComponentRejected = -8009; //!< user did not want this sub-component - probably through preferences -const WTErr eIncompatibleNumOfIOs = -8010; //!< e.g. surround sub-component in stereo only shell -const WTErr eStemProblem = -8011; //!< Some problem with stems -const WTErr eComponentTypeNotSupported = -8012; -const WTErr ePluginNotLoaded = -8013; -const WTErr ePluginInstanceNotCreate = -8014; -const WTErr ePluginAlgNotCreate = -8015; -const WTErr ePluginGUINotCreate = -8016; -const WTErr eMissmatchChannelCount = -8017; -const WTErr eIncompatibleVersion = -8018; -const WTErr eIncompatibleAffiliation = -8019; -const WTErr eNoSubComponentsFound = -8020; - -// Net-shell errors -const WTErr eNetShellInitFailed = -9001; - -// Protection errors -const WTErr eWLSLicenseFileNotFound = -10001; -const WTErr eWLSPluginNotAuthorized = -10002; -const WTErr eWLSNoLicenseForPlugin = -10003; -const WTErr eWLSInvalidLicenseFileName = -10004; -const WTErr eWLSInvalidLicenseFileContents = -10005; -const WTErr eWLSInvalidDeviceID = -10006; -const WTErr eWLSInvalidClientID = -10007; -const WTErr eWLSLicenseFileDownloadFailed = -10008; -const WTErr eWLSNoLicensesForClientOrDevice = -10009; -const WTErr eWLSNoLicensesForSomePlugins = -10010; - -// Communication errors -const WTErr eCommEndOfRecievedMessage = -11001; -const WTErr eCommSocketDisconnected = -11002; - -// Window Manager Errors -const WTErr eWMEventNotHandled = -12001; -const WTErr eWMDisposeViewFailed = -12002; - -// Plugin View Manager Errors -const WTErr ePVMPlatformNotSupported = -13001; -const WTErr ePVMAlreadyInitialized = -13002; -const WTErr ePVMIllegalParent = -13003; -const WTErr ePVMCannotCreateView = -13004; -const WTErr ePVMNothingSelected = -13005; -const WTErr ePVMDisabledItemChosen = -13006; -const WTErr ePVMMenuItemNotFound = -13007; -const WTErr ePVMMenuItemNotASubMenu = -13008; -const WTErr ePVMUnknownMenu = -13009; -const WTErr ePVMEmptyNativeViewRef = -13010; -const WTErr ePVMGenericError = -13011; -const WTErr ePVMFunctionNotImplemented = -13012; - -// Plugin View Manager - Menu Errors -const WTErr ePVMCannotCreateMenu = -13501; -const WTErr ePVMCannotSetMenuFont = -13502; -const WTErr ePVMCannotSetMenu = -13503; -const WTErr ePVMItemParentNotExists = -13504; - -// Plugin View Manager - TextField Errors -const WTErr ePVMCannotCreateTextField = -13553; -const WTErr ePVMCannotEmbedTextField = -13554; -const WTErr ePVMNoTextToValidate = -13555; -const WTErr ePVMTextTooLong = -13556; -const WTErr ePVMIllegalCharacter = -13557; - - -// Meter Manager Errors -const WTErr eMM_MeterGetMeterValueForParameterNotConnected = -14000 ; - - -//Surface Driver Manager Errors -const WTErr eSDM_SurfaceDriverAPIFailed = -14101; - -// IPC Errors -const WTErr eIPC_CreateNamedPipeFailed = -14200; -const WTErr eIPC_OpenPipeTimeout = -14201; -const WTErr eIPC_DeleteNamedPipeFailed = -14202; -const WTErr eIPC_SelectOnNamedPipeFailed = -14203; -const WTErr eIPC_ReadFromNamedPipeFailed = -14204; -const WTErr eIPC_ReadEndOfFileFromNamedPipe = -14205; -const WTErr eIPC_CloseNamedPipeFailed = -14206; -const WTErr eIPC_ParseArgsFailed = -14207; -const WTErr eIPC_OpenPipeFailed = -14208; -const WTErr eIPC_SendMsgFailed = -14209; -const WTErr eIPC_SendCommandInvalid = -14210; -const WTErr eIPC_QtTestMode = -14211; -const WTErr eIPC_ChangePermissionOnPipe = -14212; -const WTErr eIPC_ConnectionLost = -14213; - -const WTErr eIPC_InvalidRole = -14213; -const WTErr eIPC_CreateNamedPipeM2SFailed = -14214; -const WTErr eIPC_CreateNamedPipeS2MFailed = -14215; -const WTErr eIPC_ChangePermissionOnPipeM2S = -14216; -const WTErr eIPC_ChangePermissionOnPipeS2M = -14217; -const WTErr eIPC_OpenReadPipeFailed = -14218; -const WTErr eIPC_OpenReadPipeDIsableSigPipe = -14219; -const WTErr eIPC_OpenWritePipeFailed = -14220; -const WTErr eIPC_WritePipeFailed = -14221; -const WTErr eIPC_WritePipeNotOpen = -14222; -const WTErr eIPC_WriteBufferResizeFailed = -14223; -const WTErr eIPC_NotConnectedSendMsgFailed = -14224; -const WTErr eIPC_OpenWritePipeWorkerStoping = -14225; -const WTErr eIPC_SoketSendFailed = -14226; -const WTErr eIPC_PtonFailed = -14227; -const WTErr eIPC_SocketFailed = -14228; -const WTErr eIPC_BindFailed = -14229; -const WTErr eIPC_ListenFailed = -14230; -const WTErr eIPC_ConnectFailed = -14231; -const WTErr eIPC_WsaStartupFailed = -14232; -const WTErr eIPC_UdpSocketCreateFailed = -14233; -const WTErr eIPC_UdpSocketConnectFailed = -14234; -const WTErr eIPC_UdpSocketBinFailed = -14235; -const WTErr eIPC_SetBufferPreambleFailed = -14226; - -// Database errors -const WTErr eDB_BatchRollback = -15501; - -// inventory related errors -const WTErr eUnknown_Device = -16001; -const WTErr eInvNoDevice = -16002; - -// SG protocol service errors -const WTErr eSGProtocolService_Not_Running = -17001; -const WTErr eSGProtocolService_Version_MisMatch = -17002; - -// Error code related to Param -const WTErr eInvalidParam = -18001; - -#define WUIsError(theErrorCode) (eNoErr != (theErrorCode)) -#define WUNoError(theErrorCode) (eNoErr == (theErrorCode)) -#define WUThrowError(theErrorCode) {if(WUIsError(theErrorCode))throw (theErrorCode);} -#define WUThrowErrorIfNil(thePtr , theErrorCode) {if (0 == thePtr )throw (theErrorCode);} -#define WUThrowErrorIfFalse(theBool , theErrorCode) {if (!(theBool))throw (theErrorCode);} -#define WUThrowErrorCodeIfError(err,theErrorCode) {if(WUIsError(err))throw (theErrorCode);} - -// Get the error string that match the error code. -DllExport const char* WTErrName(WTErr wtErr); - -#endif //__WUErrors_h__: diff --git a/libs/backends/wavesaudio/wavesapi/MiscUtils/pthread_utils.h b/libs/backends/wavesaudio/wavesapi/MiscUtils/pthread_utils.h deleted file mode 100644 index b370845112..0000000000 --- a/libs/backends/wavesaudio/wavesapi/MiscUtils/pthread_utils.h +++ /dev/null @@ -1,38 +0,0 @@ -/* - Copyright (C) 2014 John Emmas - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. - -*/ - -#ifndef __waves_pthread_utils__ -#define __waves_pthread_utils__ - -/* Accommodate thread setting (and testing) for both - * 'libpthread' and 'libpthread_win32' (whose implementations - * of 'pthread_t' are subtlely different) - */ -#ifndef PTHREAD_MACROS_DEFINED -#define PTHREAD_MACROS_DEFINED -#ifdef PTW32_VERSION /* pthread_win32 */ -#define mark_pthread_inactive(threadID) threadID.p=0 -#define is_pthread_active(threadID) threadID.p!=0 -#else /* normal pthread */ -#define mark_pthread_inactive(threadID) threadID=0 -#define is_pthread_active(threadID) threadID!=0 -#endif /* PTW32_VERSION */ - -#endif /* PTHREAD_MACROS_DEFINED */ -#endif /* __waves_pthread_utils__ */ diff --git a/libs/backends/wavesaudio/wavesapi/MiscUtils/safe_delete.h b/libs/backends/wavesaudio/wavesapi/MiscUtils/safe_delete.h deleted file mode 100644 index 0537d1591b..0000000000 --- a/libs/backends/wavesaudio/wavesapi/MiscUtils/safe_delete.h +++ /dev/null @@ -1,37 +0,0 @@ -/* - Copyright (C) 2014 Waves Audio Ltd. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. - -*/ - -#ifndef __safe_delete_h__ - #define __safe_delete_h__ - - -/* Copy to include: -#include "safe_delete.h" -*/ - -#define safe_delete(__pObject__) {if((__pObject__) != 0) {delete (__pObject__); (__pObject__) = 0;}} - -#define safe_delete_array(__pArray__) {if((__pArray__) != 0) {delete [] (__pArray__); (__pArray__) = 0;}} - -template <class T> void safe_delete_from_iterator(T* pToDelete) -{ - safe_delete(pToDelete); -} - -#endif // __safe_delete_h__ diff --git a/libs/backends/wavesaudio/wavesapi/Threads/WCThreadSafe.cpp b/libs/backends/wavesaudio/wavesapi/Threads/WCThreadSafe.cpp deleted file mode 100644 index 1ee568af1e..0000000000 --- a/libs/backends/wavesaudio/wavesapi/Threads/WCThreadSafe.cpp +++ /dev/null @@ -1,826 +0,0 @@ -#include "Threads/WCThreadSafe.h" -#include <glib.h> - -#if XPLATFORMTHREADS_WINDOWS - #define _WIN32_WINNT 0x0500 // need at least Windows2000 (for TryEnterCriticalSection() and SignalObjectAndWait() - #include "IncludeWindows.h" - #include <process.h> -#endif // XPLATFORMTHREADS_WINDOWS - - -#if defined(__APPLE__) - #include <CoreServices/CoreServices.h> - #include <stdio.h> -#endif // __APPLE__ - -#if XPLATFORMTHREADS_POSIX - #include </usr/include/unistd.h> // avoid the framework version and use the /usr/include version - #include <pthread.h> - #include <sched.h> - #include <sys/time.h> - #include <errno.h> - #include <signal.h> -// We do this externs because <stdio.h> comes from MSL -extern "C" FILE *popen(const char *command, const char *type); -extern "C" int pclose(FILE *stream); -static int (*BSDfread)( void *, size_t, size_t, FILE * ) = 0; - -#include <string.h> - -#endif //XPLATFORMTHREADS_POSIX - -namespace wvNS { -static const unsigned int knMicrosecondsPerSecond = 1000*1000; -static const unsigned int knNanosecondsPerMicrosecond = 1000; -static const unsigned int knNanosecondsPerSecond = knMicrosecondsPerSecond*knNanosecondsPerMicrosecond; - -namespace wvThread -{ - - //-------------------------------------------------------------------------------- - static inline bool EnsureThreadingInitialized() - { - bool bRetval = true; - - return bRetval; - } - //-------------------------------------------------------------------------------- - - - - - //-------------------------------------------------------------------------------- - static uint32_t CalculateTicksPerMicrosecond(); - static uint32_t CalculateTicksPerMicrosecond() - { - uint32_t nTicksPerMicrosecond=0; -#if defined(_WIN32) - LARGE_INTEGER TSC; - ::QueryPerformanceFrequency(&TSC); - nTicksPerMicrosecond = uint32_t (TSC.QuadPart / knMicrosecondsPerSecond); -#elif defined(__linux__) && defined(__i386__) - static const timediff sktd_TSC_MeasurementPeriod = 40*1000; // delay for CalculateTicksPerMicrosecond() to measure the TSC frequency - uint64_t Tstart, Tend; - timeval tvtmp, tvstart, tvend; - - //--------------------- begin measurement code - // poll to align to a tick of gettimeofday - ::gettimeofday(&tvtmp,0); - do { - ::gettimeofday(&tvstart,0); - __asm__ __volatile__ (".byte 0x0f, 0x31" : "=A" (Tstart)); // RDTSC - } while (tvtmp.tv_usec!=tvstart.tv_usec); - // delay some - ::usleep(sktd_TSC_MeasurementPeriod); - // - ::gettimeofday(&tvtmp,0); - do { - ::gettimeofday(&tvend,0); - __asm__ __volatile__ (".byte 0x0f, 0x31" : "=A" (Tend)); // RDTSC - } while (tvtmp.tv_usec!=tvend.tv_usec); - //--------------------- end measurement code - - suseconds_t elapsed_usec = (tvend.tv_sec-tvstart.tv_sec)*knMicrosecondsPerSecond + (tvend.tv_usec-tvstart.tv_usec); - uint64_t elapsed_ticks = Tend-Tstart; - nTicksPerMicrosecond = uint32_t (elapsed_ticks/elapsed_usec); -#endif - return nTicksPerMicrosecond; - } - -#if defined(__APPLE__) //&& !defined(__MACH__) - - - bool FindNetInterfaceByIPAddress(const char *sIP, char *sInterface) // sIP and sInterface are both char[16] - { - FILE *fProcess , *pSubcall; - char sLine[256]="", *pToken, sCommand[150]; - bool res = false; - int iret; - - fProcess = popen("ifconfig -l inet", "r"); - if (fProcess) - { - memset(sInterface, '\0', 16); - iret = BSDfread(sLine, sizeof(char), sizeof(sLine), fProcess); - pToken = strtok(sLine, " "); - while (pToken) - { - sprintf(sCommand, "ifconfig %s | grep \"inet %s \"", pToken, sIP); - - pSubcall = popen(sCommand, "r"); - if (pSubcall) - { - char sSubline[100]=""; - if (BSDfread(sSubline, sizeof(char), sizeof(sSubline), pSubcall)) - { - // found - strcpy(sInterface, pToken); - res = true; - pclose(pSubcall); - break; - } - } - pclose(pSubcall); - pToken = strtok(NULL, " "); - } - - } - pclose(fProcess); - - return res; - } -#endif // MACOS - - timestamp now(void) - { - EnsureThreadingInitialized(); - static const uint32_t nTicksPerMicrosecond = CalculateTicksPerMicrosecond(); -#if defined(_WIN32) - if (nTicksPerMicrosecond) - { - LARGE_INTEGER TSC; - ::QueryPerformanceCounter(&TSC); - return timestamp(uint32_t(TSC.QuadPart/nTicksPerMicrosecond)); - } - else return timestamp(0); -#elif defined(__APPLE__) - if (nTicksPerMicrosecond) {} // prevent 'unused' warnings - UnsignedWide usecs; - ::Microseconds(&usecs); - return timestamp(usecs.lo); -#elif defined(__linux__) && defined(__i386__) && defined(__gnu_linux__) - uint64_t TSC; - __asm__ __volatile__ (".byte 0x0f, 0x31" : "=A" (TSC)); // RDTSC - return timestamp(TSC/nTicksPerMicrosecond); -#elif defined(__linux__) && defined(__PPC__) && defined(__gnu_linux__) - #warning need to implement maybe -#else - #error Dont know how to get microseconds timer ! -#endif // defined(_WIN32) - } - - - void sleep_milliseconds(unsigned int nMillisecs) - { - EnsureThreadingInitialized(); -#if XPLATFORMTHREADS_WINDOWS - ::Sleep(nMillisecs); -#elif XPLATFORMTHREADS_POSIX - ::usleep(nMillisecs*1000); -#else - #error Not implemented for your OS -#endif - } - - -#if XPLATFORMTHREADS_WINDOWS - inline DWORD win32_milliseconds(timediff td) { return (td+499)/1000; } -#endif - - void sleep(timediff _td) - { - if (_td>0) - { - EnsureThreadingInitialized(); -#if XPLATFORMTHREADS_WINDOWS - ::Sleep(win32_milliseconds(_td)); // This is the best we can do in windows -#elif XPLATFORMTHREADS_POSIX - ::usleep(_td); -#else - #error Not implemented for your OS -#endif - } - } - - -#if XPLATFORMTHREADS_WINDOWS - void yield() { ::Sleep(0); } -#elif XPLATFORMTHREADS_POSIX - void yield() { ::sched_yield(); } -#endif - - - - - class ThreadMutexInited::OSDependentMutex : public noncopyableobject - { -#if defined (XPLATFORMTHREADS_WINDOWS) - protected: - CRITICAL_SECTION m_critsec; - public: - - inline OSDependentMutex() { EnsureThreadingInitialized(); ::InitializeCriticalSection(&m_critsec); } - inline ~OSDependentMutex() { EnsureThreadingInitialized(); ::DeleteCriticalSection (&m_critsec); } - inline void obtain() { EnsureThreadingInitialized(); ::EnterCriticalSection (&m_critsec); } - inline void release() { EnsureThreadingInitialized(); ::LeaveCriticalSection (&m_critsec); } - inline bool tryobtain() { EnsureThreadingInitialized(); return TryEnterCriticalSection(&m_critsec)!=FALSE; } - -#elif defined (XPLATFORMTHREADS_POSIX) - protected: - pthread_mutex_t m_ptmutex; - public: - inline OSDependentMutex() - { - EnsureThreadingInitialized(); - pthread_mutexattr_t attr; - pthread_mutexattr_init(&attr); - pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE); - ::pthread_mutex_init (&m_ptmutex, &attr); - } - inline ~OSDependentMutex() { EnsureThreadingInitialized(); ::pthread_mutex_destroy(&m_ptmutex); } - inline void obtain() { EnsureThreadingInitialized(); ::pthread_mutex_lock (&m_ptmutex); } - inline void release() { EnsureThreadingInitialized(); ::pthread_mutex_unlock (&m_ptmutex); } - inline bool tryobtain() { EnsureThreadingInitialized(); return ::pthread_mutex_trylock(&m_ptmutex)!=EBUSY; } - -#endif - }; - - ThreadMutexInited::ThreadMutexInited() : - m_osdmutex(0) {} - - void ThreadMutexInited::init() - { - if (! is_init()) - { - m_osdmutex = new OSDependentMutex; - } - } - - void ThreadMutexInited::uninit() - { - if (is_init()) - { - delete m_osdmutex; - m_osdmutex = 0; - } - } - - ThreadMutexInited::~ThreadMutexInited() - { - uninit(); - } - - void ThreadMutexInited::obtain() - { - if (is_init()) - { - m_osdmutex->obtain(); - } - } - - void ThreadMutexInited::release() - { - if (is_init()) - { - m_osdmutex->release(); - } - } - - bool ThreadMutexInited::tryobtain() - { - bool retVal = true; - if (is_init()) - { - retVal = m_osdmutex->tryobtain(); - } - return retVal; - } - - class ThreadConditionSignal::OSDependentObject : public noncopyableobject - { -#if defined (XPLATFORMTHREADS_POSIX) - - protected: - pthread_cond_t m_ptcond; - pthread_mutex_t m_ptmutex; - public: - inline OSDependentObject() - { - EnsureThreadingInitialized(); - ::pthread_mutex_init(&m_ptmutex,0); - ::pthread_cond_init(&m_ptcond, 0); - } - inline ~OSDependentObject() { ::pthread_cond_destroy(&m_ptcond), ::pthread_mutex_destroy(&m_ptmutex); } - inline void signal_unicast() { ::pthread_cond_signal(&m_ptcond); } - inline void signal_broadcast() { ::pthread_cond_broadcast(&m_ptcond); } - inline void await_signal() { ::pthread_cond_wait(&m_ptcond, &m_ptmutex); } - inline bool await_signal(timediff td) - { - timespec tspecDeadline; - timeval tvNow; - ::gettimeofday(&tvNow,0); - tspecDeadline.tv_nsec = (tvNow.tv_usec + td%knMicrosecondsPerSecond)*knNanosecondsPerMicrosecond; - tspecDeadline.tv_sec = tvNow.tv_sec + td/knMicrosecondsPerSecond; - if (!(tspecDeadline.tv_nsec < suseconds_t(knNanosecondsPerSecond))) - ++tspecDeadline.tv_sec, tspecDeadline.tv_nsec-=knNanosecondsPerSecond; - return ::pthread_cond_timedwait(&m_ptcond, &m_ptmutex, &tspecDeadline) != ETIMEDOUT; - } - - void obtain_mutex() { ::pthread_mutex_lock(&m_ptmutex); } - bool tryobtain_mutex() { return ::pthread_mutex_trylock(&m_ptmutex)!=EBUSY; } - void release_mutex() { ::pthread_mutex_unlock(&m_ptmutex); } - - -#elif XPLATFORMTHREADS_WINDOWS - protected: - unsigned int m_nWaiterCount; - CRITICAL_SECTION m_csectWaiterCount; - - HANDLE m_hndSemaphoreSignaller; // We keep this semaphore always at 0 count (non-signalled). We use it to release a controlled number of threads. - HANDLE m_hndEventAllWaitersReleased; // auto-reset - HANDLE m_hndMutex; // the mutex associated with the condition - bool m_bBroadcastSignalled; // means that the last waiter must signal m_hndEventAllWaitersReleased when done waiting - - protected: - // - - - - - - - - - - - - - - - - - - - - - - - - - bool await_signal_win32(DWORD dwTimeout) - { - ::EnterCriticalSection(&m_csectWaiterCount); - ++m_nWaiterCount; - ::LeaveCriticalSection(&m_csectWaiterCount); - // This is the actual wait for the signal - bool bWaitSucceeded = ::SignalObjectAndWait(m_hndMutex, m_hndSemaphoreSignaller, dwTimeout, FALSE) == WAIT_OBJECT_0; - // - ::EnterCriticalSection(&m_csectWaiterCount); - bool bLastWaiter = --m_nWaiterCount==0 && m_bBroadcastSignalled; - ::LeaveCriticalSection(&m_csectWaiterCount); - - // re-acquire the mutex - if (bLastWaiter) - ::SignalObjectAndWait(m_hndEventAllWaitersReleased, m_hndMutex, INFINITE, FALSE); - else - ::WaitForSingleObject(m_hndMutex, INFINITE); - return bWaitSucceeded; - } - - - public: - - inline bool await_signal(timediff td) { return await_signal_win32((win32_milliseconds(td))); } - inline void await_signal() { await_signal_win32(INFINITE); } - - OSDependentObject() : m_nWaiterCount(0), m_bBroadcastSignalled(false) - { - EnsureThreadingInitialized(); - ::InitializeCriticalSection(&m_csectWaiterCount); - m_hndEventAllWaitersReleased = ::CreateEvent( - 0, // security - FALSE, // auto-reset - FALSE, // initial state non-sognalled - 0); // name - m_hndSemaphoreSignaller = ::CreateSemaphore( - 0, // security - 0, // initial count (and will stay this way) - 0x100000, // maximum count (should be as large as the maximum number of waiting threads) - 0); // name - m_hndMutex = ::CreateMutex( - 0, // security - FALSE, // not owned initially - 0); // name - //if (m_hndEventAllWaitersReleased==INVALID_HANDLE_VALUE || m_hndSemaphoreSignaller==INVALID_HANDLE_VALUE) - // throw something(); - } - - ~OSDependentObject() - { - ::CloseHandle(m_hndMutex); - ::CloseHandle(m_hndSemaphoreSignaller); - ::CloseHandle(m_hndEventAllWaitersReleased); - ::DeleteCriticalSection(&m_csectWaiterCount); - } - - inline void signal_unicast() - { - ::EnterCriticalSection(&m_csectWaiterCount); - unsigned int nWaiters = m_nWaiterCount; - ::LeaveCriticalSection(&m_csectWaiterCount); - if (nWaiters) - ::ReleaseSemaphore(m_hndSemaphoreSignaller, 1, 0); // release 1 semaphore credit to release one waiting thread - } - - void signal_broadcast() - { - ::EnterCriticalSection(&m_csectWaiterCount); - unsigned int nWaiters = m_nWaiterCount; - if (nWaiters) - { - m_bBroadcastSignalled = true; - ::ReleaseSemaphore(m_hndSemaphoreSignaller, nWaiters, 0); // release as many credits as there are waiting threads - ::LeaveCriticalSection(&m_csectWaiterCount); - ::WaitForSingleObject(m_hndEventAllWaitersReleased, INFINITE); - // at this point all threads are waiting on m_hndMutex, which would be released outside this function call - m_bBroadcastSignalled = false; - } - else - // no one is waiting - ::LeaveCriticalSection(&m_csectWaiterCount); - } - //------------------------------------------------ - inline void obtain_mutex() { ::WaitForSingleObject(m_hndMutex, INFINITE); } - inline bool tryobtain_mutex() { return ::WaitForSingleObject(m_hndMutex,0) == WAIT_OBJECT_0; } - inline void release_mutex() { ::ReleaseMutex(m_hndMutex); } - //------------------------------------------------ -#endif // OS switch - }; - - void ThreadConditionSignal::obtain_mutex() - { - m_osdepobj.obtain_mutex(); - } - bool ThreadConditionSignal::tryobtain_mutex() { return m_osdepobj.tryobtain_mutex(); } - void ThreadConditionSignal::release_mutex() - { - m_osdepobj.release_mutex(); - } - - void ThreadConditionSignal::await_condition() { m_osdepobj.await_signal(); } - bool ThreadConditionSignal::await_condition(timediff tdTimeout) { return m_osdepobj.await_signal(tdTimeout); } - void ThreadConditionSignal::signal_condition_single() { m_osdepobj.signal_unicast(); } - void ThreadConditionSignal::signal_condition_broadcast() { m_osdepobj.signal_broadcast(); } - - ThreadConditionSignal::ThreadConditionSignal() : m_osdepobj(*new OSDependentObject) {} - ThreadConditionSignal::~ThreadConditionSignal() { delete &m_osdepobj; } - - - - - - - - -#if XPLATFORMTHREADS_POSIX - namespace // anon - { - inline int max_FIFO_schedparam() - { - static const int max_priority = ::sched_get_priority_max(SCHED_FIFO); - return max_priority; - } - inline int schedparam_by_percentage(unsigned short percentage) - { - return (max_FIFO_schedparam()*10*percentage+500)/1000; - } - class POSIXThreadPriority - { - public: - int m_SchedPolicy; - int m_SchedPriority; - POSIXThreadPriority(ThreadPriority pri) - { - switch (pri) - { - case ThreadPriority::TimeCritical: m_SchedPolicy=SCHED_FIFO, m_SchedPriority=schedparam_by_percentage(80); break; - case ThreadPriority::AboveNormal: m_SchedPolicy=SCHED_FIFO, m_SchedPriority=schedparam_by_percentage(20); break; - case ThreadPriority::BelowNormal: // fall through to normal; nothing is below normal in POSIX - case ThreadPriority::Normal: // fall through to default - default: m_SchedPolicy=SCHED_OTHER, m_SchedPriority=0; break; - } - } - }; - - } // namespace anonymous -#endif // XPLATFORMTHREADS_POSIX - -#if XPLATFORMTHREADS_WINDOWS - namespace // anon - { - inline int WinThreadPriority(ThreadPriority pri) - { - switch (pri) - { - case ThreadPriority::BelowNormal: return THREAD_PRIORITY_BELOW_NORMAL; - case ThreadPriority::AboveNormal: return THREAD_PRIORITY_ABOVE_NORMAL; - case ThreadPriority::TimeCritical: return THREAD_PRIORITY_TIME_CRITICAL; - case ThreadPriority::Normal: // fall through to default - default: return THREAD_PRIORITY_NORMAL; - } - } - } // namespace anon -#endif // XPLATFORMTHREADS_WINDOWS - - - - void SetMyThreadPriority(ThreadPriority pri) - { -#if XPLATFORMTHREADS_WINDOWS - ::SetThreadPriority(::GetCurrentThread(), WinThreadPriority(pri)); -#endif // XPLATFORMTHREADS_WINDOWS -#if XPLATFORMTHREADS_POSIX - const POSIXThreadPriority posixpri(pri); - sched_param sparam; - ::memset(&sparam, 0, sizeof(sparam)); - sparam.sched_priority = posixpri.m_SchedPriority; -#if defined(__linux__) - ::sched_setscheduler(0, posixpri.m_SchedPolicy, &sparam); // linux uses this function instead of pthread_ -#else - pthread_setschedparam(pthread_self(), posixpri.m_SchedPolicy, &sparam); -#endif -#endif // XPLATFORMTHREADS_POSIX - } - - - struct ThreadWrapperData - { - ThreadFunction *func; - ThreadFunctionArgument arg; - }; - -#if XPLATFORMTHREADS_WINDOWS - static unsigned int __stdcall ThreadWrapper(void * arg) - { - register ThreadWrapperData *twd = reinterpret_cast<ThreadWrapperData*>(arg); - ThreadFunction *func=twd->func; - ThreadFunctionArgument farg=twd->arg; - delete twd; - return DWORD(func(farg)); - } -#elif XPLATFORMTHREADS_POSIX - static void * ThreadWrapper(void *arg) - { - register ThreadWrapperData *twd = reinterpret_cast<ThreadWrapperData*>(arg); - ThreadFunction *func=twd->func; - ThreadFunctionArgument farg=twd->arg; - delete twd; - return reinterpret_cast<void*>(func(farg)); - } - typedef void*(ThreadWrapperFunction)(void*); - - static ThreadWrapperFunction *ThunkedThreadWrapper = ThreadWrapper; - -#endif // OS switch - - - - - - class ThreadHandle::OSDependent - { - public: - static void StartThread(ThreadWrapperData *, ThreadHandle &, ThreadPriority); - static bool KillThread(ThreadHandle); - static bool JoinThread(ThreadHandle, ThreadFunctionReturnType*); - static void Close(ThreadHandle); -#if XPLATFORMTHREADS_WINDOWS - static inline uintptr_t from_oshandle(HANDLE h) { return reinterpret_cast<uintptr_t>(h); } - static inline HANDLE to_oshandle(uintptr_t h) { return reinterpret_cast<HANDLE>(h); } -#elif XPLATFORMTHREADS_POSIX - static inline uintptr_t from_oshandle(pthread_t pt) { return uintptr_t(pt); } - static inline pthread_t to_oshandle(uintptr_t h) { return pthread_t(h); } -#endif // OS switch - }; - -#if XPLATFORMTHREADS_WINDOWS - const ThreadHandle ThreadHandle::Invalid(OSDependent::from_oshandle(INVALID_HANDLE_VALUE)); -#elif XPLATFORMTHREADS_POSIX - const ThreadHandle ThreadHandle::Invalid(OSDependent::from_oshandle(0)); -#endif // OS switch - - inline void ThreadHandle::OSDependent::StartThread(ThreadWrapperData *ptwdata, ThreadHandle &th, ThreadPriority pri) - { -#if XPLATFORMTHREADS_WINDOWS - uintptr_t h = ::_beginthreadex( - 0, // no security attributes, not inheritable - 0, // default stack size - ThreadWrapper, // function to call - (void*)(ptwdata), // argument for function - 0, // creation flags - 0 // where to store thread ID - ); - - if (h) - { - th.m_oshandle = h; - if (pri!=ThreadPriority::Normal) - ::SetThreadPriority(to_oshandle(h), WinThreadPriority(pri)); - } - else - th=Invalid; -#elif XPLATFORMTHREADS_POSIX - pthread_attr_t my_thread_attr, *pmy_thread_attr = 0; - sched_param my_schedparam; - - if (pri!=ThreadPriority::Normal) - { - pmy_thread_attr = &my_thread_attr; - - const POSIXThreadPriority posixpriority(pri); - int result; - result = pthread_attr_init (pmy_thread_attr); - result = pthread_attr_setschedpolicy(pmy_thread_attr, posixpriority.m_SchedPolicy); - - memset(&my_schedparam, 0, sizeof(my_schedparam)); - my_schedparam.sched_priority = posixpriority.m_SchedPriority; - result = pthread_attr_setschedparam(pmy_thread_attr, &my_schedparam); - } - - pthread_t pt; - int anyerr = pthread_create( - &pt, // variable for thread handle - pmy_thread_attr, // default attributes - ThunkedThreadWrapper, - ptwdata - ); - - if (anyerr) - th=Invalid; - else - th.m_oshandle = OSDependent::from_oshandle(pt); -#endif - } - - inline bool ThreadHandle::OSDependent::KillThread(ThreadHandle h) - { -#if XPLATFORMTHREADS_WINDOWS - return ::TerminateThread(to_oshandle(h.m_oshandle), (DWORD)-1) != 0; -#elif XPLATFORMTHREADS_POSIX - return pthread_cancel(to_oshandle(h.m_oshandle)) == 0; -#endif - } - - bool ThreadHandle::OSDependent::JoinThread(ThreadHandle h, ThreadFunctionReturnType *pretval) - { -#if XPLATFORMTHREADS_WINDOWS - const bool kbReturnedOk = (WAIT_OBJECT_0 == ::WaitForSingleObject(OSDependent::to_oshandle(h.m_oshandle), INFINITE)); - if (kbReturnedOk && pretval) - { - DWORD dwExitCode; - ::GetExitCodeThread(to_oshandle(h.m_oshandle), &dwExitCode); - *pretval = (ThreadFunctionReturnType)(dwExitCode); - } - return kbReturnedOk; -#endif -#if XPLATFORMTHREADS_POSIX - ThreadFunctionReturnType ptrExitCode = 0; - int join_return_code = pthread_join(to_oshandle(h.m_oshandle), (void**)ptrExitCode); - const bool kbReturnedOk = (0 == join_return_code); - if (0 != pretval) - { - *pretval = ptrExitCode; - } - return kbReturnedOk; -#endif - } - -#if XPLATFORMTHREADS_WINDOWS - inline void ThreadHandle::OSDependent::Close(ThreadHandle h) - { - ::CloseHandle(OSDependent::to_oshandle(h.m_oshandle)); - } -#endif // XPLATFORMTHREADS_WINDOWS -#if XPLATFORMTHREADS_POSIX - inline void ThreadHandle::OSDependent::Close(ThreadHandle) {} -#endif // XPLATFORMTHREADS_POSIX - - //********************************************************************************************** - - class WCThreadRef::OSDependent - { - public: - static void GetCurrentThreadRef(WCThreadRef& tid); -#if XPLATFORMTHREADS_WINDOWS - static inline uintptr_t from_os(DWORD thread_id) { return (uintptr_t)(thread_id); } - static inline DWORD to_os(uintptr_t thread_id) { return (DWORD)(thread_id); } -#elif XPLATFORMTHREADS_POSIX - static inline uintptr_t from_os(pthread_t thread_id) { return (uintptr_t)(thread_id); } - static inline pthread_t to_os(uintptr_t thread_id) { return pthread_t(thread_id); } -#endif // OS switch - }; - - //********************************************************************************************** - inline void WCThreadRef::OSDependent::GetCurrentThreadRef(WCThreadRef& tid) - { -#if XPLATFORMTHREADS_WINDOWS - DWORD thread_id = ::GetCurrentThreadId(); - tid.m_osThreadRef = OSDependent::from_os(thread_id); - -#elif XPLATFORMTHREADS_POSIX - pthread_t thread_id = ::pthread_self(); - tid.m_osThreadRef = OSDependent::from_os(thread_id); - -#endif // OS switch - } - - //********************************************************************************************** - - ThreadHandle StartThread(ThreadFunction func, ThreadFunctionArgument arg, ThreadPriority thpri) - { - EnsureThreadingInitialized(); - ThreadWrapperData *ptwdata = new ThreadWrapperData; - ptwdata->func = func; - ptwdata->arg = arg; - ThreadHandle thToReturn; - ThreadHandle::OSDependent::StartThread(ptwdata, thToReturn, thpri); - return thToReturn; - } - - bool KillThread(ThreadHandle h) - { - EnsureThreadingInitialized(); - return ThreadHandle::OSDependent::KillThread(h); - } - - bool JoinThread(ThreadHandle h, ThreadFunctionReturnType *pretval) - { - EnsureThreadingInitialized(); - return ThreadHandle::OSDependent::JoinThread(h, pretval); - } - - void Close(ThreadHandle h) - { - EnsureThreadingInitialized(); - return ThreadHandle::OSDependent::Close(h); - } - - //******************************************************************************************* - - WCThreadRef GetCurrentThreadRef() - { - EnsureThreadingInitialized(); // Is it necessary? - WCThreadRef tRefToReturn; - WCThreadRef::OSDependent::GetCurrentThreadRef(tRefToReturn); - return tRefToReturn; - } - - //******************************************************************************************* - - bool IsThreadExists(const WCThreadRef& threadRef) - { -#if XPLATFORMTHREADS_WINDOWS - DWORD dwThreadId = WCThreadRef::OSDependent::to_os((uintptr_t)threadRef); - HANDLE handle = ::OpenThread(SYNCHRONIZE, // dwDesiredAccess - use of the thread handle in any of the wait functions - FALSE, // bInheritHandle - processes do not inherit this handle - dwThreadId); - - // Now we have the handle, check if the associated thread exists: - DWORD retVal = WaitForSingleObject(handle, 0); - if (retVal == WAIT_FAILED) - return false; // the thread does not exists - else - return true; // the thread exists - -#elif XPLATFORMTHREADS_POSIX - pthread_t pthreadRef = WCThreadRef::OSDependent::to_os((uintptr_t)threadRef); - int retVal = pthread_kill(pthreadRef, 0); // send a signal to the thread, but do nothing - if (retVal == ESRCH) - return false; // the thread does not exists - else - return true; // the thread exists - -#endif // OS switch - } - - //******************************************************************************************* - - bool operator==(const WCThreadRef& first, const WCThreadRef& second) - { - return (first.m_osThreadRef == second.m_osThreadRef); - } - - bool operator!=(const WCThreadRef& first, const WCThreadRef& second) - { - return (first.m_osThreadRef != second.m_osThreadRef); - } - - bool operator<(const WCThreadRef& first, const WCThreadRef& second) - { - return (first.m_osThreadRef < second.m_osThreadRef); - } - - bool operator>(const WCThreadRef& first, const WCThreadRef& second) - { - return (first.m_osThreadRef > second.m_osThreadRef); - } - - bool WCAtomicLock::obtain(const uint32_t in_num_trys) - { - bool retVal = false; - - uint32_t timeOut = in_num_trys; - while (true) - { - retVal = g_atomic_int_compare_and_exchange(&m_the_lock, gint(0), gint(1)); - if (retVal) - { - break; - } - else - { - if (--timeOut == 0) - { - break; - } - sleep_milliseconds(1000); - } - } - - return retVal; - } - - void WCAtomicLock::release() - { - m_the_lock = 0; - } - -} // namespace wvThread -} // namespace wvNS { - diff --git a/libs/backends/wavesaudio/wavesapi/Threads/WCThreadSafe.h b/libs/backends/wavesaudio/wavesapi/Threads/WCThreadSafe.h deleted file mode 100644 index eb8d91c696..0000000000 --- a/libs/backends/wavesaudio/wavesapi/Threads/WCThreadSafe.h +++ /dev/null @@ -1,411 +0,0 @@ -/* - Copyright (C) 2014 Waves Audio Ltd. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. - -*/ - -#ifndef __WCThreadSafe_h_ - #define __WCThreadSafe_h_ - -/* Copy to include -#include "Threads/WCThreadSafe.h" -*/ - -// -// * WCThreadSafe.h (used to be called XPlatformOSServices.hpp) -// * -// * Consistent C++ interfaces to common Operating System services. -// * -// * -// * -// * -// * Created 2004-December-13 by Udi Barzilai as XPlatformOSServices.hpp -// * Moved to WCThreadSafe.h by Shai 26/10/2005 -// * 26/10/2005: ThreadMutex now inhetites from ThreadMutexInited -// * namespace changed to wvThread - -#include "WavesPublicAPI/wstdint.h" -#include <string> - -#include "BasicTypes/WUDefines.h" - -#if defined(__linux__) || defined(__APPLE__) - #define XPLATFORMOSSERVICES_UNIX 1 -#endif - -#if defined(_WIN32) - #define XPLATFORMOSSERVICES_WIN32 1 -#endif - -#if XPLATFORMOSSERVICES_WIN32 - #define XPLATFORMTHREADS_WINDOWS 1 -#elif XPLATFORMOSSERVICES_UNIX - #define XPLATFORMTHREADS_POSIX 1 -#endif -namespace wvNS { -typedef uint32_t WTThreadSafetyType; -const WTThreadSafetyType kNoThreadSafetyNeeded = 0; -const WTThreadSafetyType kpthreadsmutexThreadSafety = 1; - - -namespace wvThread -{ - //#include "BasicTypes/WavesAPISetAligment.h" - //Packing affects the layout of classes, and commonly, if packing changes across header files, there can be problems. -#ifdef PLATFORM_WINDOWS -#pragma pack(push) -#pragma pack(8) -#endif - -#ifdef __APPLE__ -#ifdef __GNUC__ -#pragma pack(push, 8) -#endif -#endif - - //-------------------------------------------------------- - typedef int32_t timediff; // in microseconds - static const timediff ktdOneSecond = 1000*1000; - //-------------------------------------------------------- - class timestamp - { - protected: - typedef uint32_t tickcount; - tickcount m_nMicroseconds; // may wrap around - static const tickcount ms_knWraparoundThreshold = ~tickcount(0) ^ (~tickcount(0)>>1); // half the range - - public: - timestamp() : m_nMicroseconds(0) { /* uninitialized */ } - timestamp(const timestamp &_ts) : m_nMicroseconds(_ts.m_nMicroseconds) {} - timestamp &operator=(const timestamp &_rhs) { m_nMicroseconds = _rhs.m_nMicroseconds; return *this; } - explicit timestamp(tickcount _i) : m_nMicroseconds(_i) {} - uint32_t ticks() const { return m_nMicroseconds; } - timediff operator-(timestamp _rhs) const { return timediff(m_nMicroseconds-_rhs.m_nMicroseconds); } - timestamp & operator+=(timediff _t) { m_nMicroseconds+=_t; return *this; } - timestamp & operator-=(timediff _t) { m_nMicroseconds-=_t; return *this; } - timestamp operator+(timediff _t) const { return timestamp(m_nMicroseconds+_t); } - timestamp operator-(timediff _t) const { return timestamp(m_nMicroseconds-_t); } - bool operator==(timestamp _rhs) const { return m_nMicroseconds==_rhs.m_nMicroseconds; } - bool operator!=(timestamp _rhs) const { return m_nMicroseconds!=_rhs.m_nMicroseconds; } - bool operator< (timestamp _rhs) const { return m_nMicroseconds-_rhs.m_nMicroseconds >= ms_knWraparoundThreshold; } - static timestamp null() { return timestamp(0); } - bool is_null() const { return m_nMicroseconds==0; } - }; - //-------------------------------------------------------- -#ifdef __APPLE__ - bool FindNetInterfaceByIPAddress(const char *sIP, char *sInterface); -#endif // MACOS - //-------------------------------------------------------- - timestamp now(); - //-------------------------------------------------------- - DllExport void sleep(timediff); - DllExport void sleep_milliseconds(unsigned int nMillisecs); - //-------------------------------------------------------- - void yield(); - //-------------------------------------------------------- - - - - typedef uintptr_t os_dependent_handle_type; - - //-------------------------------------------------------- - typedef int ThreadFunctionReturnType; - typedef void * ThreadFunctionArgument; - //-------------------------------------------------------- - typedef ThreadFunctionReturnType (ThreadFunction)(ThreadFunctionArgument); - //-------------------------------------------------------- - class ThreadHandle - { - public: - class OSDependent; - protected: - uintptr_t m_oshandle; // hopefully this is good enough for all systems - public: - static const ThreadHandle Invalid; - protected: - ThreadHandle(uintptr_t n) : m_oshandle(n) {} - public: - ThreadHandle() : m_oshandle(Invalid.m_oshandle) {} - bool is_invalid() const { return !m_oshandle || m_oshandle==Invalid.m_oshandle; } - }; - //-------------------------------------------------------- - class ThreadPriority - { - public: enum value { BelowNormal=1, Normal=2, AboveNormal=3, TimeCritical=4 }; - protected: value m_value; - public: ThreadPriority(value v) : m_value(v) {} - public: operator value() const { return m_value; } - }; - //-------------------------------------------------------- - void SetMyThreadPriority(ThreadPriority); - //-------------------------------------------------------- - ThreadHandle StartThread(ThreadFunction, ThreadFunctionArgument, ThreadPriority=ThreadPriority::Normal); - bool JoinThread(ThreadHandle, ThreadFunctionReturnType * = 0); - bool KillThread(ThreadHandle); // use only for abnormal termination - void Close(ThreadHandle); // should be called once for every handle obtained from StartThread. - //-------------------------------------------------------- - - - - - //-------------------------------------------------------- - class DllExport noncopyableobject - { - protected: - noncopyableobject() {} - private: - noncopyableobject(const noncopyableobject &); - noncopyableobject & operator=(const noncopyableobject &); - }; - //-------------------------------------------------------- - - - //-------------------------------------------------------- - // Thread Mutex class that needs to be explicitly initialized - class DllExport ThreadMutexInited : public noncopyableobject - { - protected: - class OSDependentMutex; - OSDependentMutex* m_osdmutex; - - public: - ThreadMutexInited(); - ~ThreadMutexInited(); - - void init(); - void uninit(); - inline bool is_init() { return 0 != m_osdmutex; } - void obtain(); - bool tryobtain(); - void release(); - - private: - ThreadMutexInited(const ThreadMutexInited&); // cannot be copied - ThreadMutexInited& operator=(const ThreadMutexInited&); // cannot be copied - - public: - class lock : public noncopyableobject - { - protected: - ThreadMutexInited &m_mutex; - public: - inline lock(ThreadMutexInited &mtx) : m_mutex(mtx) { m_mutex.obtain(); } - inline ~lock() { m_mutex.release(); } - }; - class trylock : public noncopyableobject - { - protected: - ThreadMutexInited &m_mutex; - bool m_bObtained; - public: - inline trylock(ThreadMutexInited &mtx) : m_mutex(mtx), m_bObtained(false) { m_bObtained = m_mutex.tryobtain(); } - inline ~trylock() { if (m_bObtained) m_mutex.release(); } - inline operator bool() const { return m_bObtained; } - }; - }; - //-------------------------------------------------------- - - // Thread Mutex class that is automatically initialized - class ThreadMutex : public ThreadMutexInited - { - public: - ThreadMutex() {init();} - }; - - //-------------------------------------------------------- - class DllExport ThreadConditionSignal : public noncopyableobject - { - protected: - class OSDependentObject; - OSDependentObject &m_osdepobj; - - protected: - void obtain_mutex(); - bool tryobtain_mutex(); - void release_mutex(); - - public: - class lock : public noncopyableobject - { - protected: - ThreadConditionSignal &m_tcs; - public: - lock(ThreadConditionSignal &tcs) : m_tcs(tcs) { m_tcs.obtain_mutex(); } - ~lock() { m_tcs.release_mutex(); } - }; - class trylock : public noncopyableobject - { - protected: - ThreadConditionSignal &m_tcs; - bool m_bObtained; - public: - trylock(ThreadConditionSignal &tcs) : m_tcs(tcs), m_bObtained(false) { m_bObtained = m_tcs.tryobtain_mutex(); } - ~trylock() { if (m_bObtained) m_tcs.release_mutex(); } - operator bool() const { return m_bObtained; } - }; - - public: - ThreadConditionSignal(); - ~ThreadConditionSignal(); - - // IMPORTANT: All of the functions below MUST be called ONLY while holding a lock for this object !!! - void await_condition(); - bool await_condition(timediff tdTimeout); - void signal_condition_single(); - void signal_condition_broadcast(); - }; - //-------------------------------------------------------- - - - - - - //-------------------------------------------------------- - // A doorbell is a simple communication mechanism that allows - // one thread two wake another when there is some work to be done. - // The signal is 'clear on read'. This class is not intended for - // multi-way communication (i.e. more than two threads). -//#define XPLATFORMTHREADS_DOORBELL_INLINE_USING_COND_VAR (!XPLATFORMTHREADS_WINDOWS && !XPLATFORMOSSERVICES_MACOS) -#ifdef XPLATFORMTHREADS_DOORBELL_INLINE_USING_COND_VAR -#undef XPLATFORMTHREADS_DOORBELL_INLINE_USING_COND_VAR -#endif -#define XPLATFORMTHREADS_DOORBELL_INLINE_USING_COND_VAR 1 -#if XPLATFORMTHREADS_DOORBELL_INLINE_USING_COND_VAR - class doorbell_type - { - protected: - ThreadConditionSignal m_signal; - bool m_rang; - protected: - template<bool wait_forever> bool wait_for_ring_internal(timediff timeout) - {// mutex - ThreadConditionSignal::lock guard(m_signal); - if (!m_rang) - { - if (wait_forever) - { - m_signal.await_condition(); - } - else - { - m_signal.await_condition(timeout); - } - } - const bool rang = m_rang; - m_rang = false; - return rang; - }// mutex - - public: - doorbell_type() : m_rang(false) {} - inline ~doorbell_type() {} - inline void ring() - {// mutex - ThreadConditionSignal::lock guard(m_signal); - m_rang = true; - m_signal.signal_condition_single(); - }// mutex - inline bool wait_for_ring() { return wait_for_ring_internal<true>(0); } - inline bool wait_for_ring(timediff timeout) { return wait_for_ring_internal<false>(timeout); } - }; -#else - class doorbell_type : public noncopyableobject - { - protected: - os_dependent_handle_type m_os_dependent_handle; - protected: - template<bool wait_forever> bool wait_for_ring_internal(timediff); - public: - doorbell_type(); - ~doorbell_type(); - void ring(); - bool wait_for_ring(); - bool wait_for_ring(timediff timeout); - }; -#endif // XPLATFORMTHREADS_DOORBELL_INLINE_USING_COND_VAR - //-------------------------------------------------------- - - //--------------------------------------------------------------- - class DllExport WCThreadRef // Class which holds the threadRef, DWORD in Windows and pthread_t in POSIX (Mac, Unix) - { - public: - class OSDependent; // the class which contains the OS Dependent implementation - - WCThreadRef() : m_osThreadRef(0) {} - bool is_invalid() const { return m_osThreadRef == 0;} - - operator uintptr_t() const {return m_osThreadRef;} - - protected: - uintptr_t m_osThreadRef; - WCThreadRef(uintptr_t n) : m_osThreadRef(n) {} - - friend DllExport bool operator==(const WCThreadRef& first, const WCThreadRef& second); - friend DllExport bool operator!=(const WCThreadRef& first, const WCThreadRef& second); - friend DllExport bool operator<(const WCThreadRef& first, const WCThreadRef& second); - friend DllExport bool operator>(const WCThreadRef& first, const WCThreadRef& second); - }; - - DllExport WCThreadRef GetCurrentThreadRef(); // getting the current thread reference - cross-platform implemented - bool IsThreadExists(const WCThreadRef& threadRef); // correct to the very snapshot of time of execution - - //--------------------------------------------------------------- - - class DllExport WCAtomicLock - { - public: - WCAtomicLock() : m_the_lock(0) {} - bool obtain(const uint32_t in_num_trys = 1); - void release(); - private: - int32_t m_the_lock; - }; - - //#include "BasicTypes/WavesAPIResetAligment.h" -#ifdef PLATFORM_WINDOWS -#pragma pack(pop) -#endif - -#ifdef __APPLE__ -#ifdef __GNUC__ -#pragma pack(pop) -#endif -#endif - -class WCStThreadMutexLocker -{ -public: - WCStThreadMutexLocker(wvNS::wvThread::ThreadMutexInited& in_mutex) : - m_mutex(in_mutex) - { - m_mutex.obtain(); - } - - ~WCStThreadMutexLocker() - { - m_mutex.release(); - } -protected: - wvNS::wvThread::ThreadMutexInited& m_mutex; - WCStThreadMutexLocker(const WCStThreadMutexLocker&); - WCStThreadMutexLocker& operator=(const WCStThreadMutexLocker&); -}; - -} // namespace wvThread - - -} //namespace wvNS { -#endif // #ifndef __WCThreadSafe_h_ diff --git a/libs/backends/wavesaudio/wavesapi/WavesPublicAPI/1.0/WavesPublicAPI_Defines.h b/libs/backends/wavesaudio/wavesapi/WavesPublicAPI/1.0/WavesPublicAPI_Defines.h deleted file mode 100644 index 24bfb10573..0000000000 --- a/libs/backends/wavesaudio/wavesapi/WavesPublicAPI/1.0/WavesPublicAPI_Defines.h +++ /dev/null @@ -1,60 +0,0 @@ -/* - Copyright (C) 2014 Waves Audio Ltd. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. - -*/ - -#ifndef __WavesPublicAPI_Defines_h__ - #define __WavesPublicAPI_Defines_h__ - -/*Copy to include -#include "WavesPublicAPI_Defines.h" -*/ - -#ifdef __APPLE__ - - #ifdef __GNUC__ - #define WPAPI_DllExport __attribute__ ((visibility("default"))) - #define __WPAPI_CDECL - #define __WPAPI_STDCALL - - #else - - #define WPAPI_DllExport __declspec(export) - #define __WPAPI_CDECL - #define __WPAPI_STDCALL - - #endif - -#endif - - -#ifdef PLATFORM_WINDOWS - #define WPAPI_DllExport __declspec(dllexport) - #define __WPAPI_CDECL __cdecl - #define __WPAPI_STDCALL __stdcall -#endif - -#ifdef __linux__ - - #define WPAPI_DllExport __attribute__ ((visibility("default"))) - - #define __WPAPI_CDECL - #define __WPAPI_STDCALL - -#endif - -#endif //__WavesPublicAPI_Defines_h__ diff --git a/libs/backends/wavesaudio/wavesapi/WavesPublicAPI/WTErr.h b/libs/backends/wavesaudio/wavesapi/WavesPublicAPI/WTErr.h deleted file mode 100644 index 451369db6f..0000000000 --- a/libs/backends/wavesaudio/wavesapi/WavesPublicAPI/WTErr.h +++ /dev/null @@ -1,46 +0,0 @@ -/* - Copyright (C) 2014 Waves Audio Ltd. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. - -*/ - -/////////////////////////////////////////////////////////////////////////////////////////////////////// -// \file WTErr.h, defines basic error type and "No Error" code -// All users may use their own error codes with this type, as long as eNoErr remains defined here -/////////////////////////////////////////////////////////////////////////////////////////////////////// -#ifndef __WTErr_h__ -#define __WTErr_h__ - -/* Copy to include: -#include "WavesPublicAPI/WTErr.h" -*/ - -#ifdef __cplusplus -extern "C" { -#endif - -#include "WavesPublicAPI/wstdint.h" - -typedef int32_t WTErr; // Waves Type Error -const WTErr eNoErr = 0; - - -#ifdef __cplusplus -} //extern "C" { -#endif - -#endif // __WTErr_h__ - diff --git a/libs/backends/wavesaudio/wavesapi/WavesPublicAPI/wstdint.h b/libs/backends/wavesaudio/wavesapi/WavesPublicAPI/wstdint.h deleted file mode 100644 index 46869c40ae..0000000000 --- a/libs/backends/wavesaudio/wavesapi/WavesPublicAPI/wstdint.h +++ /dev/null @@ -1,367 +0,0 @@ -/* - Copyright (C) 2014 Waves Audio Ltd. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. - -*/ - -#ifndef __stdint_h__ -#define __stdint_h__ - -/* Copy to include -#include "wstdint.h" -*/ - - -#ifdef __APPLE__ - #include <stddef.h> - #include </usr/include/stdint.h> // Mac has this file in /usr/includez -#endif -#ifdef __linux__ - #if ! defined(__STDC_LIMIT_MACROS) - #define __STDC_LIMIT_MACROS - #endif - - #include <stddef.h> - #include </usr/include/stdint.h> -#endif - -#if (defined (PLATFORM_WINDOWS) || defined(WIN32) || defined(WIN64)) -#if (_MSC_VER > 1600) || defined(__MINGW64__) || defined(__MINGW32__) - // Taken from MSDN official page: - // In Visual Studio 2010 _MSC_VER is defined as 1600, In Visual Studio 2012 _MSC_VER is defined as 1700. - #include <stdint.h> -#else -#ifndef _STDINT_H - #define _STDINT_H // this will prevent Altura's CGBase.h from defining int32_t -#endif -/* - * ISO C 99 <stdint.h> for platforms that lack it. - * <http://www.opengroup.org/onlinepubs/007904975/basedefs/stdint.h.html> - */ - -/* Get wchar_t, WCHAR_MIN, WCHAR_MAX. */ -#include <stddef.h> -/* Get CHAR_BIT, LONG_MIN, LONG_MAX, ULONG_MAX. */ -#include <limits.h> - -/* Get those types that are already defined in other system include files. */ -#if defined(__FreeBSD__) -# include <sys/inttypes.h> -#endif - -#if defined(__sun) && HAVE_SYS_INTTYPES_H -# include <sys/inttypes.h> - /* Solaris 7 <sys/inttypes.h> has the types except the *_fast*_t types, and - the macros except for *_FAST*_*, INTPTR_MIN, PTRDIFF_MIN, PTRDIFF_MAX. - But note that <sys/int_types.h> contains only the type definitions! */ -# define HAVE_SYSTEM_INTTYPES -#endif -#if (defined(__hpux) || defined(_AIX)) && HAVE_INTTYPES_H -# include <inttypes.h> - /* HP-UX 10 <inttypes.h> has nearly everything, except UINT_LEAST8_MAX, - UINT_FAST8_MAX, PTRDIFF_MIN, PTRDIFF_MAX. */ - /* AIX 4 <inttypes.h> has nearly everything, except INTPTR_MIN, INTPTR_MAX, - UINTPTR_MAX, PTRDIFF_MIN, PTRDIFF_MAX. */ -# define HAVE_SYSTEM_INTTYPES -#endif -#if !(defined(UNIX_CYGWIN32) && defined(__BIT_TYPES_DEFINED__)) -# define NEED_SIGNED_INT_TYPES -#endif - -#if !defined(HAVE_SYSTEM_INTTYPES) - -/* 7.18.1.1. Exact-width integer types */ -#if !defined(__FreeBSD__) - -#if defined(_MSC_VER) -#ifndef __int8_t_defined -#define __int8_t_defined -typedef __int8 int8_t; -typedef unsigned __int8 uint8_t; -typedef __int16 int16_t; -typedef unsigned __int16 uint16_t; -typedef __int32 int32_t; -typedef unsigned __int32 uint32_t; -typedef __int64 int64_t; -typedef unsigned __int64 uint64_t; -#endif - -#else // _MSC_VER - -#ifdef NEED_SIGNED_INT_TYPES -typedef signed char int8_t; -#endif -typedef unsigned char uint8_t; - -#ifdef NEED_SIGNED_INT_TYPES -typedef short int16_t; -#endif -typedef unsigned short uint16_t; - -#ifdef NEED_SIGNED_INT_TYPES -typedef int int32_t; -#endif -typedef unsigned int uint32_t; - -#if 0 -#ifdef NEED_SIGNED_INT_TYPES -typedef long int64_t; -#endif -typedef unsigned long uint64_t; -#elif 0 -#ifdef NEED_SIGNED_INT_TYPES -typedef long long int64_t; -#endif -typedef unsigned long long uint64_t; -#endif - -#endif // _MSC_VER - -#endif /* !FreeBSD */ - -/* 7.18.1.2. Minimum-width integer types */ - -typedef int8_t int_least8_t; -typedef uint8_t uint_least8_t; -typedef int16_t int_least16_t; -typedef uint16_t uint_least16_t; -#if !defined(kAlturaAlreadyDefinesInt32) -typedef int32_t int_least32_t; -#endif -typedef uint32_t uint_least32_t; -typedef int64_t int_least64_t; -typedef uint64_t uint_least64_t; - - -/* 7.18.1.3. Fastest minimum-width integer types */ - -#ifndef _STDINT_H -typedef int32_t int_fast8_t; -typedef uint32_t uint_fast8_t; -typedef int32_t int_fast16_t; -typedef uint32_t uint_fast16_t; -typedef int32_t int_fast32_t; -typedef uint32_t uint_fast32_t; -typedef int64_t int_fast64_t; -typedef uint64_t uint_fast64_t; -#endif - - -/* 7.18.1.4. Integer types capable of holding object pointers */ - -#if !defined(__FreeBSD__) - -/* On some platforms (like IRIX6 MIPS with -n32) sizeof(void*) < sizeof(long), - but this doesn't matter here. */ -#if !defined(_INTPTR_T_DEFINED) -typedef long intptr_t; -#define _INTPTR_T_DEFINED -#endif -#if !defined(_UINTPTR_T_DEFINED) -typedef unsigned long uintptr_t; -#define _UINTPTR_T_DEFINED -#endif - -#endif /* !FreeBSD */ - -/* 7.18.1.5. Greatest-width integer types */ - - -typedef int64_t intmax_t; -typedef uint64_t uintmax_t; -#if 0 || 0 -typedef int32_t intmax_t; -typedef uint32_t uintmax_t; -#endif - -/* 7.18.2. Limits of specified-width integer types */ - -//#if !defined(__cplusplus) || defined(__STDC_LIMIT_MACROS) - -/* 7.18.2.1. Limits of exact-width integer types */ - -#ifndef _STDINT_H - -#define INT8_MIN -128 -#define INT8_MAX 127 -#define UINT8_MAX 255U -#define INT16_MIN -32768 -#define INT16_MAX 32767 -#define UINT16_MAX 65535U -#define INT32_MIN (~INT32_MAX) -#define INT32_MAX 2147483647 -#define UINT32_MAX 4294967295U -#if 0 -#define INT64_MIN (~INT64_MIN) -#define INT64_MAX 9223372036854775807L -#define UINT64_MAX 18446744073709551615UL -#elif 0 -#define INT64_MIN (~INT64_MIN) -#define INT64_MAX 9223372036854775807LL -#define UINT64_MAX 18446744073709551615ULL -#endif - -/* 7.18.2.2. Limits of minimum-width integer types */ - -#define INT_LEAST8_MIN INT8_MIN -#define INT_LEAST8_MAX INT8_MAX -#define UINT_LEAST8_MAX UINT8_MAX -#define INT_LEAST16_MIN INT16_MIN -#define INT_LEAST16_MAX INT16_MAX -#define UINT_LEAST16_MAX UINT16_MAX -#define INT_LEAST32_MIN INT32_MIN -#define INT_LEAST32_MAX INT32_MAX -#define UINT_LEAST32_MAX UINT32_MAX -#if 0 || 0 -#define INT_LEAST64_MIN INT64_MIN -#define INT_LEAST64_MAX INT64_MAX -#define UINT_LEAST64_MAX UINT64_MAX -#endif - -/* 7.18.2.3. Limits of fastest minimum-width integer types */ - -#define INT_FAST8_MIN INT32_MIN -#define INT_FAST8_MAX INT32_MAX -#define UINT_FAST8_MAX UINT32_MAX -#define INT_FAST16_MIN INT32_MIN -#define INT_FAST16_MAX INT32_MAX -#define UINT_FAST16_MAX UINT32_MAX -#define INT_FAST32_MIN INT32_MIN -#define INT_FAST32_MAX INT32_MAX -#define UINT_FAST32_MAX UINT32_MAX -#if 0 || 0 -#define INT_FAST64_MIN INT64_MIN -#define INT_FAST64_MAX INT64_MAX -#define UINT_FAST64_MAX UINT64_MAX -#endif - -/* 7.18.2.4. Limits of integer types capable of holding object pointers */ - -#define INTPTR_MIN LONG_MIN -#define INTPTR_MAX LONG_MAX -#define UINTPTR_MAX ULONG_MAX - -/* 7.18.2.5. Limits of greatest-width integer types */ - -#if 0 || 0 -#define INTMAX_MIN INT64_MIN -#define INTMAX_MAX INT64_MAX -#define UINTMAX_MAX UINT64_MAX -#else -#define INTMAX_MIN INT32_MIN -#define INTMAX_MAX INT32_MAX -#define UINTMAX_MAX UINT32_MAX -#endif - -/* 7.18.3. Limits of other integer types */ - -#define PTRDIFF_MIN (~(ptrdiff_t)0 << (sizeof(ptrdiff_t)*CHAR_BIT-1)) -#define PTRDIFF_MAX (~PTRDIFF_MIN) - -/* This may be wrong... */ -#define SIG_ATOMIC_MIN 0 -#define SIG_ATOMIC_MAX 127 - -#endif /* _STDINT_H */ - -//#define SIZE_MAX (~(size_t)0) - -/* wchar_t limits already defined in <stddef.h>. */ -/* wint_t limits already defined in <wchar.h>. */ - -//#endif - -/* 7.18.4. Macros for integer constants */ - -#if !defined(__cplusplus) || defined(__STDC_CONSTANT_MACROS) - -/* 7.18.4.1. Macros for minimum-width integer constants */ - -#ifdef INT8_C -#undef INT8_C -#endif -#define INT8_C(x) x - -#ifdef UINT8_C -#undef UINT8_C -#endif -#define UINT8_C(x) x##U - -#ifdef INT16_C -#undef INT16_C -#endif -#define INT16_C(x) x - -#ifdef UINT16_C -#undef UINT16_C -#endif -#define UINT16_C(x) x##U - -#ifdef INT32_C -#undef INT32_C -#endif -#define INT32_C(x) x - -#ifdef UINT32_C -#undef UINT32_C -#endif -#define UINT32_C(x) x##U - -// INT64_C and UINT64_C definitions -#ifdef INT64_C -#undef INT64_C -#endif -#ifdef UINT64_C -#undef UINT64_C -#endif -#if 0 -#define INT64_C(x) x##L -#define UINT64_C(x) x##UL -#elif 0 -#define INT64_C(x) x##LL -#define UINT64_C(x) x##ULL -#endif // #if 0 - -/* 7.18.4.2. Macros for greatest-width integer constants */ - -// INTMAX_C and UINTMAX_C definitions -#ifdef INTMAX_C -#undef INTMAX_C -#endif -#ifdef UINTMAX_C -#undef UINTMAX_C -#endif - -#if 0 -#define INTMAX_C(x) x##L -#define UINTMAX_C(x) x##UL -#elif 0 -#define INTMAX_C(x) x##LL -#define UINTMAX_C(x) x##ULL -#else -#define INTMAX_C(x) x -#define UINTMAX_C(x) x##U -#endif - -#endif - -#endif /* !HAVE_SYSTEM_INTTYPES */ - -#endif /* (_MSC_VER < 1400) */ - -#endif /* #ifdef PLATFORM_WINDOWS */ - -#endif /* __stdint_h__ */ diff --git a/libs/backends/wavesaudio/wavesapi/akupara/basics.hpp b/libs/backends/wavesaudio/wavesapi/akupara/basics.hpp deleted file mode 100644 index 33808ede8d..0000000000 --- a/libs/backends/wavesaudio/wavesapi/akupara/basics.hpp +++ /dev/null @@ -1,53 +0,0 @@ -/* - * basics.hpp - * Akupara - * - * Created by Udi on 12/19/06. - * Copyright 2006 __MyCompanyName__. All rights reserved. - * - */ -#if !defined(_AKUPARA_BASICS_HPP__INCLUDED_) -#define _AKUPARA_BASICS_HPP__INCLUDED_ - -#include "WavesPublicAPI/wstdint.h" - -namespace Akupara -{ - // The ultimate nothingness - // This is useful for writing constructors that nullify their object, and for testing nullness - struct null_type - { - null_type() {} - null_type(const null_type *) {} // this allows 0 to be implicitly converted to null_type - }; - inline null_type null() { return null_type(); } - - - // This is a byte, guaranteed to be unsigned regardless of your compiler's char signedness - typedef uint8_t byte_type; - - - // derive from this if your class needs to be noncopyable - class noncopyable_type - { - private: - noncopyable_type(const noncopyable_type &); - noncopyable_type &operator=(const noncopyable_type &); - public: - noncopyable_type() {} - }; - - -} // namespace Akupara - - -#if defined(__GNUC__) -#define AKUPARA_EXPECT_FALSE(x) __builtin_expect(x,false) -#define AKUPARA_EXPECT_TRUE(x) __builtin_expect(x,true ) -#else -#define AKUPARA_EXPECT_FALSE(x) x -#define AKUPARA_EXPECT_TRUE(x) x -#endif // __GNUC__ - - -#endif // _AKUPARA_BASICS_HPP__INCLUDED_ diff --git a/libs/backends/wavesaudio/wavesapi/akupara/compiletime_functions.hpp b/libs/backends/wavesaudio/wavesapi/akupara/compiletime_functions.hpp deleted file mode 100644 index 14c5f96523..0000000000 --- a/libs/backends/wavesaudio/wavesapi/akupara/compiletime_functions.hpp +++ /dev/null @@ -1,205 +0,0 @@ -/* -* compiletime_functions.hpp -* Akupara -* -* Created by Udi on 12/19/06. -* -*/ -#if !defined(_AKUPARA_COMPILETIME_FUNCTIONS_HPP__INCLUDED_) -#define _AKUPARA_COMPILETIME_FUNCTIONS_HPP__INCLUDED_ - -//#include "WavesPublicAPIs/wstdint.h" - -namespace Akupara -{ - // For templates that "return" a value, use template_name<arguments>::value - // For templates that "return" a type, use template_name<arguments>::type - - - // Integer log2 functions - //------------------------------------------------------------------------ - template<unsigned int n> - struct compiletime_bit_count_to_represent { static const unsigned int value = 1+compiletime_bit_count_to_represent<(n>>1)>::value; }; - - template<> - struct compiletime_bit_count_to_represent<0> { static const unsigned int value = 0; }; - //------------------------------------------------------------------------ - template<unsigned int n> - struct compiletime_log2_ceiling { static const unsigned int value=compiletime_bit_count_to_represent<n-1>::value; }; - - template<> - struct compiletime_log2_ceiling<0> {}; // no value for 0 argument - //------------------------------------------------------------------------ - template<unsigned int n> - struct compiletime_log2_floor { static const unsigned int value=compiletime_bit_count_to_represent<n>::value-1; }; - - template<> - struct compiletime_log2_floor<0> {}; // no value for 0 argument - //------------------------------------------------------------------------ - - - - // Assertion - accessing 'value' will generate a compile-time error if the argument evaluates to false - //------------------------------------------------------------------------ - template<bool> - struct compiletime_assert; - - template<> - struct compiletime_assert<true> { static const bool value=true; }; - - template<> - struct compiletime_assert<false> {}; // no value member for false assertion -> compile time error - //------------------------------------------------------------------------ - - - // Select type - selects one of two types based on a boolean - //------------------------------------------------------------------------ - template<bool, typename, typename> - struct compiletime_select_type; - - template<typename _true_type, typename _false_type> - struct compiletime_select_type<true, _true_type, _false_type> { typedef _true_type type; }; - - template<typename _true_type, typename _false_type> - struct compiletime_select_type<false, _true_type, _false_type> { typedef _false_type type; }; - //------------------------------------------------------------------------ - - - - - - // Integer types by byte count - //------------------------------------------------------------------------ - namespace detail - { - template<unsigned int _size, bool _signed> - struct integer_with_byte_count_base; - - template<> - struct integer_with_byte_count_base<1,true> { typedef int8_t type; }; - - template<> - struct integer_with_byte_count_base<2,true> { typedef int16_t type; }; - - template<> - struct integer_with_byte_count_base<4,true> { typedef int32_t type; }; - - template<> - struct integer_with_byte_count_base<8,true> { typedef int64_t type; }; - - template<> - struct integer_with_byte_count_base<1,false> { typedef uint8_t type; }; - - template<> - struct integer_with_byte_count_base<2,false> { typedef uint16_t type; }; - - template<> - struct integer_with_byte_count_base<4,false> { typedef uint32_t type; }; - - template<> - struct integer_with_byte_count_base<8,false> { typedef uint64_t type; }; - } // namespace detail - //------------------------------------------------------------------------ - template<unsigned int _size, bool _signed=true> - struct integer_with_byte_count : public detail::integer_with_byte_count_base<_size,_signed> - { - typedef typename detail::integer_with_byte_count_base<_size,_signed>::type type; // not required but makes the statement below less messy - static const bool s_correct_size = compiletime_assert<sizeof(type)==_size>::value; // if you get a compilation error here then integer_with_byte_count is not defined correctly - }; - //------------------------------------------------------------------------ - template<unsigned int _size> - struct signed_integer_with_byte_count : public integer_with_byte_count<_size,true> {}; - - template<unsigned int _size> - struct unsigned_integer_with_byte_count : public integer_with_byte_count<_size,false> {}; - //------------------------------------------------------------------------ - - - - // The following are TR1 compatible, until we get decent TR1 library support on all platforms - //------------------------------------------------------------------------ - template<typename _T, _T _v> - struct integral_constant - { - static const _T value = _v; - typedef _T value_type; - typedef integral_constant<_T, _v> type; - }; // struct integral_constant - typedef integral_constant<bool, false> false_type; - typedef integral_constant<bool, true > true_type; - //------------------------------------------------------------------------ - template<typename _T, typename _U> struct is_same : public false_type {}; - template<typename _T> struct is_same<_T,_T> : public true_type {}; - //------------------------------------------------------------------------ - - - - // These are NOT TR1 but make use of some TR1 stuff - //------------------------------------------------------------------------ - namespace detail - { - struct no_type; // if you end up getting this type, it means that you asked for something that doesn't exist - template<unsigned int _pair_index> struct signed_unsigned_pair; -#define AKUPARA_SIGNED_UNSIGNED_INTEGER_PAIR(index, base_type_name) \ - template<> struct signed_unsigned_pair<index> { typedef signed base_type_name signed_type; typedef unsigned base_type_name unsigned_type; }; -#define AKUPARA_SIGNED_UNSIGNED_FLOAT_PAIR(index, type_name) \ - template<> struct signed_unsigned_pair<index> { typedef type_name signed_type; typedef no_type unsigned_type; }; - AKUPARA_SIGNED_UNSIGNED_INTEGER_PAIR(1, char ) - AKUPARA_SIGNED_UNSIGNED_INTEGER_PAIR(2, short ) - AKUPARA_SIGNED_UNSIGNED_INTEGER_PAIR(3, int ) - - //AKUPARA_SIGNED_UNSIGNED_INTEGER_PAIR(4, int32_t )// 64BitConversion - template<> - struct - signed_unsigned_pair<4> - { - typedef int32_t signed_type; - typedef uint32_t unsigned_type; - }; - - - AKUPARA_SIGNED_UNSIGNED_INTEGER_PAIR(5, long long) - AKUPARA_SIGNED_UNSIGNED_FLOAT_PAIR (6, float ) - AKUPARA_SIGNED_UNSIGNED_FLOAT_PAIR (7, double ) - AKUPARA_SIGNED_UNSIGNED_FLOAT_PAIR (8, long double) - const unsigned int k_signed_unsigned_pair_count = 8; - - // eliminate the no_type type - template<typename _T> struct filtered_type { typedef _T type; }; - template<> struct filtered_type<no_type> {}; // no type defined - - // search for _T in signed type list - template<unsigned int _index, typename _T> struct find_in_signed_type_list_from_index - { - static const unsigned int value = is_same< _T, typename signed_unsigned_pair<_index>::signed_type >::value ? _index : find_in_signed_type_list_from_index<_index-1,_T>::value; - }; - template<typename _T> struct find_in_signed_type_list_from_index<0, _T> { static const unsigned int value = 0; }; - template<typename _T> struct find_in_signed_type_list : public find_in_signed_type_list_from_index<k_signed_unsigned_pair_count, _T> {}; - - // search for _T in unsigned type list - template<unsigned int _index, typename _T> struct find_in_unsigned_type_list_from_index - { - static const unsigned int value = is_same< _T, typename signed_unsigned_pair<_index>::unsigned_type >::value ? _index : find_in_unsigned_type_list_from_index<_index-1,_T>::value; - }; - template<typename _T> struct find_in_unsigned_type_list_from_index<0, _T> { static const unsigned int value = 0; }; - template<typename _T> struct find_in_unsigned_type_list : public find_in_unsigned_type_list_from_index<k_signed_unsigned_pair_count, _T> {}; - - template<bool _is_signed, bool _is_unsigned, typename _T> struct equivalent_signed_type; - template<typename _T> struct equivalent_signed_type <true, false, _T> { typedef _T type; }; - template<typename _T> struct equivalent_signed_type <false, true, _T> { typedef typename filtered_type< typename signed_unsigned_pair< find_in_unsigned_type_list<_T>::value >::signed_type >::type type; }; - - template<bool _is_signed, bool _is_unsigned, typename _T> struct equivalent_unsigned_type; - template<typename _T> struct equivalent_unsigned_type<true, false, _T> { typedef typename filtered_type< typename signed_unsigned_pair< find_in_signed_type_list<_T>::value >::unsigned_type >::type type; }; - template<typename _T> struct equivalent_unsigned_type<false, true, _T> { typedef _T type; }; - } // namespace detail - //------------------------------------------------------------------------ - template<typename _T> struct is_signed { static const bool value = detail::find_in_signed_type_list <_T>::value != 0; }; - template<typename _T> struct is_unsigned { static const bool value = detail::find_in_unsigned_type_list<_T>::value != 0; }; - //------------------------------------------------------------------------ - template<typename _T> struct equivalent_signed_type : public detail::equivalent_signed_type < is_signed<_T>::value, is_unsigned<_T>::value, _T > {}; - template<typename _T> struct equivalent_unsigned_type : public detail::equivalent_unsigned_type< is_signed<_T>::value, is_unsigned<_T>::value, _T > {}; - //------------------------------------------------------------------------ - -} // namespace Akupara - -#endif // _AKUPARA_COMPILETIME_FUNCTIONS_HPP__INCLUDED_ diff --git a/libs/backends/wavesaudio/wavesapi/akupara/threading/atomic_ops.hpp b/libs/backends/wavesaudio/wavesapi/akupara/threading/atomic_ops.hpp deleted file mode 100644 index 2111026d0b..0000000000 --- a/libs/backends/wavesaudio/wavesapi/akupara/threading/atomic_ops.hpp +++ /dev/null @@ -1,388 +0,0 @@ -/* -* Akupara/threading/atomic_ops.hpp -* -* -* Created by Udi Barzilai on 06/06. -* Copyright 2006 __MyCompanyName__. All rights reserved. -* -*/ -#if !defined(_AKUPARA_THREADING_ATOMIC_OPS_HPP__INCLUDED_) -#define _AKUPARA_THREADING_ATOMIC_OPS_HPP__INCLUDED_ - -#include "Akupara/basics.hpp" // for EXPECT macro -#include "Akupara/compiletime_functions.hpp" // for TR1 stuff, signed/unsigned stuff - -namespace Akupara -{ - namespace threading - { - namespace atomic - { - namespace machine - { - // Machine capabilities - // The following templates are specialized by the machine-specific headers to indicate - // the capabilities of the machine being compiled for. A true 'value' member for a given - // byte count means that there is an implementation of the corresponding atomic operation. - //------------------------------------- - template<unsigned int _byte_count> struct implements_load : public false_type {}; // simple assignment from memory (assumes naturally aligned address) - template<unsigned int _byte_count> struct implements_store : public false_type {}; // simple assignment to memory (assumes naturally aligned address) - template<unsigned int _byte_count> struct implements_CAS : public false_type {}; // compare_and_store() - template<unsigned int _byte_count> struct implements_LL_SC : public false_type {}; // load_linked(), store_conditional() - template<unsigned int _byte_count> struct implements_add : public false_type {}; // add(), subtract() - template<unsigned int _byte_count> struct implements_fetch_and_add : public false_type {}; // fetch_and_add(), fetch_and_subtract() - template<unsigned int _byte_count> struct implements_add_and_fetch : public false_type {}; // add_and_fetch(), subtract_and_fetch() - //------------------------------------- - - - //------------------------------------- - // functions in this namespace may or may not be implemented, for any integer types, as specified by the machine capabilities templates above - template<typename _integer_type> bool compare_and_store(volatile _integer_type * operand_address, const _integer_type & expected_value, const _integer_type & value_to_store); - - template<typename _integer_type> _integer_type load_linked(volatile _integer_type * operand_address); - template<typename _integer_type> bool store_conditional(volatile _integer_type * operand_address, const _integer_type & value_to_store); - - template<typename _integer_type> void add(volatile _integer_type * operand_address, const _integer_type & addend); - template<typename _integer_type> void subtract(volatile _integer_type * operand_address, const _integer_type & subtrahend); - - template<typename _integer_type> _integer_type fetch_and_add(volatile _integer_type * operand_address, const _integer_type & addend); - template<typename _integer_type> _integer_type fetch_and_subtract(volatile _integer_type * operand_address, const _integer_type & subtrahend); - - template<typename _integer_type> _integer_type add_and_fetch(volatile _integer_type * operand_address, const _integer_type & addend); - template<typename _integer_type> _integer_type subtract_and_fetch(volatile _integer_type * operand_address, const _integer_type & subtrahend); - - void memory_barrier_read(); - void memory_barrier_write(); - void memory_barrier_readwrite(); - //------------------------------------- - - } // namespace machine - } // namespace atomic - } // namespace threading -} // namespace Akupara - -// Include the machine-specific implementations; these only implement the templates above for some of the _signed_ integer types -#if defined(__GNUC__) && defined(__POWERPC__) -#include "atomic_ops_gcc_ppc.hpp" -#endif // defined(__GNUC__) && defined(__POWERPC__) - -#if defined(__GNUC__) && (defined(__i386__) || defined(__x86_64__)) -#include "atomic_ops_gcc_x86.hpp" -#endif // defined(__GNUC__) && defined(__i386__) - -#if defined(_MSC_VER) && defined(_M_IX86) -#include "atomic_ops_msvc_x86.hpp" -#endif // defined(_MSC_VER) && defined(_M_IX86) - -#if defined(_MSC_VER) && defined(_M_X64) -#include "atomic_ops_msvc_x86_64.hpp" -#endif // defined(_MSC_VER) && defined(_M_X64) - -namespace Akupara -{ - namespace threading - { - namespace atomic - { - - - // Select the most convenient atomic integer type based on the machine's ability to load/store atomically - // The definition below selects that largest atomically accessible integer up to the size of int - //---------------------------------------------------------------------------------------- - namespace detail - { - template<unsigned int _byte_count> - struct largest_atomic_byte_count_upto - { - static const unsigned int value = - machine::implements_load<_byte_count>::value && machine::implements_store<_byte_count>::value ? -_byte_count : - largest_atomic_byte_count_upto<_byte_count/2>::value; - }; - - template<> - struct largest_atomic_byte_count_upto<0> { static const unsigned int value = 0; }; - - const unsigned int k_byte_count_best_atomic = largest_atomic_byte_count_upto<sizeof(int)>::value; - } - typedef signed_integer_with_byte_count< detail::k_byte_count_best_atomic >::type signed_integer_type; - typedef unsigned_integer_with_byte_count< detail::k_byte_count_best_atomic >::type unsigned_integer_type; - typedef signed_integer_type integer_type; - //---------------------------------------------------------------------------------------- - - //---------------------------------------------------------------------------------------- - // These need to be implemented by all machines - using machine::memory_barrier_read; - using machine::memory_barrier_write; - using machine::memory_barrier_readwrite; - //---------------------------------------------------------------------------------------- - - //---------------------------------------------------------------------------------------- - // These may or may not be implemented, but if they aren't, we can't help much - using machine::load_linked; - using machine::store_conditional; - //---------------------------------------------------------------------------------------- - - - //---------------------------------------------------------------------------------------- - // CAS implementation - namespace detail - { - template< - typename _integer_type, - bool _implements_CAS = machine::implements_CAS <sizeof(_integer_type)>::value, - bool _implements_LL_SC = machine::implements_LL_SC<sizeof(_integer_type)>::value> - struct implementation_CAS - { - static const bool s_exists = false; - }; - // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // specialization for native CAS support - template<typename _integer_type, bool _implements_LL_SC> - struct implementation_CAS<_integer_type, true, _implements_LL_SC> - { - static const bool s_exists = true; - static inline bool compare_and_store(volatile _integer_type * operand_address, const _integer_type & expected_value, const _integer_type & value_to_store) - { - return machine::compare_and_store(operand_address, expected_value, value_to_store); - } - }; - // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // specialization for cases with no CAS but with LL/SC - template<typename _integer_type> - struct implementation_CAS<_integer_type, false, true> - { - static const bool s_exists = true; - static inline bool compare_and_store(volatile _integer_type * operand_address, const _integer_type & expected_value, const _integer_type & value_to_store) - { - while (machine::load_linked(operand_address) == expected_value) - if (AKUPARA_EXPECT_TRUE(machine::store_conditional(operand_address, value_to_store))) - return true; - return false; - } - }; - // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - } // namespace detail - // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - template<typename _integer_type> - inline bool compare_and_store(volatile _integer_type * operand_address, const _integer_type & expected_value, const _integer_type & value_to_store) - { - // if your compiler can't find the function to call here then there is no implementation available for your machine - return detail::implementation_CAS<_integer_type>::compare_and_store(operand_address, expected_value, value_to_store); - } - //---------------------------------------------------------------------------------------- - - - - - - //---------------------------------------------------------------------------------------- - // fetch_and_add - namespace detail - { - template< - typename _integer_type, - bool _0 = machine::implements_fetch_and_add<sizeof(_integer_type)>::value, - bool _1 = machine::implements_add_and_fetch<sizeof(_integer_type)>::value, - bool _2 = machine::implements_LL_SC <sizeof(_integer_type)>::value, - bool _3 = machine::implements_CAS <sizeof(_integer_type)>::value> - struct implementation_FAA - { - static const bool s_exists = false; - }; - // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // specialization for native support - template<typename _integer_type, bool _1, bool _2, bool _3> - struct implementation_FAA<_integer_type, true, _1, _2, _3> - { - static const bool s_exists = true; - static inline _integer_type fetch_and_add(volatile _integer_type * operand_address, const _integer_type & addend) - { - return machine::fetch_and_add(operand_address, addend); - } - }; - // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // specialization using add_and_fetch - template<typename _integer_type, bool _2, bool _3> - struct implementation_FAA<_integer_type, false, true, _2, _3> - { - static const bool s_exists = true; - static inline _integer_type fetch_and_add(volatile _integer_type * operand_address, const _integer_type & addend) - { - return machine::add_and_fetch(operand_address, addend) - addend; - } - }; - // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // specialization using LL/SC - template<typename _integer_type, bool _3> - struct implementation_FAA<_integer_type, false, false, true, _3> - { - static const bool s_exists = true; - static inline _integer_type fetch_and_add(volatile _integer_type * operand_address, const _integer_type & addend) - { - _integer_type old_value; - do - old_value = machine::load_linked(operand_address); - while (!machine::store_conditional(operand_address, old_value+addend)); - return old_value; - } - }; - // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // specialization using CAS - template<typename _integer_type> - struct implementation_FAA<_integer_type, false, false, false, true> - { - static const bool s_exists = true; - static inline _integer_type fetch_and_add(volatile _integer_type * operand_address, const _integer_type & addend) - { - _integer_type old_value; - do - old_value = *operand_address; - while (!machine::compare_and_store(operand_address, old_value, old_value+addend)); - return old_value; - } - }; - // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - } // namespace detail - template<typename _integer_type> - inline _integer_type fetch_and_add(volatile _integer_type * operand_address, const _integer_type & addend) - { - // if your compiler can't find the function to call here then there is no implementation available for your machine - return detail::implementation_FAA<_integer_type>::fetch_and_add(operand_address, addend); - } - //---------------------------------------------------------------------------------------- - - - - - //---------------------------------------------------------------------------------------- - // add_and_fetch - namespace detail - { - template< - typename _integer_type, - bool _0 = machine::implements_add_and_fetch<sizeof(_integer_type)>::value, - bool _1 = machine::implements_fetch_and_add<sizeof(_integer_type)>::value, - bool _2 = machine::implements_LL_SC <sizeof(_integer_type)>::value, - bool _3 = machine::implements_CAS <sizeof(_integer_type)>::value> - struct implementation_AAF - { - static const bool s_exists = false; - }; - // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // specialization for native support - template<typename _integer_type, bool _1, bool _2, bool _3> - struct implementation_AAF<_integer_type, true, _1, _2, _3> - { - static const bool s_exists = true; - static inline _integer_type add_and_fetch(volatile _integer_type * operand_address, const _integer_type & addend) - { - return machine::add_and_fetch(operand_address, addend); - } - }; - // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // specialization using add_and_fetch - template<typename _integer_type, bool _2, bool _3> - struct implementation_AAF<_integer_type, false, true, _2, _3> - { - static const bool s_exists = true; - static inline _integer_type add_and_fetch(volatile _integer_type * operand_address, const _integer_type & addend) - { - return machine::fetch_and_add(operand_address, addend) + addend; - } - }; - // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // specialization using LL/SC - template<typename _integer_type, bool _3> - struct implementation_AAF<_integer_type, false, false, true, _3> - { - static const bool s_exists = true; - static inline _integer_type add_and_fetch(volatile _integer_type * operand_address, const _integer_type & addend) - { - _integer_type new_value; - do - new_value = machine::load_linked(operand_address)+addend; - while (!machine::store_conditional(operand_address, new_value)); - return new_value; - } - }; - // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // specialization using CAS - template<typename _integer_type> - struct implementation_AAF<_integer_type, false, false, false, true> - { - static const bool s_exists = true; - static inline _integer_type add_and_fetch(volatile _integer_type * operand_address, const _integer_type & addend) - { - _integer_type old_value, new_value; - do - old_value = *operand_address, new_value = old_value + addend; - while (!machine::compare_and_store(operand_address, old_value, new_value)); - return new_value; - } - }; - // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - } // namespace detail - template<typename _integer_type> - inline _integer_type add_and_fetch(volatile _integer_type * operand_address, const _integer_type & addend) - { - // if your compiler can't find the function to call here then there is no implementation available for your machine - return detail::implementation_AAF<_integer_type>::add_and_fetch(operand_address, addend); - } - //---------------------------------------------------------------------------------------- - - - - //---------------------------------------------------------------------------------------- - // add - template<typename _integer_type> - inline void add(volatile _integer_type * operand_address, const _integer_type & addend) - { - if (machine::implements_add<sizeof(_integer_type)>::value) - machine::add(operand_address, addend); - else if (machine::implements_fetch_and_add<sizeof(_integer_type)>::value) - machine::fetch_and_add(operand_address, addend); - else if (machine::implements_add_and_fetch<sizeof(_integer_type)>::value) - machine::add_and_fetch(operand_address, addend); - else - fetch_and_add(operand_address, addend); // this will simulate using CAS or LL/SC (or it will fail the compilation if neither is available) - } - //---------------------------------------------------------------------------------------- - - - - //---------------------------------------------------------------------------------------- - // TODO: this is where we add implementations for: - // - functions not implemented by the machine - // - functions that take unsigned types (routed to call the signed versions with appropriate conversions) - // For now we add nothing, so developers will need to stick to what their machine can do, and use signed - // integers only. - using machine::subtract; - using machine::subtract_and_fetch; - using machine::fetch_and_subtract; - //---------------------------------------------------------------------------------------- - - - - //--------------------------------------------------------------------- - template<class _base_type, unsigned int _bytes_per_cache_line=machine::k_bytes_per_cache_line> - struct pad_to_cache_line : public _base_type - { - private: - typedef pad_to_cache_line this_type; - typedef _base_type base_type; - public: - static const unsigned int s_bytes_per_cache_line = _bytes_per_cache_line; - private: - int m_padding[(s_bytes_per_cache_line - sizeof(base_type))/sizeof(int)]; - public: - pad_to_cache_line() {} - template<typename _arg_type> pad_to_cache_line(_arg_type arg) : base_type(arg) {} - }; - //--------------------------------------------------------------------- - - } // namespace atomic - } // namespace threading -} // namespace Akupara - -#endif // _AKUPARA_THREADING_ATOMIC_OPS_HPP__INCLUDED_ diff --git a/libs/backends/wavesaudio/wavesapi/akupara/threading/atomic_ops_gcc_x86.hpp b/libs/backends/wavesaudio/wavesapi/akupara/threading/atomic_ops_gcc_x86.hpp deleted file mode 100644 index 74d73106f8..0000000000 --- a/libs/backends/wavesaudio/wavesapi/akupara/threading/atomic_ops_gcc_x86.hpp +++ /dev/null @@ -1,201 +0,0 @@ -/* - * Akupara/threading/atomic_ops_gcc_x86.hpp - * - * - * Created by Udi Barzilai on 06/06. - * Copyright 2006 __MyCompanyName__. All rights reserved. - * - */ -#if !defined(_AKUPARA_THREADING_ATOMIC_OPS_GCC_X86_HPP__INCLUDED_) -# define _AKUPARA_THREADING_ATOMIC_OPS_GCC_X86_HPP__INCLUDED_ -# if defined(__GNUC__) && (defined(__i386__) || defined(__x86_64__)) - -namespace Akupara -{ - namespace threading - { - namespace atomic - { - namespace machine - { - const unsigned int k_bytes_per_cache_line = 64; // this is true for P4 & K8 - - - // Flags for operations supported by this machine - //------------------------------------- - template<> struct implements_load <4> : public true_type {}; - template<> struct implements_store <4> : public true_type {}; - template<> struct implements_CAS <4> : public true_type {}; - template<> struct implements_CAS <8> : public true_type {}; - template<> struct implements_add <4> : public true_type {}; - template<> struct implements_fetch_and_add<4> : public true_type {}; - //------------------------------------- - - - - // CAS - //-------------------------------------------------------------------------------- - template<> - inline bool compare_and_store<int64_t>(volatile int64_t * p, const int64_t & x, const int64_t & y) - { - register int32_t evh=int32_t(x>>32), evl=int32_t(x); - register const int32_t nvh=int32_t(y>>32), nvl=int32_t(y); - register bool result; - __asm__ __volatile__ ( - "# CAS64\n" - " lock \n" - " cmpxchg8b %[location] \n" - " sete %[result] \n" - : [location] "+m" (*p), [result] "=qm" (result), [expected_value_high] "+d" (evh), [expected_value_low] "+a" (evl) - : [new_value_high] "c" (nvh), [new_value_low] "b" (nvl) - : "cc" - ); - return result; - } - //-------------------------------------------------------------------------------- - template<> - inline bool compare_and_store<int32_t>(volatile int32_t *p, const int32_t & x, const int32_t & y) - { - register int32_t expected_value = x; - register bool result; - __asm__ __volatile__ ( - "# CAS32\n" - " lock \n" - " cmpxchgl %[new_value],%[operand] \n" - " sete %[result] \n" - : [operand] "+m" (*p), [result] "=qm" (result), [expected_value] "+a" (expected_value) - : [new_value] "r" (y) - : "cc" - ); - return result; - } - //-------------------------------------------------------------------------------- - - - - - // Atomic add/sub - //-------------------------------------------------------------------------------- - inline void increment(volatile int32_t * operand_address) - { - __asm__ __volatile__ ( - "# atomic_increment_32\n" - " lock; \n" - " incl %[operand]; \n" - : [operand] "+m" (*operand_address) - : - : "cc" - ); - } - //-------------------------------------------------------------------------------- - inline void decrement(volatile int32_t * operand_address) - { - __asm__ __volatile__ ( - "# atomic_decrement_32\n" - " lock; \n" - " decl %[operand]; \n" - : [operand] "+m" (*operand_address) - : - : "cc" - ); - } - //-------------------------------------------------------------------------------- - template<> - inline void add<int32_t>(volatile int32_t * operand_address, const int32_t & addend) - { - if (__builtin_constant_p(addend) && addend==1) - increment(operand_address); - else if (__builtin_constant_p(addend) && addend==-1) - decrement(operand_address); - else - __asm__ __volatile__ ( - "# atomic_add_32 \n" - " lock \n" - " addl %[addend], %[operand] \n" - : [operand] "+m" (*operand_address) - : [addend] "ir" (addend) - : "cc" - ); - } - //-------------------------------------------------------------------------------- - template<> - inline void subtract<int32_t>(volatile int32_t * operand_address, const int32_t & subtrahend) - { - if (__builtin_constant_p(subtrahend) && subtrahend==1) - decrement(operand_address); - else if (__builtin_constant_p(subtrahend) && subtrahend==-1) - increment(operand_address); - else - __asm__ __volatile__ ( - "# atomic_subtract_32 \n" - " lock \n" - " subl %[subtrahend], %[operand] \n" - : [operand] "+m" (*operand_address) - : [subtrahend] "ir" (subtrahend) - : "cc" - ); - } - //-------------------------------------------------------------------------------- - - - - // Atomic fetch and add/sub - //-------------------------------------------------------------------------------- - template<> - inline int32_t fetch_and_add<int32_t>(volatile int32_t * operand_address, const int32_t & addend) - { - register int32_t addend_and_fetched = addend; - __asm__ __volatile__ ( - "# atomic_fetch_and_add_32 \n" - " lock; \n" - " xaddl %[addend], %[operand]; \n" - : [operand] "+m" (*operand_address), [addend] "+r" (addend_and_fetched) - : - : "cc" - ); - return addend_and_fetched; - } - //-------------------------------------------------------------------------------- - template<> - inline int32_t fetch_and_subtract<int32_t>(volatile int32_t * operand_address, const int32_t & subtrahend) - { - return fetch_and_add(operand_address, -subtrahend); - } - //-------------------------------------------------------------------------------- - - - - - // Memory barriers - //-------------------------------------------------------------------------------- - inline void memory_barrier_readwrite() - { - #if _AKUPARA_X86_SSE_NOT_AVAILABLE - __asm__ __volatile__ (" lock; addl $0,0(%%esp); # memory_barrier_readwrite" : : : "memory"); - #else - __asm__ __volatile__ (" mfence; # memory_barrier_readwrite" : : : "memory"); - #endif // _LOCKFREE_ATOMIC_OPS_X86_LFENCE_NOT_AVAILABLE - } - //-------------------------------------------------------------------------------- - inline void memory_barrier_read() - { - #if _AKUPARA_X86_SSE_NOT_AVAILABLE - __asm__ __volatile__ (" lock; addl $0,0(%%esp); # memory_barrier_read" : : : "memory"); - #else - __asm__ __volatile__ (" lfence; # memory_barrier_read" : : : "memory"); - #endif // _LOCKFREE_ATOMIC_OPS_X86_LFENCE_NOT_AVAILABLE - } - //-------------------------------------------------------------------------------- - inline void memory_barrier_write() - { - __asm__ __volatile__ (" sfence; # memory_barrier_write" : : : "memory"); - } - //-------------------------------------------------------------------------------- - - } // namespace machine - } // namespace atomic - } // namespace threading -} // namespace Akupara - -# endif // defined(__GNUC__) && defined(__i386__) -#endif // _AKUPARA_THREADING_ATOMIC_OPS_GCC_X86_HPP__INCLUDED_ diff --git a/libs/backends/wavesaudio/wavesapi/devicemanager/IncludeWindows.h b/libs/backends/wavesaudio/wavesapi/devicemanager/IncludeWindows.h deleted file mode 100644 index 53ed7e69bc..0000000000 --- a/libs/backends/wavesaudio/wavesapi/devicemanager/IncludeWindows.h +++ /dev/null @@ -1,50 +0,0 @@ -/* - Copyright (C) 2014 Waves Audio Ltd. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. - -*/ - -#ifndef __IncludeWindows_h__ -#define __IncludeWindows_h__ - -#ifdef PLATFORM_WINDOWS - -/* Copy to include -#include "IncludeWindows.h" -*/ - -#ifndef _WIN32_WINNT -#define _WIN32_WINNT 0x0601 // Windows 7 -#endif - -#ifndef WINVER -#define WINVER 0x0601 // Windows 7 -#endif - -#ifndef WIN32_LEAN_AND_MEAN -#define WIN32_LEAN_AND_MEAN -#endif - -#ifndef NOMINMAX -#define NOMINMAX // DO NOT REMOVE NOMINMAX - DOING SO CAUSES CONFLICTS WITH STD INCLUDES (<limits> ...) -#endif - -#include <winsock2.h> -#include <windows.h> -#include <objbase.h> -#endif // #if PLATFORM_WINDOWS -#endif // #ifndef __IncludeWindows_h__ - diff --git a/libs/backends/wavesaudio/wavesapi/devicemanager/WCMRAudioDeviceManager.cpp b/libs/backends/wavesaudio/wavesapi/devicemanager/WCMRAudioDeviceManager.cpp deleted file mode 100644 index 7c4a3e9962..0000000000 --- a/libs/backends/wavesaudio/wavesapi/devicemanager/WCMRAudioDeviceManager.cpp +++ /dev/null @@ -1,692 +0,0 @@ -//---------------------------------------------------------------------------------- -// -// Copyright (c) 2008 Waves Audio Ltd. All rights reserved. -// -//! \file WCMRAudioDeviceManager.cpp -//! -//! WCMRAudioDeviceManager and related class declarations -//! -//---------------------------------------------------------------------------------*/ -#include <iostream> -#include "WCMRAudioDeviceManager.h" - - -//********************************************************************************************** -// WCMRAudioDevice::WCMRAudioDevice -// -//! Constructor for the audio device. The derived classes will need to do more actual work, such -//! as determining supported sampling rates, buffer sizes, and channel counts. Connection -//! and streaming will also be provided by the derived implementations. -//! -//! \param *pManager : The audio device manager that's managing this device. -//! \return Nothing. -//! -//********************************************************************************************** -WCMRAudioDevice::WCMRAudioDevice (WCMRAudioDeviceManager *pManager) : - m_pMyManager (pManager) - , m_ConnectionStatus (DeviceDisconnected) - , m_IsActive (false) - , m_IsStreaming (false) - , m_CurrentSamplingRate (-1) - , m_CurrentBufferSize (0) - , m_LeftMonitorChannel (-1) - , m_RightMonitorChannel (-1) - , m_MonitorGain (1.0f) -{ - m_DeviceName = "Unknown"; -} - - - -//********************************************************************************************** -// WCMRAudioDevice::~WCMRAudioDevice -// -//! Destructor for the audio device. It release all the connections that were created. -//! -//! \param none -//! -//! \return Nothing. -//! -//********************************************************************************************** -WCMRAudioDevice::~WCMRAudioDevice () -{ - AUTO_FUNC_DEBUG; - try - { - } - catch (...) - { - //destructors should absorb exceptions, no harm in logging though!! - DEBUG_MSG ("Exception during destructor"); - } -} - - - - -//********************************************************************************************** -// WCMRAudioDevice::DeviceName -// -//! Retrieves Device's name. -//! -//! \param none -//! -//! \return The device name. -//! -//********************************************************************************************** -const std::string& WCMRAudioDevice::DeviceName () const -{ - return (m_DeviceName); - -} - - - -//********************************************************************************************** -// WCMRAudioDevice::InputChannels -// -//! Retrieves Input Channel information. Note that the list may be changed at run-time. -//! -//! \param none -//! -//! \return A vector with Input Channel Names. -//! -//********************************************************************************************** -const std::vector<std::string>& WCMRAudioDevice::InputChannels () -{ - return (m_InputChannels); - -} - - - -//********************************************************************************************** -// WCMRAudioDevice::OutputChannels -// -//! Retrieves Output Channel Information. Note that the list may be changed at run-time. -//! -//! \param none -//! -//! \return A vector with Output Channel Names. -//! -//********************************************************************************************** -const std::vector<std::string>& WCMRAudioDevice::OutputChannels () -{ - return (m_OutputChannels); -} - - - - -//********************************************************************************************** -// WCMRAudioDevice::SamplingRates -// -//! Retrieves supported sampling rate information. -//! -//! \param none -//! -//! \return A vector with supported sampling rates. -//! -//********************************************************************************************** -const std::vector<int>& WCMRAudioDevice::SamplingRates () -{ - return (m_SamplingRates); -} - - - -//********************************************************************************************** -// WCMRAudioDevice::CurrentSamplingRate -// -//! The device's current sampling rate. This may be overridden, if the device needs to -//! query the driver for the current rate. -//! -//! \param none -//! -//! \return The device's current sampling rate. -1 on error. -//! -//********************************************************************************************** -int WCMRAudioDevice::CurrentSamplingRate () -{ - return (m_CurrentSamplingRate); -} - - - - -//********************************************************************************************** -// WCMRAudioDevice::SetCurrentSamplingRate -// -//! Change the sampling rate to be used by the device. This will most likely be overridden, -//! the base class simply updates the member variable. -//! -//! \param newRate : The rate to use (samples per sec). -//! -//! \return eNoErr always. The derived classes may return error codes. -//! -//********************************************************************************************** -WTErr WCMRAudioDevice::SetCurrentSamplingRate (int newRate) -{ - //changes the status. - m_CurrentSamplingRate = newRate; - return (eNoErr); -} - - - - -//********************************************************************************************** -// WCMRAudioDevice::BufferSizes -// -//! Retrieves supported buffer size information. -//! -//! \param none -//! -//! \return A vector with supported buffer sizes. -//! -//********************************************************************************************** -const std::vector<int>& WCMRAudioDevice::BufferSizes () -{ - return (m_BufferSizes); -} - - - -//********************************************************************************************** -// WCMRAudioDevice::CurrentBufferSize -// -//! The device's current buffer size in use. This may be overridden, if the device needs to -//! query the driver for the current size. -//! -//! \param none -//! -//! \return The device's current buffer size. 0 on error. -//! -//********************************************************************************************** -int WCMRAudioDevice::CurrentBufferSize () -{ - return (m_CurrentBufferSize); -} - -//********************************************************************************************** -// WCMRAudioDevice::CurrentBlockSize -// -//! Device's block size we use for holding the audio samples. -//! Usually this is equal to the buffer size, but in some cases the buffer size holds additional -//! data other then the audio buffers, like frames info in SG, so it can be overridden -//! -//! \param none -//! -//! \return The device's current block size. 0 on error. -//! -//********************************************************************************************** -int WCMRAudioDevice::CurrentBlockSize() -{ - // By default - return the buffer size - return CurrentBufferSize(); -} - - -//********************************************************************************************** -// WCMRAudioDevice::SetCurrentBufferSize -// -//! Change the buffer size to be used by the device. This will most likely be overridden, -//! the base class simply updates the member variable. -//! -//! \param newSize : The buffer size to use (in sample-frames) -//! -//! \return eNoErr always. The derived classes may return error codes. -//! -//********************************************************************************************** -WTErr WCMRAudioDevice::SetCurrentBufferSize (int newSize) -{ - //This will most likely be overridden, the base class simply - //changes the member. - m_CurrentBufferSize = newSize; - return (eNoErr); -} - - - - -//********************************************************************************************** -// WCMRAudioDevice::ConnectionStatus -// -//! Retrieves the device's current connection status. This will most likely be overridden, -//! in case some driver communication is required to query the status. -//! -//! \param none -//! -//! \return A ConnectionStates value. -//! -//********************************************************************************************** -WCMRAudioDevice::ConnectionStates WCMRAudioDevice::ConnectionStatus () -{ - return (m_ConnectionStatus); - -} - - - - -//********************************************************************************************** -// WCMRAudioDevice::Active -// -//! Retrieves Device activation status. -//! -//! \param none -//! -//! \return true if device is active, false otherwise. -//! -//********************************************************************************************** -bool WCMRAudioDevice::Active () -{ - return (m_IsActive); - -} - - - -//********************************************************************************************** -// WCMRAudioDevice::SetActive -// -//! Sets the device's activation status. -//! -//! \param newState : Should be true to activate, false to deactivate. This roughly corresponds -//! to opening and closing the device handle/stream/audio unit. -//! -//! \return eNoErr always, the derived classes may return appropriate error code. -//! -//********************************************************************************************** -WTErr WCMRAudioDevice::SetActive (bool newState) -{ - //This will most likely be overridden, the base class simply - //changes the member. - m_IsActive = newState; - return (eNoErr); -} - - - - -//********************************************************************************************** -// WCMRAudioDevice::Streaming -// -//! Retrieves Device streaming status. -//! -//! \param none -//! -//! \return true if device is streaming, false otherwise. -//! -//********************************************************************************************** -bool WCMRAudioDevice::Streaming () -{ - return (m_IsStreaming); -} - - - -//********************************************************************************************** -// WCMRAudioDevice::SetStreaming -// -//! Sets the device's streaming status. -//! -//! \param newState : Should be true to start streaming, false to stop streaming. This roughly -//! corresponds to calling Start/Stop on the lower level interface. -//! -//! \return eNoErr always, the derived classes may return appropriate error code. -//! -//********************************************************************************************** -WTErr WCMRAudioDevice::SetStreaming (bool newState) -{ - // We must notify angine about our intention to start streming - // so Engine will provide all the initializations in the first audio callback - if (newState) { - m_pMyManager->NotifyClient (WCMRAudioDeviceManagerClient::DeviceStartsStreaming); - } - - //This will most likely be overridden, the base class simply - //changes the member. - m_IsStreaming = newState; - return (eNoErr); -} - - -WTErr WCMRAudioDevice::ResetDevice () -{ - // Keep device sates - bool wasStreaming = Streaming(); - bool wasActive = Active(); - - WTErr err = SetStreaming(false); - - if (err == eNoErr) - err = SetActive(false); - - if (err == eNoErr && wasActive) - err = SetActive(true); - - if (err == eNoErr && wasStreaming) - SetStreaming(true); - - return err; -} - - -/////////////////////////////////////////////////////////////////////////////////////////////////////// -// IsProcessActive - returns true if process code is running. -// A normal audio device should return the Streaming() value -/////////////////////////////////////////////////////////////////////////////////////////////////////// -bool WCMRAudioDevice::IsProcessActive() -{ - return Streaming(); -} - - - - - -//********************************************************************************************** -// WCMRAudioDevice::DoIdle -// -//! A place for doing idle time processing. The derived classes will probably do something -//! meaningful. -//! -//! \param none -//! -//! \return eNoErr always. -//! -//********************************************************************************************** -WTErr WCMRAudioDevice::DoIdle () -{ - //We don't need to do anything here... - //the derived classes may want to use this however. - return (eNoErr); -} - - - - -//********************************************************************************************** -// WCMRAudioDevice::InputLevels -// -//! Retrieve current input levels. -//! -//! \param none -//! -//! \return A vector (the same size as input channels list) that contains current input levels. -//! -//********************************************************************************************** -const std::vector<float>& WCMRAudioDevice::InputLevels () -{ - //The derived classes may override if they need to query - //the driver for the levels. - return (m_InputLevels); -} - - - -//********************************************************************************************** -// WCMRAudioDevice::OutputLevels -// -//! Retrieve current output levels. -//! -//! \param none -//! -//! \return A vector (the same size as output channels list) that contains current output levels. -//! -//********************************************************************************************** -const std::vector<float>& WCMRAudioDevice::OutputLevels () -{ - //The derived classes may override if they need to query - //the driver for the levels. - return (m_OutputLevels); -} - - - -//********************************************************************************************** -// WCMRAudioDevice::GetMonitorInfo -// -//! Retrieves current monitoring information. -//! -//! \param *pLeftChannel : Pointer to receive left monitor channel index. -//! \param *pRightChannel : Pointer to receive right monitor channel index. -//! \param *pGain : Pointer to receive the gain (linear) to be applied. -//! -//! \return Nothing. -//! -//********************************************************************************************** -void WCMRAudioDevice::GetMonitorInfo (int *pLeftChannel, int *pRightChannel, float *pGain) -{ - if (pLeftChannel) - *pLeftChannel = m_LeftMonitorChannel; - if (pRightChannel) - *pRightChannel = m_RightMonitorChannel; - if (pGain) - *pGain = m_MonitorGain; - return; -} - - - -//********************************************************************************************** -// WCMRAudioDevice::SetMonitorChannels -// -//! Used to set the channels to be used for monitoring. -//! -//! \param leftChannel : Left monitor channel index. -//! \param rightChannel : Right monitor channel index. -//! -//! \return eNoErr always, the derived classes may return appropriate errors. -//! -//********************************************************************************************** -WTErr WCMRAudioDevice::SetMonitorChannels (int leftChannel, int rightChannel) -{ - //This will most likely be overridden, the base class simply - //changes the member. - m_LeftMonitorChannel = leftChannel; - m_RightMonitorChannel = rightChannel; - return (eNoErr); -} - - - -//********************************************************************************************** -// WCMRAudioDevice::SetMonitorGain -// -//! Used to set monitor gain (or atten). -//! -//! \param newGain : The new gain or atten. value to use. Specified as a linear multiplier (not dB) -//! -//! \return eNoErr always, the derived classes may return appropriate errors. -//! -//********************************************************************************************** -WTErr WCMRAudioDevice::SetMonitorGain (float newGain) -{ - //This will most likely be overridden, the base class simply - //changes the member. - m_MonitorGain = newGain; - return (eNoErr); -} - - - - -//********************************************************************************************** -// WCMRAudioDevice::ShowConfigPanel -// -//! Used to show device specific config/control panel. Some interfaces may not support it. -//! Some interfaces may require the device to be active before it can display a panel. -//! -//! \param pParam : A device/interface specific parameter - optional. -//! -//! \return eNoErr always, the derived classes may return errors. -//! -//********************************************************************************************** -WTErr WCMRAudioDevice::ShowConfigPanel (void *WCUNUSEDPARAM(pParam)) -{ - //This will most likely be overridden... - return (eNoErr); -} - - -//********************************************************************************************** -// WCMRAudioDevice::SendCustomCommand -// -//! Used to Send a custom command to the audiodevice. Some interfaces may require the device -//! to be active before it can do anything in this. -//! -//! \param customCommand : A device/interface specific command. -//! \param pCommandParam : A device/interface/command specific parameter - optional. -//! -//! \return eNoErr always, the derived classes may return errors. -//! -//********************************************************************************************** -WTErr WCMRAudioDevice::SendCustomCommand (int WCUNUSEDPARAM(customCommand), void *WCUNUSEDPARAM(pCommandParam)) -{ - //This will most likely be overridden... - return (eNoErr); -} - -//********************************************************************************************** -// WCMRAudioDevice::GetLatency -// -//! Get Latency for device. -//! -//! Use 'kAudioDevicePropertyLatency' and 'kAudioDevicePropertySafetyOffset' + GetStreamLatencies -//! -//! \param isInput : Return latency for the input if isInput is true, otherwise the output latency -//! wiil be returned. -//! \return Latency in samples. -//! -//********************************************************************************************** -uint32_t WCMRAudioDevice::GetLatency (bool isInput) -{ - //This will most likely be overridden... - return 0; -} - - -//********************************************************************************************** -// WCMRAudioDeviceManager::WCMRAudioDeviceManager -// -//! The constructuor, most of the work will be done in the derived class' constructor. -//! -//! \param *pTheClient : -//! -//! \return Nothing. -//! -//********************************************************************************************** -WCMRAudioDeviceManager::WCMRAudioDeviceManager(WCMRAudioDeviceManagerClient *pTheClient, eAudioDeviceFilter eCurAudioDeviceFilter) - : m_eAudioDeviceFilter(eCurAudioDeviceFilter) - , m_CurrentDevice(0) - , m_pTheClient (pTheClient) -{ -} - - -//********************************************************************************************** -// WCMRAudioDeviceManager::~WCMRAudioDeviceManager -// -//! It clears the device list, releasing each of the device. -//! -//! \param none -//! -//! \return Nothing. -//! -//********************************************************************************************** -WCMRAudioDeviceManager::~WCMRAudioDeviceManager() -{ - AUTO_FUNC_DEBUG; - - std::cout << "API::Destroying AudioDeviceManager " << std::endl; - try - { - // clean up device info list - { - wvNS::wvThread::ThreadMutex::lock theLock(m_AudioDeviceInfoVecMutex); - while( m_DeviceInfoVec.size() ) - { - DeviceInfo* devInfo = m_DeviceInfoVec.back(); - m_DeviceInfoVec.pop_back(); - delete devInfo; - } - } - delete m_CurrentDevice; - - } - catch (...) - { - //destructors should absorb exceptions, no harm in logging though!! - DEBUG_MSG ("Exception during destructor"); - } -} - - -WCMRAudioDevice* WCMRAudioDeviceManager::InitNewCurrentDevice(const std::string & deviceName) -{ - return initNewCurrentDeviceImpl(deviceName); -} - - -void WCMRAudioDeviceManager::DestroyCurrentDevice() -{ - return destroyCurrentDeviceImpl(); -} - - -const DeviceInfoVec WCMRAudioDeviceManager::DeviceInfoList() const -{ - wvNS::wvThread::ThreadMutex::lock theLock(m_AudioDeviceInfoVecMutex); - return m_DeviceInfoVec; -} - - -WTErr WCMRAudioDeviceManager::GetDeviceInfoByName(const std::string & nameToMatch, DeviceInfo & devInfo) const -{ - wvNS::wvThread::ThreadMutex::lock theLock(m_AudioDeviceInfoVecMutex); - DeviceInfoVecConstIter iter = m_DeviceInfoVec.begin(); - for (; iter != m_DeviceInfoVec.end(); ++iter) - { - if (nameToMatch == (*iter)->m_DeviceName) - { - devInfo = *(*iter); - return eNoErr; - } - } - - return eRMResNotFound; -} - - -WTErr WCMRAudioDeviceManager::GetDeviceSampleRates(const std::string & nameToMatch, std::vector<int>& sampleRates) const -{ - return getDeviceSampleRatesImpl(nameToMatch, sampleRates); -} - - - -WTErr WCMRAudioDeviceManager::GetDeviceBufferSizes(const std::string & nameToMatch, std::vector<int>& bufferSizes) const -{ - return getDeviceBufferSizesImpl(nameToMatch, bufferSizes); -} - - -//********************************************************************************************** -// WCMRAudioDeviceManager::NotifyClient -// -//! A helper routine used to call the client for notification. -//! -//! \param forReason : The reason for notification. -//! \param *pParam : A parameter (if required) for notification. -//! -//! \return Nothing. -//! -//********************************************************************************************** -void WCMRAudioDeviceManager::NotifyClient (WCMRAudioDeviceManagerClient::NotificationReason forReason, void *pParam) -{ - if (m_pTheClient) - m_pTheClient->AudioDeviceManagerNotification (forReason, pParam); - return; -} diff --git a/libs/backends/wavesaudio/wavesapi/devicemanager/WCMRAudioDeviceManager.h b/libs/backends/wavesaudio/wavesapi/devicemanager/WCMRAudioDeviceManager.h deleted file mode 100644 index b22e35263d..0000000000 --- a/libs/backends/wavesaudio/wavesapi/devicemanager/WCMRAudioDeviceManager.h +++ /dev/null @@ -1,271 +0,0 @@ -/* - Copyright (C) 2014 Waves Audio Ltd. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. - -*/ - -//---------------------------------------------------------------------------------- -// -// -//! \file WCMRAudioDeviceManager.h -//! -//! WCMRAudioDeviceManager and related class declarations -//! -//---------------------------------------------------------------------------------*/ -#ifndef __WCMRAudioDeviceManager_h_ - #define __WCMRAudioDeviceManager_h_ - -/* Copy to include -#include "WCMRAudioDeviceManager.h" -*/ - -#define AUTO_FUNC_DEBUG -#define DEBUG_MSG(a) -#define ASSERT_ERROR(a, b) -#define TRACE_MSG(a) - -#include <string> -#include <vector> -#include <map> -#include "WCRefManager.h" -#include "BasicTypes/WUTypes.h" -#include "WUErrors.h" -#include "WCThreadSafe.h" - -#define WCUNUSEDPARAM(a) - -class WCMRAudioDevice; -class WCMRAudioDeviceManager; - -typedef unsigned int DeviceID; - -struct DeviceInfo -{ - DeviceID m_DeviceId; - std::string m_DeviceName; - std::vector<int> m_AvailableSampleRates; - std::vector<int> m_AvailableBufferSizes; - unsigned int m_MaxInputChannels; - unsigned int m_MaxOutputChannels; - - DeviceInfo(): - m_DeviceId(-1), m_DeviceName("Unknown"), m_MaxInputChannels(0), m_MaxOutputChannels(0) - {}; - - DeviceInfo(unsigned int deviceID, const std::string & deviceName): - m_DeviceId(deviceID), m_DeviceName(deviceName), m_MaxInputChannels(0), m_MaxOutputChannels(0) - {}; -}; - -typedef std::vector<DeviceInfo*> DeviceInfoVec; -typedef DeviceInfoVec::iterator DeviceInfoVecIter; -typedef DeviceInfoVec::const_iterator DeviceInfoVecConstIter; - -/// for notification... A client must derive it's class from us. -class WCMRAudioDeviceManagerClient -{ - public: - enum NotificationReason - { - DeviceListChanged, - Dropout, - RequestReset, - RequestResync, - SamplingRateChanged, //param has new SR, or -1 if not known - SamplingRateChangedSilent, //To indicate sampling rate changed but no need to notify user - BufferSizeChanged, - ClockSourceChanged, - DeviceStoppedStreaming, - DeviceStartsStreaming, - DeviceDroppedSamples, - DeviceConnectionLost, - DeviceGenericError, - DeviceStatusChanged, - DeviceStatisticsUpdated, - DeviceDebugInfo, //param has c string - DeviceProgressInfo, //param has c string - MIDIData, - MIDINodeUp, - MIDINodeDown, - DeviceSampleRateMisMatch, - SystemSamplingRateChangedInfoOnly, - LostClockSource, - IODeviceDisconnected, - ChannelCountModified, - MasterUp, - MasterDown, - AudioDropFound, - ReflasherEvent, - AGDeviceSamplingRateChangedInfoOnly, - IODeviceNameChanged, - SetDisplayNameFromIOModule, - IOMStateChanged, ///< This is used when IOM state is changed. - AudioCallback // VKamyshniy: param is AudioCallbackDataData* - }; - - WCMRAudioDeviceManagerClient () {} - virtual ~WCMRAudioDeviceManagerClient () {} - - // VKamyshniy: This is a structure to call the client's AudioDeviceManagerNotification - // every AudioCallback time - struct AudioCallbackData - { - const float *acdInputBuffer; - float *acdOutputBuffer; - size_t acdFrames; - int64_t acdSampleTime; - uint64_t acdCycleStartTimeNanos; - }; - - virtual void AudioDeviceManagerNotification (NotificationReason WCUNUSEDPARAM(reason), void *WCUNUSEDPARAM(pParam)) {} -}; - - -class WCMRAudioDevice : public WCRefManager -{ -public: - - enum ConnectionStates - { - DeviceAvailable, - DeviceDisconnected, - DeviceErrors - }; - - WCMRAudioDevice (WCMRAudioDeviceManager *pManager);///<Constructor - virtual ~WCMRAudioDevice ();///<Destructor - - virtual const std::string& DeviceName() const;///<Name? - virtual const std::vector<std::string>& InputChannels();///<Current Input Channel List? - note that this may change with change in sampling rate. - virtual const std::vector<std::string>& OutputChannels();///<Current Output Channel List? - note that this may change with change in sampling rate. - - virtual const std::vector<int>& SamplingRates();///<Supported Sampling Rate List? - virtual int CurrentSamplingRate(); ///<Current Sampling rate.? - virtual WTErr SetCurrentSamplingRate(int newRate);///<Change Current Sampling Rate : This is a requset, might not be successful at run time! - - virtual const std::vector<int>& BufferSizes();///<Supported Buffer Size List? - note that this may change with change in sampling rate. - virtual int CurrentBufferSize();///<Current Buffer Size.? - note that this may change with change in sampling rate. - virtual WTErr SetCurrentBufferSize (int newSize);///<Change Current Buffer Size : This is a requset, might not be successful at run time! - - virtual int CurrentBlockSize(); - - virtual ConnectionStates ConnectionStatus();///< Connection Status - device available, gone, disconnected - - virtual bool Active();///<Active status - mainly significant for ASIO, as certain ops can only be performed on active devices! - virtual WTErr SetActive (bool newState);///<Prepare/Activate device. - - virtual bool Streaming();///<Streaming Status? - virtual WTErr SetStreaming (bool newState);///<Start/Stop Streaming - should reconnect connections when streaming starts! - - virtual WTErr ResetDevice (); - - virtual bool IsProcessActive(); - - virtual WTErr DoIdle();///<Do Idle Processing - - virtual const std::vector<float>& InputLevels();///<Retrieve Input Levels (for VU display)? - - virtual const std::vector<float>& OutputLevels();///<Retrieve Output Levels (for VU display)? - - void GetMonitorInfo (int *pLeftChannel = NULL, int *pRightChannel = NULL, float *pGain = NULL);///<Retrieve current monitor channel pair and gain - optional, will not be available with AG - virtual WTErr SetMonitorChannels (int leftChannel, int rightChannel);///<Set monitor channels. - optional, will not be available with AG - virtual WTErr SetMonitorGain (float newGain);///<Set monitor gain. - optional, will not be available with AG - - virtual WTErr ShowConfigPanel (void *pParam);///< Show Control Panel - in case of ASIO this will work only with Active device! - virtual WTErr SendCustomCommand (int customCommand, void *pCommandParam); ///< Send a custom command to the audiodevice... - - virtual uint32_t GetLatency (bool isInput); ///Get latency. - - virtual WTErr UpdateDeviceInfo () = 0; - -protected: - WCMRAudioDeviceManager *m_pMyManager; ///< The manager who's managing this device, can be used for sending notifications! - - std::string m_DeviceName; ///< Name of the device. - std::vector<std::string> m_InputChannels; ///< List of input channel names. - std::vector<std::string> m_OutputChannels; ///< List of output channel names. - std::vector<int> m_SamplingRates; ///< List of available sampling rates. - std::vector<int> m_BufferSizes; ///< List of available buffer sizes. - - int m_CurrentSamplingRate; ///< Currently selected sampling rate. - int m_CurrentBufferSize; ///< Currently selected buffer size. - - ConnectionStates m_ConnectionStatus; ///< Status of device connection - bool m_IsActive; ///< Flag for teh active status. - bool m_IsStreaming; ///< Flag for streaming status. - std::vector<float> m_InputLevels; ///< List of input levels. - std::vector<float> m_OutputLevels; ///< List of output levels. - - int m_LeftMonitorChannel; ///< The device channel to use for monitoring left channel data. - int m_RightMonitorChannel; ///< The device channel to use for monitoring right channel data. - float m_MonitorGain; ///< Amount of gain to apply for monitoring signal. -}; - - -// This enum is for choosing filter for audio devices scan -typedef enum eAudioDeviceFilter -{ - eAllDevices = 0, // Choose all audio devices - eInputOnlyDevices, // Choose only input audio devices - eOutputOnlyDevices, // Choose only output audio devices - eFullDuplexDevices, // Choose audio devices that have both input and output channels on the same device - eMatchedDuplexDevices, // Match(aggregate) audio devices that have both input and output channels but are considered different audio devices (For mac) - eAudioDeviceFilterNum // Number of enums -} eAudioDeviceFilter; - - -class WCMRAudioDeviceManager : public WCRefManager -{ -public://< Public functions for the class. - - WCMRAudioDeviceManager(WCMRAudioDeviceManagerClient *pTheClient, eAudioDeviceFilter eCurAudioDeviceFilter); ///< constructor - virtual ~WCMRAudioDeviceManager(void); ///< Destructor - - //interfaces - WCMRAudioDevice* InitNewCurrentDevice(const std::string & deviceName); - void DestroyCurrentDevice(); - const DeviceInfoVec DeviceInfoList () const; - WTErr GetDeviceInfoByName(const std::string & nameToMatch, DeviceInfo & devInfo) const; - WTErr GetDeviceSampleRates(const std::string & nameToMatch, std::vector<int>& sampleRates) const; - WTErr GetDeviceBufferSizes(const std::string & nameToMatch, std::vector<int>& bufferSizes) const; - - //virtual void EnableVerboseLogging(bool /*bEnable*/, const std::string& /*logFilePath*/) { }; - - //notify backend - void NotifyClient (WCMRAudioDeviceManagerClient::NotificationReason forReason, void *pParam = NULL); - -protected: - - mutable wvNS::wvThread::ThreadMutex m_AudioDeviceInfoVecMutex; // mutex to lock device info list - DeviceInfoVec m_DeviceInfoVec; - - eAudioDeviceFilter m_eAudioDeviceFilter; - WCMRAudioDevice* m_CurrentDevice; - -private: - // override in derived classes - // made private to avoid pure virtual function call - virtual WCMRAudioDevice* initNewCurrentDeviceImpl(const std::string & deviceName) = 0; - virtual void destroyCurrentDeviceImpl() = 0; - virtual WTErr getDeviceSampleRatesImpl(const std::string & deviceName, std::vector<int>& sampleRates) const = 0; - virtual WTErr getDeviceBufferSizesImpl(const std::string & deviceName, std::vector<int>& bufferSizes) const = 0; - virtual WTErr generateDeviceListImpl() = 0; - virtual WTErr updateDeviceListImpl() = 0; - - WCMRAudioDeviceManagerClient *m_pTheClient; ///< The device manager's client, used to send notifications. -}; - -#endif //#ifndef __WCMRAudioDeviceManager_h_ diff --git a/libs/backends/wavesaudio/wavesapi/devicemanager/WCMRCoreAudioDeviceManager.cpp b/libs/backends/wavesaudio/wavesapi/devicemanager/WCMRCoreAudioDeviceManager.cpp deleted file mode 100644 index 2a9a9ba19f..0000000000 --- a/libs/backends/wavesaudio/wavesapi/devicemanager/WCMRCoreAudioDeviceManager.cpp +++ /dev/null @@ -1,3140 +0,0 @@ -//---------------------------------------------------------------------------------- -// -// Copyright (c) 2008 Waves Audio Ltd. All rights reserved. -// -//! \file WCMRCoreAudioDeviceManager.cpp -//! -//! WCMRCoreAudioDeviceManager and related class declarations -//! -//---------------------------------------------------------------------------------*/ -#include "WCMRCoreAudioDeviceManager.h" -#include <CoreServices/CoreServices.h> -#include "MiscUtils/safe_delete.h" -#include <sstream> -#include <syslog.h> - -// This flag is turned to 1, but it does not work with aggregated devices. -// due to problems with aggregated devices this flag is not functional there -#define ENABLE_DEVICE_CHANGE_LISTNER 1 - -#define PROPERTY_CHANGE_SLEEP_TIME_MILLISECONDS 10 -#define PROPERTY_CHANGE_TIMEOUT_SECONDS 5 -#define USE_IOCYCLE_TIMES 1 ///< Set this to 0 to use individual thread cpu measurement - -using namespace wvNS; -///< Supported Sample rates -static const double gAllSampleRates[] = -{ - 44100.0, 48000.0, 88200.0, 96000.0, 176400.0, 192000.0, -1 /* negative terminated list */ -}; - - -///< Default Supported Buffer Sizes. -static const int gAllBufferSizes[] = -{ - 32, 64, 96, 128, 192, 256, 512, 1024, 2048, -1 /* negative terminated list */ -}; - - -///< The default SR. -static const int DEFAULT_SR = 44100; -///< The default buffer size. -static const int DEFAULT_BUFFERSIZE = 1024; - -static const int NONE_DEVICE_ID = -1; - -///< Number of stalls to wait before notifying user... -static const int NUM_STALLS_FOR_NOTIFICATION = 2 * 50; // 2*50 corresponds to 2 * 50 x 42 ms idle timer - about 4 seconds. -static const int CHANGE_CHECK_COUNTER_PERIOD = 100; // 120 corresponds to 120 x 42 ms idle timer - about 4 seconds. - -#define AUHAL_OUTPUT_ELEMENT 0 -#define AUHAL_INPUT_ELEMENT 1 - -#include <sys/sysctl.h> - -static int getProcessorCount() -{ - int count = 1; - size_t size = sizeof(count); - - if (sysctlbyname("hw.ncpu", &count, &size, NULL, 0)) - return 1; - - //if something did not work, let's revert to a safe value... - if (count == 0) - count = 1; - - return count; -} - - -//********************************************************************************************** -// WCMRCoreAudioDevice::WCMRCoreAudioDevice -// -//! Constructor for the audio device. Opens the PA device and gets information about the device. -//! such as determining supported sampling rates, buffer sizes, and channel counts. -//! -//! \param *pManager : The audio device manager that's managing this device. -//! \param deviceID : The port audio device ID. -//! \param useMultithreading : Whether to use multi-threading for audio processing. Default is true. -//! -//! \return Nothing. -//! -//********************************************************************************************** -WCMRCoreAudioDevice::WCMRCoreAudioDevice (WCMRCoreAudioDeviceManager *pManager, AudioDeviceID deviceID, bool useMultithreading, bool bNocopy) - : WCMRNativeAudioDevice (pManager, useMultithreading, bNocopy) - , m_SampleCountAtLastIdle (0) - , m_StalledSampleCounter(0) - , m_SampleCounter(0) - , m_BufferSizeChangeRequested (0) - , m_BufferSizeChangeReported (0) - , m_ResetRequested (0) - , m_ResetReported (0) - , m_ResyncRequested (0) - , m_ResyncReported (0) - , m_SRChangeRequested (0) - , m_SRChangeReported (0) - , m_ChangeCheckCounter(0) - , m_IOProcThreadPort (0) - , m_DropsDetected(0) - , m_DropsReported(0) - , m_IgnoreThisDrop(true) - , m_LastCPULog(0) -#if WV_USE_TONE_GEN - , m_pToneData(0) - , m_ToneDataSamples (0) - , m_NextSampleToUse (0) -#endif //WV_USE_TONE_GEN -{ - AUTO_FUNC_DEBUG; - UInt32 propSize = 0; - OSStatus err = kAudioHardwareNoError; - - //Update device info... - m_DeviceID = deviceID; - - m_CurrentSamplingRate = DEFAULT_SR; - m_CurrentBufferSize = DEFAULT_BUFFERSIZE; - m_StopRequested = true; - m_pInputData = NULL; - - m_CPUCount = getProcessorCount(); - m_LastCPULog = wvThread::now() - 10 * wvThread::ktdOneSecond; - - - - /* - @constant kAudioDevicePropertyNominalSampleRate - A Float64 that indicates the current nominal sample rate of the AudioDevice. - */ - Float64 currentNominalRate; - propSize = sizeof (currentNominalRate); - err = kAudioHardwareNoError; - if (AudioDeviceGetProperty(m_DeviceID, 0, 0, kAudioDevicePropertyNominalSampleRate, &propSize, ¤tNominalRate) != kAudioHardwareNoError) - err = AudioDeviceGetProperty(m_DeviceID, 0, 1, kAudioDevicePropertyNominalSampleRate, &propSize, ¤tNominalRate); - - if (err == kAudioHardwareNoError) - m_CurrentSamplingRate = (int)currentNominalRate; - - /* - @constant kAudioDevicePropertyBufferFrameSize - A UInt32 whose value indicates the number of frames in the IO buffers. - */ - - UInt32 bufferSize; - propSize = sizeof (bufferSize); - err = kAudioHardwareNoError; - if (AudioDeviceGetProperty(m_DeviceID, 0, 0, kAudioDevicePropertyBufferFrameSize, &propSize, &bufferSize) != kAudioHardwareNoError) - err = AudioDeviceGetProperty(m_DeviceID, 0, 1, kAudioDevicePropertyBufferFrameSize, &propSize, &bufferSize); - - if (err == kAudioHardwareNoError) - m_CurrentBufferSize = (int)bufferSize; - - - UpdateDeviceInfo(); - - //should use a valid current SR... - if (m_SamplingRates.size()) - { - //see if the current sr is present in the sr list, if not, use the first one! - std::vector<int>::iterator intIter = find(m_SamplingRates.begin(), m_SamplingRates.end(), m_CurrentSamplingRate); - if (intIter == m_SamplingRates.end()) - { - //not found... use the first one - m_CurrentSamplingRate = m_SamplingRates[0]; - } - } - - //should use a valid current buffer size - if (m_BufferSizes.size()) - { - //see if the current sr is present in the buffersize list, if not, use the first one! - std::vector<int>::iterator intIter = find(m_BufferSizes.begin(), m_BufferSizes.end(), m_CurrentBufferSize); - if (intIter == m_BufferSizes.end()) - { - //not found... use the first one - m_CurrentBufferSize = m_BufferSizes[0]; - } - } - - //build our input/output level lists - for (unsigned int currentChannel = 0; currentChannel < m_InputChannels.size(); currentChannel++) - { - m_InputLevels.push_back (0.0); - } - - //build our input/output level lists - for (unsigned int currentChannel = 0; currentChannel < m_OutputChannels.size(); currentChannel++) - { - m_OutputLevels.push_back (0.0); - } - -} - - - -//********************************************************************************************** -// WCMRCoreAudioDevice::~WCMRCoreAudioDevice -// -//! Destructor for the audio device. The base release all the connections that were created, if -//! they have not been already destroyed! Here we simply stop streaming, and close device -//! handles if necessary. -//! -//! \param none -//! -//! \return Nothing. -//! -//********************************************************************************************** -WCMRCoreAudioDevice::~WCMRCoreAudioDevice () -{ - AUTO_FUNC_DEBUG; - - try - { - //If device is streaming, need to stop it! - if (Streaming()) - { - SetStreaming (false); - } - - //If device is active (meaning stream is open) we need to close it. - if (Active()) - { - SetActive (false); - } - - } - catch (...) - { - //destructors should absorb exceptions, no harm in logging though!! - DEBUG_MSG ("Exception during destructor"); - } - -} - - -//********************************************************************************************** -// WCMRCoreAudioDevice::UpdateDeviceInfo -// -//! Updates Device Information about channels, sampling rates, buffer sizes. -//! -//! \return WTErr. -//! -//********************************************************************************************** -WTErr WCMRCoreAudioDevice::UpdateDeviceInfo () -{ - AUTO_FUNC_DEBUG; - - WTErr retVal = eNoErr; - - // Some devices change the ID during restart - WTErr errId = UpdateDeviceId(); - - // Update all devices parts regardless of errors - WTErr errName = UpdateDeviceName(); - WTErr errIn = UpdateDeviceInputs(); - WTErr errOut = UpdateDeviceOutputs(); - WTErr errSR = eNoErr; - WTErr errBS = eNoErr; - - errSR = UpdateDeviceSampleRates(); - errBS = UpdateDeviceBufferSizes(); - - if(errId != eNoErr || errName != eNoErr || errIn != eNoErr || errOut != eNoErr || errSR != eNoErr || errBS != eNoErr) - { - retVal = eCoreAudioFailed; - } - - return retVal; -} - - -WTErr WCMRCoreAudioDevice::UpdateDeviceId() -{ - //Get device count... - UInt32 propSize = 0; - WTErr retVal = eNoErr; - OSStatus osErr = AudioHardwareGetPropertyInfo (kAudioHardwarePropertyDevices, &propSize, NULL); - ASSERT_ERROR(osErr, "AudioHardwareGetProperty 1"); - if (WUIsError(osErr)) - throw osErr; - - size_t numDevices = propSize / sizeof (AudioDeviceID); - AudioDeviceID* deviceIDs = new AudioDeviceID[numDevices]; - - //retrieve the device IDs - propSize = numDevices * sizeof (AudioDeviceID); - osErr = AudioHardwareGetProperty (kAudioHardwarePropertyDevices, &propSize, deviceIDs); - ASSERT_ERROR(osErr, "Error while getting audio devices: AudioHardwareGetProperty 2"); - if (WUIsError(osErr)) - throw osErr; - - //now add the ones that are not there... - for (size_t deviceIndex = 0; deviceIndex < numDevices; deviceIndex++) - { - DeviceInfo* pDevInfo = 0; - - //Get device name and create new DeviceInfo entry - //Get property name size. - osErr = AudioDeviceGetPropertyInfo(deviceIDs[deviceIndex], 0, 0, kAudioDevicePropertyDeviceName, &propSize, NULL); - if (osErr == kAudioHardwareNoError) - { - //Get property: name. - char* deviceName = new char[propSize]; - osErr = AudioDeviceGetProperty(deviceIDs[deviceIndex], 0, 0, kAudioDevicePropertyDeviceName, &propSize, deviceName); - if (osErr == kAudioHardwareNoError) - { - if ( (m_DeviceName == deviceName) && - (m_DeviceID != deviceIDs[deviceIndex]) ) { - - m_DeviceID = deviceIDs[deviceIndex]; - - m_pMyManager->NotifyClient (WCMRAudioDeviceManagerClient::DeviceDebugInfo, (void *)"Current device has changed it's id."); - } - } - else - { - retVal = eCoreAudioFailed; - DEBUG_MSG("Failed to get device name. Device ID: " << m_DeviceID); - } - - delete [] deviceName; - } - else - { - retVal = eCoreAudioFailed; - DEBUG_MSG("Failed to get device name prop Info. Device ID: " << m_DeviceID); - } - } - - delete [] deviceIDs; - return retVal; -} - - -//********************************************************************************************** -// WCMRCoreAudioDevice::UpdateDeviceName -// -//! Updates Device name. -//! -//! Use 'kAudioDevicePropertyDeviceName' -//! -//! 1. Get property name size. -//! 2. Get property: name. -//! -//! \return WTErr. -//! -//********************************************************************************************** -WTErr WCMRCoreAudioDevice::UpdateDeviceName() -{ - AUTO_FUNC_DEBUG; - WTErr retVal = eNoErr; - OSStatus err = kAudioHardwareNoError; - UInt32 propSize = 0; - - // Initiate name to unknown. - m_DeviceName = "Unknown"; - - //! 1. Get property name size. - err = AudioDeviceGetPropertyInfo(m_DeviceID, 0, 0, kAudioDevicePropertyDeviceName, &propSize, NULL); - if (err == kAudioHardwareNoError) - { - //! 2. Get property: name. - char* deviceName = new char[propSize]; - err = AudioDeviceGetProperty(m_DeviceID, 0, 0, kAudioDevicePropertyDeviceName, &propSize, deviceName); - if (err == kAudioHardwareNoError) - { - m_DeviceName = deviceName; - } - else - { - retVal = eCoreAudioFailed; - DEBUG_MSG("Failed to get device name. Device ID: " << m_DeviceID); - } - - delete [] deviceName; - } - else - { - retVal = eCoreAudioFailed; - DEBUG_MSG("Failed to get device name property size. Device ID: " << m_DeviceID); - } - - return retVal; -} - -//********************************************************************************************** -// WCMRCoreAudioDevice::UpdateDeviceInputs -// -//! Updates Device Inputs. -//! -//! Use 'kAudioDevicePropertyStreamConfiguration' -//! This property returns the stream configuration of the device in an -//! AudioBufferList (with the buffer pointers set to NULL) which describes the -//! list of streams and the number of channels in each stream. This corresponds -//! to what will be passed into the IOProc. -//! -//! 1. Get property cannels input size. -//! 2. Get property: cannels input. -//! 3. Update input channels -//! -//! \return WTErr. -//! -//********************************************************************************************** -WTErr WCMRCoreAudioDevice::UpdateDeviceInputs() -{ - AUTO_FUNC_DEBUG; - WTErr retVal = eNoErr; - OSStatus err = kAudioHardwareNoError; - UInt32 propSize = 0; - int maxInputChannels = 0; - - // 1. Get property cannels input size. - err = AudioDeviceGetPropertyInfo (m_DeviceID, 0, 1/* Input */, kAudioDevicePropertyStreamConfiguration, &propSize, NULL); - if (err == kAudioHardwareNoError) - { - //! 2. Get property: cannels input. - - // Allocate size according to the property size. Note that this is a variable sized struct... - AudioBufferList *pStreamBuffers = (AudioBufferList *)malloc(propSize); - - if (pStreamBuffers) - { - memset (pStreamBuffers, 0, propSize); - - // Get the Input channels - err = AudioDeviceGetProperty (m_DeviceID, 0, true/* Input */, kAudioDevicePropertyStreamConfiguration, &propSize, pStreamBuffers); - if (err == kAudioHardwareNoError) - { - // Calculate the number of input channels - for (UInt32 streamIndex = 0; streamIndex < pStreamBuffers->mNumberBuffers; streamIndex++) - { - maxInputChannels += pStreamBuffers->mBuffers[streamIndex].mNumberChannels; - } - } - else - { - retVal = eCoreAudioFailed; - DEBUG_MSG("Failed to get device Input channels. Device Name: " << m_DeviceName.c_str()); - } - - free (pStreamBuffers); - } - else - { - retVal = eMemOutOfMemory; - DEBUG_MSG("Faild to allocate memory. Device Name: " << m_DeviceName.c_str()); - } - } - else - { - retVal = eCoreAudioFailed; - DEBUG_MSG("Failed to get device Input channels property size. Device Name: " << m_DeviceName.c_str()); - } - - // Update input channels - m_InputChannels.clear(); - - for (int channel = 0; channel < maxInputChannels; channel++) - { - CFStringRef cfName; - std::stringstream chNameStream; - UInt32 nameSize = 0; - OSStatus error = kAudioHardwareNoError; - - error = AudioDeviceGetPropertyInfo (m_DeviceID, - channel + 1, - true /* Input */, - kAudioDevicePropertyChannelNameCFString, - &nameSize, - NULL); - - if (error == kAudioHardwareNoError) - { - error = AudioDeviceGetProperty (m_DeviceID, - channel + 1, - true /* Input */, - kAudioDevicePropertyChannelNameCFString, - &nameSize, - &cfName); - } - - bool decoded = false; - char* cstr_name = 0; - if (error == kAudioHardwareNoError) - { - CFIndex length = CFStringGetLength(cfName); - CFIndex maxSize = CFStringGetMaximumSizeForEncoding(length, kCFStringEncodingUTF8); - cstr_name = new char[maxSize]; - decoded = CFStringGetCString(cfName, cstr_name, maxSize, kCFStringEncodingUTF8); - } - - chNameStream << (channel+1) << " - "; - - if (cstr_name && decoded && (0 != std::strlen(cstr_name) ) ) { - chNameStream << cstr_name; - } - else - { - chNameStream << "Input " << (channel+1); - } - - m_InputChannels.push_back (chNameStream.str()); - - delete [] cstr_name; - } - - return retVal; -} - -//********************************************************************************************** -// WCMRCoreAudioDevice::UpdateDeviceOutputs -// -//! Updates Device Outputs. -//! -//! Use 'kAudioDevicePropertyStreamConfiguration' -//! This property returns the stream configuration of the device in an -//! AudioBufferList (with the buffer pointers set to NULL) which describes the -//! list of streams and the number of channels in each stream. This corresponds -//! to what will be passed into the IOProc. -//! -//! 1. Get property cannels output size. -//! 2. Get property: cannels output. -//! 3. Update output channels -//! -//! \return Nothing. -//! -//********************************************************************************************** -WTErr WCMRCoreAudioDevice::UpdateDeviceOutputs() -{ - AUTO_FUNC_DEBUG; - - WTErr retVal = eNoErr; - OSStatus err = kAudioHardwareNoError; - UInt32 propSize = 0; - int maxOutputChannels = 0; - - //! 1. Get property cannels output size. - err = AudioDeviceGetPropertyInfo (m_DeviceID, 0, 0/* Output */, kAudioDevicePropertyStreamConfiguration, &propSize, NULL); - if (err == kAudioHardwareNoError) - { - //! 2. Get property: cannels output. - - // Allocate size according to the property size. Note that this is a variable sized struct... - AudioBufferList *pStreamBuffers = (AudioBufferList *)malloc(propSize); - if (pStreamBuffers) - { - memset (pStreamBuffers, 0, propSize); - - // Get the Output channels - err = AudioDeviceGetProperty (m_DeviceID, 0, 0/* Output */, kAudioDevicePropertyStreamConfiguration, &propSize, pStreamBuffers); - if (err == kAudioHardwareNoError) - { - // Calculate the number of output channels - for (UInt32 streamIndex = 0; streamIndex < pStreamBuffers->mNumberBuffers; streamIndex++) - { - maxOutputChannels += pStreamBuffers->mBuffers[streamIndex].mNumberChannels; - } - } - else - { - retVal = eCoreAudioFailed; - DEBUG_MSG("Failed to get device Output channels. Device Name: " << m_DeviceName.c_str()); - } - free (pStreamBuffers); - } - else - { - retVal = eMemOutOfMemory; - DEBUG_MSG("Faild to allocate memory. Device Name: " << m_DeviceName.c_str()); - } - } - else - { - retVal = eCoreAudioFailed; - DEBUG_MSG("Failed to get device Output channels property size. Device Name: " << m_DeviceName.c_str()); - } - - // Update output channels - m_OutputChannels.clear(); - for (int channel = 0; channel < maxOutputChannels; channel++) - { - CFStringRef cfName; - std::stringstream chNameStream; - UInt32 nameSize = 0; - OSStatus error = kAudioHardwareNoError; - - error = AudioDeviceGetPropertyInfo (m_DeviceID, - channel + 1, - false /* Output */, - kAudioDevicePropertyChannelNameCFString, - &nameSize, - NULL); - - if (error == kAudioHardwareNoError) - { - error = AudioDeviceGetProperty (m_DeviceID, - channel + 1, - false /* Output */, - kAudioDevicePropertyChannelNameCFString, - &nameSize, - &cfName); - } - - bool decoded = false; - char* cstr_name = 0; - if (error == kAudioHardwareNoError ) - { - CFIndex length = CFStringGetLength(cfName); - CFIndex maxSize = CFStringGetMaximumSizeForEncoding(length, kCFStringEncodingUTF8); - cstr_name = new char[maxSize]; - decoded = CFStringGetCString(cfName, cstr_name, maxSize, kCFStringEncodingUTF8); - } - - chNameStream << (channel+1) << " - "; - - if (cstr_name && decoded && (0 != std::strlen(cstr_name) ) ) { - chNameStream << cstr_name; - } - else - { - chNameStream << "Output " << (channel+1); - } - - m_OutputChannels.push_back (chNameStream.str()); - - delete [] cstr_name; - } - - return retVal; -} - -//********************************************************************************************** -// WCMRCoreAudioDevice::UpdateDeviceSampleRates -// -//! Updates Device Sample rates. -//! -//! Use 'kAudioDevicePropertyAvailableNominalSampleRates' -//! -//! 1. Get sample rate property size. -//! 2. Get property: sample rates. -//! 3. Update sample rates -//! -//! \return Nothing. -//! -//********************************************************************************************** -WTErr WCMRCoreAudioDevice::UpdateDeviceSampleRates() -{ - AUTO_FUNC_DEBUG; - - WTErr retVal = eNoErr; - OSStatus err = kAudioHardwareNoError; - UInt32 propSize = 0; - - m_SamplingRates.clear(); - - //! 1. Get sample rate property size. - err = AudioDeviceGetPropertyInfo(m_DeviceID, 0, 0, kAudioDevicePropertyAvailableNominalSampleRates, &propSize, NULL); - if (err == kAudioHardwareNoError) - { - //! 2. Get property: cannels output. - - // Allocate size accrding to the number of audio values - int numRates = propSize / sizeof(AudioValueRange); - AudioValueRange* supportedRates = new AudioValueRange[numRates]; - - // Get sampling rates from Audio device - err = AudioDeviceGetProperty(m_DeviceID, 0, 0, kAudioDevicePropertyAvailableNominalSampleRates, &propSize, supportedRates); - if (err == kAudioHardwareNoError) - { - //! 3. Update sample rates - - // now iterate through our standard SRs - for(int ourSR=0; gAllSampleRates[ourSR] > 0; ourSR++) - { - //check to see if our SR is in the supported rates... - for (int deviceSR = 0; deviceSR < numRates; deviceSR++) - { - if ((supportedRates[deviceSR].mMinimum <= gAllSampleRates[ourSR]) && - (supportedRates[deviceSR].mMaximum >= gAllSampleRates[ourSR])) - { - m_SamplingRates.push_back ((int)gAllSampleRates[ourSR]); - break; - } - } - } - } - else - { - retVal = eCoreAudioFailed; - DEBUG_MSG("Failed to get device Sample rates. Device Name: " << m_DeviceName.c_str()); - } - - delete [] supportedRates; - } - else - { - retVal = eCoreAudioFailed; - DEBUG_MSG("Failed to get device Sample rates property size. Device Name: " << m_DeviceName.c_str()); - } - - return retVal; -} - - -//********************************************************************************************** -// WCMRCoreAudioDevice::UpdateDeviceBufferSizes_Simple -// -// Use kAudioDevicePropertyBufferFrameSizeRange -// -// in case of 'eMatchedDuplexDevices' and a matching device exists return common device name -// in all other cases retur base class function implementation -// -// 1. Get buffer size range -// 2. Run on all ranges and add them to the list -// -// \return error code -// -//********************************************************************************************** -WTErr WCMRCoreAudioDevice::UpdateDeviceBufferSizes () -{ - AUTO_FUNC_DEBUG; - - WTErr retVal = eNoErr; - OSStatus err = kAudioHardwareNoError; - UInt32 propSize = 0; - - // Clear buffer sizes - m_BufferSizes.clear(); - - // 1. Get buffer size range - AudioValueRange bufferSizesRange; - propSize = sizeof (AudioValueRange); - err = AudioDeviceGetProperty (m_DeviceID, 0, 0, kAudioDevicePropertyBufferFrameSizeRange, &propSize, &bufferSizesRange); - if(err == kAudioHardwareNoError) - { - // 2. Run on all ranges and add them to the list - for(int bsize=0; gAllBufferSizes[bsize] > 0; bsize++) - { - if ((bufferSizesRange.mMinimum <= gAllBufferSizes[bsize]) && (bufferSizesRange.mMaximum >= gAllBufferSizes[bsize])) - { - m_BufferSizes.push_back (gAllBufferSizes[bsize]); - } - } - - //if we didn't get a single hit, let's simply add the min. and the max... - if (m_BufferSizes.empty()) - { - m_BufferSizes.push_back ((int)bufferSizesRange.mMinimum); - m_BufferSizes.push_back ((int)bufferSizesRange.mMaximum); - } - } - else - { - retVal = eCoreAudioFailed; - DEBUG_MSG("Failed to get device buffer sizes range. Device Name: " << m_DeviceName.c_str()); - } - - return retVal; -} - - -//********************************************************************************************** -// WCMRCoreAudioDevice::DeviceName -// -//! in case of 'eMatchedDuplexDevices' and a matching device exists return common device name -//! in all other cases retur base class function implementation -//! -//! \param none -//! -//! \return current device name -//! -//********************************************************************************************** -const std::string& WCMRCoreAudioDevice::DeviceName() const -{ - return WCMRAudioDevice::DeviceName(); -} - -//********************************************************************************************** -// WCMRCoreAudioDevice::InputChannels -// -//! return base class function implementation -//! -//! \param none -//! -//! \return base class function implementation -//! -//********************************************************************************************** -const std::vector<std::string>& WCMRCoreAudioDevice::InputChannels() -{ - return WCMRAudioDevice::InputChannels(); -} - -//********************************************************************************************** -// WCMRCoreAudioDevice::OutputChannels -// -//! in case of 'eMatchedDuplexDevices' return matching device output channel if there is one -//! in all other cases retur base class function implementation -//! -//! \param none -//! -//! \return list of output channels of current device -//! -//********************************************************************************************** -const std::vector<std::string>& WCMRCoreAudioDevice::OutputChannels() -{ - return WCMRAudioDevice::OutputChannels(); -} - - -//********************************************************************************************** -// WCMRCoreAudioDevice::SamplingRates -// -//! in case of 'eMatchedDuplexDevices' and a matching device exists return common sample rate -//! in all other cases retur base class function implementation -//! -//! \param none -//! -//! \return current sample rate -//! -//********************************************************************************************** -const std::vector<int>& WCMRCoreAudioDevice::SamplingRates() -{ - return WCMRAudioDevice::SamplingRates(); -} - -//********************************************************************************************** -// WCMRCoreAudioDevice::CurrentSamplingRate -// -//! The device's current sampling rate. This may be overridden, if the device needs to -//! query the driver for the current rate. -//! -//! \param none -//! -//! \return The device's current sampling rate. -1 on error. -//! -//********************************************************************************************** -int WCMRCoreAudioDevice::CurrentSamplingRate () -{ - AUTO_FUNC_DEBUG; - //ToDo: Perhaps for ASIO devices that are active, we should retrive the SR from the device... - UInt32 propSize = 0; - OSStatus err = kAudioHardwareNoError; - - Float64 currentNominalRate; - propSize = sizeof (currentNominalRate); - err = kAudioHardwareNoError; - if (AudioDeviceGetProperty(m_DeviceID, 0, 0, kAudioDevicePropertyNominalSampleRate, &propSize, ¤tNominalRate) != kAudioHardwareNoError) - err = AudioDeviceGetProperty(m_DeviceID, 0, 1, kAudioDevicePropertyNominalSampleRate, &propSize, ¤tNominalRate); - - if (err == kAudioHardwareNoError) - m_CurrentSamplingRate = (int)currentNominalRate; - else - { - DEBUG_MSG("Unable to get sampling rate!"); - } - - return (m_CurrentSamplingRate); -} - - - - -//********************************************************************************************** -// WCMRCoreAudioDevice::SetCurrentSamplingRate -// -//! Change the sampling rate to be used by the device. -//! -//! \param newRate : The rate to use (samples per sec). -//! -//! \return eNoErr always. The derived classes may return error codes. -//! -//********************************************************************************************** -WTErr WCMRCoreAudioDevice::SetCurrentSamplingRate (int newRate) -{ - AUTO_FUNC_DEBUG; - std::vector<int>::iterator intIter; - WTErr retVal = eNoErr; - - //changes the status. - int oldRate = CurrentSamplingRate(); - bool oldActive = Active(); - - //no change, nothing to do - if (oldRate == newRate) - goto Exit; - - //see if this is one of our supported rates... - intIter = find(m_SamplingRates.begin(), m_SamplingRates.end(), newRate); - if (intIter == m_SamplingRates.end()) - { - //Can't change, perhaps use an "invalid param" type of error - retVal = eCommandLineParameter; - goto Exit; - } - - if (Streaming()) - { - //Can't change, perhaps use an "in use" type of error - retVal = eGenericErr; - goto Exit; - } - - if (oldActive) - { - //Deactivate it for the change... - SetActive (false); - } - - retVal = SetAndCheckCurrentSamplingRate (newRate); - if(retVal == eNoErr) - { - retVal = UpdateDeviceInfo (); - } - - //reactivate it. - if (oldActive) - { - retVal = SetActive (true); - } - -Exit: - - return (retVal); - -} - -//********************************************************************************************** -// WCMRCoreAudioDevice::SetAndCheckCurrentSamplingRate -// -//! Change the sampling rate to be used by the device. -//! -//! \param newRate : The rate to use (samples per sec). -//! -//! \return eNoErr always. The derived classes may return error codes. -//! -//********************************************************************************************** -WTErr WCMRCoreAudioDevice::SetAndCheckCurrentSamplingRate (int newRate) -{ - AUTO_FUNC_DEBUG; - std::vector<int>::iterator intIter; - WTErr retVal = eNoErr; - OSStatus err = kAudioHardwareNoError; - UInt32 propSize = 0; - - // 1. Set new sampling rate - Float64 newNominalRate = newRate; - propSize = sizeof (Float64); - err = AudioDeviceSetProperty(m_DeviceID, NULL, 0, 0, kAudioDevicePropertyNominalSampleRate, propSize, &newNominalRate); - - if (err != kAudioHardwareNoError) - { - retVal = eCoreAudioFailed; - DEBUG_MSG ("Unable to set SR! Device name: " << m_DeviceName.c_str()); - } - else - { - // 2. wait for the SR to actually change... - - // Set total time out time - int tryAgain = ((PROPERTY_CHANGE_TIMEOUT_SECONDS * 1000) / PROPERTY_CHANGE_SLEEP_TIME_MILLISECONDS) ; - int actualWait = 0; - Float64 actualSamplingRate = 0.0; - - // Run as ling as time out is not finished - while (tryAgain) - { - // Get current sampling rate - err = AudioDeviceGetProperty(m_DeviceID, 0, 0, kAudioDevicePropertyNominalSampleRate, &propSize, &actualSamplingRate); - if (err == kAudioHardwareNoError) - { - if (actualSamplingRate == newNominalRate) - { - //success, let's get out! - break; - } - } - else - { - //error reading rate, but let's not complain too much! - m_pMyManager->NotifyClient (WCMRAudioDeviceManagerClient::DeviceDebugInfo, (void *)"Could not read Sampling Rate for verification."); - DEBUG_MSG ("Unable to get SR. Device name: " << m_DeviceName.c_str()); - } - - // oh well...there's always another millisecond... - wvThread::sleep_milliseconds (PROPERTY_CHANGE_SLEEP_TIME_MILLISECONDS); - tryAgain--; - actualWait++; - } - - // If sample rate actually changed - if (tryAgain != 0) - { - m_pMyManager->NotifyClient (WCMRAudioDeviceManagerClient::DeviceDebugInfo, (void *)"Changed the Sampling Rate."); - - // Update member with new rate - m_CurrentSamplingRate = newRate; - - char debugMsg[128]; - snprintf (debugMsg, sizeof(debugMsg), "Actual Wait for SR Change was %d milliseconds", actualWait * PROPERTY_CHANGE_SLEEP_TIME_MILLISECONDS); - m_pMyManager->NotifyClient (WCMRAudioDeviceManagerClient::DeviceDebugInfo, (void *)debugMsg); - } - // If sample rate did not change after time out - else - { - // Check if current device sample rate is supported - bool found = false; - for(int i = 0; gAllSampleRates[i] > 0; i++) - { - if (fabs(gAllSampleRates[i] - actualSamplingRate) < 0.01) { - found = true; - } - } - - if (found) { - // Update member with last read value - m_CurrentSamplingRate = static_cast<int>(actualSamplingRate); - - char debugMsg[128]; - snprintf (debugMsg, sizeof(debugMsg), "Unable to change SR, even after waiting for %d milliseconds", actualWait * PROPERTY_CHANGE_SLEEP_TIME_MILLISECONDS); - m_pMyManager->NotifyClient (WCMRAudioDeviceManagerClient::DeviceDebugInfo, (void *)debugMsg); - - float sample_rate_update = actualSamplingRate; - m_pMyManager->NotifyClient (WCMRAudioDeviceManagerClient::SamplingRateChanged, (void *)&sample_rate_update); - } else { - retVal = eGenericErr; - } - } - } - - return (retVal); -} - - -//********************************************************************************************** -// WCMRCoreAudioDevice::BufferSizes -// -//! in case of 'eMatchedDuplexDevices' and a matching device exists return common buffer sizes -//! in all other cases retur base class function implementation -//! -//! \param none -//! -//! \return current sample rate -//! -//********************************************************************************************** -const std::vector<int>& WCMRCoreAudioDevice::BufferSizes() -{ - return WCMRAudioDevice::BufferSizes(); -} - - -//********************************************************************************************** -// WCMRCoreAudioDevice::CurrentBufferSize -// -//! The device's current buffer size in use. This may be overridden, if the device needs to -//! query the driver for the current size. -//! -//! \param none -//! -//! \return The device's current buffer size. 0 on error. -//! -//********************************************************************************************** -int WCMRCoreAudioDevice::CurrentBufferSize () -{ - AUTO_FUNC_DEBUG; - - return (m_CurrentBufferSize); -} - - - -//********************************************************************************************** -// WCMRCoreAudioDevice::SetCurrentBufferSize -// -//! Change the buffer size to be used by the device. This will most likely be overridden, -//! the base class simply updates the member variable. -//! -//! \param newSize : The buffer size to use (in sample-frames) -//! -//! \return eNoErr always. The derived classes may return error codes. -//! -//********************************************************************************************** -WTErr WCMRCoreAudioDevice::SetCurrentBufferSize (int newSize) -{ - AUTO_FUNC_DEBUG; - WTErr retVal = eNoErr; - std::vector<int>::iterator intIter; - - //changes the status. - int oldSize = CurrentBufferSize(); - bool oldActive = Active(); - - //same size, nothing to do. - if (oldSize == newSize) - goto Exit; - - if (Streaming()) - { - //Can't change, perhaps use an "in use" type of error - retVal = eGenericErr; - goto Exit; - } - - if (oldActive) - { - //Deactivate it for the change... - SetActive (false); - } - - // when audio device is inactive it is safe to set a working buffer size according to new buffer size - // if 'newSize' is not a valid buffer size, another valid buffer size will be set - retVal = SetWorkingBufferSize(newSize); - if(retVal != eNoErr) - { - DEBUG_MSG("Unable to set a working buffer size. Device Name: " << DeviceName().c_str()); - goto Exit; - } - - //reactivate it. - if (oldActive) - { - retVal = SetActive (true); - if(retVal != eNoErr) - { - DEBUG_MSG("Unable to activate device. Device Name: " << DeviceName().c_str()); - goto Exit; - } - } - -Exit: - - return (retVal); -} - -WTErr WCMRCoreAudioDevice::SetWorkingBufferSize(int newSize) -{ - AUTO_FUNC_DEBUG; - WTErr retVal = eNoErr; - OSStatus err = kAudioHardwareNoError; - - // 1. Set new buffer size - err = SetBufferSizesByIO(newSize); - - // If there's no error it means this buffer size is supported - if(err == kAudioHardwareNoError) - { - m_CurrentBufferSize = newSize; - } - // If there was an error it means that this buffer size was not supported - else - { - // In case the new buffer size could not be set, set another working buffer size - - // Run on all buffer sizes: - - // Try setting buffer sizes that are bigger then selected buffer size first, - // Since bigger buffer sizes usually work safer - for(std::vector<int>::const_iterator iter = m_BufferSizes.begin();iter != m_BufferSizes.end();++iter) - { - int nCurBS = *iter; - - if(nCurBS > newSize) - { - // Try setting current buffer size - err = SetBufferSizesByIO(nCurBS); - - // in case buffer size is valid - if(err == kAudioHardwareNoError) - { - // Set current buffer size - m_CurrentBufferSize = nCurBS; - break; - } - } - } - - // If bigger buffer sizes failed, go to smaller buffer sizes - if(err != kAudioHardwareNoError) - { - for(std::vector<int>::const_iterator iter = m_BufferSizes.begin();iter != m_BufferSizes.end();++iter) - { - int nCurBS = *iter; - - if(nCurBS < newSize) - { - // Try setting current buffer size - err = SetBufferSizesByIO(*iter); - - // in case buffer size is valid - if(err == kAudioHardwareNoError) - { - // Set current buffer size - m_CurrentBufferSize = *iter; - break; - } - } - } - } - - // Check if a valid buffer size was found - if(err == kAudioHardwareNoError) - { - // Notify that a different sample rate is set - char debugMsg[256]; - snprintf (debugMsg, sizeof(debugMsg), "Could not set buffer size: %d, Set buffer size to: %d.", newSize, m_CurrentBufferSize); - m_pMyManager->NotifyClient (WCMRAudioDeviceManagerClient::DeviceDebugInfo, (void *)debugMsg); - } - // if there was no buffer size that could be set - else - { - // Set the parameter buffer size by default, set a debug message - m_CurrentBufferSize = newSize; - DEBUG_MSG("Unable to set any buffer size. Device Name: " << m_DeviceName.c_str()); - } - } - - return retVal; -} - -OSStatus WCMRCoreAudioDevice::SetBufferSizesByIO(int newSize) -{ - OSStatus err = kAudioHardwareNoError; - - // 1. Set new buffer size - UInt32 bufferSize = (UInt32)newSize; - UInt32 propSize = sizeof (UInt32); - - // Set new buffer size to input - if (!m_InputChannels.empty()) - { - err = AudioDeviceSetProperty(m_DeviceID, NULL, 0, 1, kAudioDevicePropertyBufferFrameSize, propSize, &bufferSize); - } - else - { - err = AudioDeviceSetProperty(m_DeviceID, NULL, 0, 0, kAudioDevicePropertyBufferFrameSize, propSize, &bufferSize); - } - - return err; -} - -//********************************************************************************************** -// WCMRCoreAudioDevice::ConnectionStatus -// -//! Retrieves the device's current connection status. This will most likely be overridden, -//! in case some driver communication is required to query the status. -//! -//! \param none -//! -//! \return A ConnectionStates value. -//! -//********************************************************************************************** -WCMRCoreAudioDevice::ConnectionStates WCMRCoreAudioDevice::ConnectionStatus () -{ - AUTO_FUNC_DEBUG; - //ToDo: May want to do something more to extract the actual status! - return (m_ConnectionStatus); - -} - - -//********************************************************************************************** -// WCMRCoreAudioDevice::EnableAudioUnitIO -// -//! Sets up the AUHAL for IO, allowing changes to the devices to be used by the AudioUnit. -//! -//! \param none -//! -//! \return eNoErr on success, an error code on failure. -//! -//********************************************************************************************** -WTErr WCMRCoreAudioDevice::EnableAudioUnitIO() -{ - AUTO_FUNC_DEBUG; - WTErr retVal = eNoErr; - OSStatus err = kAudioHardwareNoError; - - UInt32 enableIO = 1; - if (!m_InputChannels.empty()) - { - /////////////// - //ENABLE IO (INPUT) - //You must enable the Audio Unit (AUHAL) for input - - //Enable input on the AUHAL - err = AudioUnitSetProperty(m_AUHALAudioUnit, - kAudioOutputUnitProperty_EnableIO, kAudioUnitScope_Input, - AUHAL_INPUT_ELEMENT, - &enableIO, sizeof(enableIO)); - - if (err) - { - DEBUG_MSG("Couldn't Enable IO on input scope of input element, error = " << err); - retVal = eGenericErr; - goto Exit; - } - } - - //disable Output on the AUHAL if there's no output - if (m_OutputChannels.empty()) - enableIO = 0; - else - enableIO = 1; - - err = AudioUnitSetProperty(m_AUHALAudioUnit, - kAudioOutputUnitProperty_EnableIO, kAudioUnitScope_Output, - AUHAL_OUTPUT_ELEMENT, - &enableIO, sizeof(enableIO)); - - if (err) - { - DEBUG_MSG("Couldn't Enable/Disable IO on output scope of output element, error = " << err); - retVal = eGenericErr; - goto Exit; - } - -Exit: - return retVal; -} - - -//********************************************************************************************** -// WCMRCoreAudioDevice::EnableListeners -// -//! Sets up listeners to listen for Audio Device property changes, so that app can be notified. -//! -//! \param none -//! -//! \return eNoErr on success, an error code on failure. -//! -//********************************************************************************************** -WTErr WCMRCoreAudioDevice::EnableListeners() -{ - AUTO_FUNC_DEBUG; - WTErr retVal = eNoErr; - OSStatus err = kAudioHardwareNoError; - - //listner for SR change... - err = AudioDeviceAddPropertyListener(m_DeviceID, 0, 0, kAudioDevicePropertyNominalSampleRate, - StaticPropertyChangeProc, this); - - if (err) - { - DEBUG_MSG("Couldn't Setup SR Property Listner, error = " << err); - retVal = eGenericErr; - goto Exit; - } - -#if ENABLE_DEVICE_CHANGE_LISTNER - { - //listner for device change... - - err = AudioDeviceAddPropertyListener (m_DeviceID, - kAudioPropertyWildcardChannel, - true, - kAudioDevicePropertyDeviceHasChanged, - StaticPropertyChangeProc, - this); - - if (err) - { - DEBUG_MSG("Couldn't Setup device change Property Listner, error = " << err); - retVal = eGenericErr; - goto Exit; - } - } -#endif //ENABLE_DEVICE_CHANGE_LISTNER - - //listner for dropouts... - err = AudioDeviceAddPropertyListener(m_DeviceID, 0, 0, kAudioDeviceProcessorOverload, - StaticPropertyChangeProc, this); - - if (err) - { - DEBUG_MSG("Couldn't Setup Processor Overload Property Listner, error = " << err); - retVal = eGenericErr; - goto Exit; - } - - -Exit: - return retVal; -} - - - -//********************************************************************************************** -// WCMRCoreAudioDevice::DisableListeners -// -//! Undoes the work done by EnableListeners -//! -//! \param none -//! -//! \return eNoErr on success, an error code on failure. -//! -//********************************************************************************************** -WTErr WCMRCoreAudioDevice::DisableListeners() -{ - AUTO_FUNC_DEBUG; - WTErr retVal = eNoErr; - OSStatus err = kAudioHardwareNoError; - - //listner for SR change... - err = AudioDeviceRemovePropertyListener(m_DeviceID, 0, 0, kAudioDevicePropertyNominalSampleRate, - StaticPropertyChangeProc); - - if (err) - { - DEBUG_MSG("Couldn't Cleanup SR Property Listner, error = " << err); - //not sure if we need to report this... - } - -#if ENABLE_DEVICE_CHANGE_LISTNER - { - err = AudioDeviceRemovePropertyListener (m_DeviceID, - kAudioPropertyWildcardChannel, - true/* Input */, - kAudioDevicePropertyDeviceHasChanged, - StaticPropertyChangeProc); - - if (err) - { - DEBUG_MSG("Couldn't Cleanup device input stream change Property Listner, error = " << err); - //not sure if we need to report this... - } - - } -#endif //ENABLE_DEVICE_CHANGE_LISTNER - - err = AudioDeviceRemovePropertyListener(m_DeviceID, 0, 0, kAudioDeviceProcessorOverload, - StaticPropertyChangeProc); - - if (err) - { - DEBUG_MSG("Couldn't Cleanup device change Property Listner, error = " << err); - //not sure if we need to report this... - } - - - return retVal; -} - - -//********************************************************************************************** -// WCMRCoreAudioDevice::StaticPropertyChangeProc -// -//! The property change function called (as a result of EnableListeners) when device properties change. -//! It calls upon the non-static PropertyChangeProc to do the work. -//! -//! \param inDevice : The audio device in question. -//! \param inChannel : The channel on which the property has change. -//! \param isInput : If the change is for Input. -//! \param inPropertyID : The property that has changed. -//! \param inClientData: What was passed when listener was enabled, in our case teh WCMRCoreAudioDevice object. -//! -//! \return 0 always. -//! -//********************************************************************************************** -OSStatus WCMRCoreAudioDevice::StaticPropertyChangeProc (AudioDeviceID /*inDevice*/, UInt32 /*inChannel*/, Boolean /*isInput*/, - AudioDevicePropertyID inPropertyID, void *inClientData) -{ - if (inClientData) - { - WCMRCoreAudioDevice* pCoreDevice = (WCMRCoreAudioDevice *)inClientData; - pCoreDevice->PropertyChangeProc (inPropertyID); - } - - return 0; -} - - - -//********************************************************************************************** -// WCMRCoreAudioDevice::PropertyChangeProc -// -//! The non-static property change proc. Gets called when properties change. Since this gets called -//! on an arbitrary thread, we simply update the request counters and return. -//! -//! \param none -//! -//! \return nothing. -//! -//********************************************************************************************** -void WCMRCoreAudioDevice::PropertyChangeProc (AudioDevicePropertyID inPropertyID) -{ - switch (inPropertyID) - { - case kAudioDevicePropertyNominalSampleRate: - m_SRChangeRequested++; - break; -#if ENABLE_DEVICE_CHANGE_LISTNER - case kAudioDevicePropertyDeviceHasChanged: - { - m_ResetRequested++; - m_pMyManager->NotifyClient (WCMRAudioDeviceManagerClient::RequestReset); - } - break; -#endif //ENABLE_DEVICE_CHANGE_LISTNER - case kAudioDeviceProcessorOverload: - { - if (m_IgnoreThisDrop) - m_IgnoreThisDrop = false; //We'll ignore once, just once! - else - m_DropsDetected++; - m_pMyManager->NotifyClient (WCMRAudioDeviceManagerClient::Dropout ); - break; - } - default: - break; - } -} - - -//********************************************************************************************** -// WCMRCoreAudioDevice::SetupAUHAL -// -//! Sets up the AUHAL AudioUnit for device IO. -//! -//! \param none -//! -//! \return eNoErr on success, an error code on failure. -//! -//********************************************************************************************** -WTErr WCMRCoreAudioDevice::SetupAUHAL() -{ - AUTO_FUNC_DEBUG; - WTErr retVal = eNoErr; - OSStatus err = kAudioHardwareNoError; - UInt32 propSize = 0; - Component comp; - ComponentDescription desc; - AudioStreamBasicDescription streamFormatToUse, auhalStreamFormat; - - //There are several different types of Audio Units. - //Some audio units serve as Outputs, Mixers, or DSP - //units. See AUComponent.h for listing - desc.componentType = kAudioUnitType_Output; - - //Every Component has a subType, which will give a clearer picture - //of what this components function will be. - desc.componentSubType = kAudioUnitSubType_HALOutput; - - //all Audio Units in AUComponent.h must use - //"kAudioUnitManufacturer_Apple" as the Manufacturer - desc.componentManufacturer = kAudioUnitManufacturer_Apple; - desc.componentFlags = 0; - desc.componentFlagsMask = 0; - - //Finds a component that meets the desc spec's - comp = FindNextComponent(NULL, &desc); - if (comp == NULL) - { - DEBUG_MSG("Couldn't find AUHAL Component"); - retVal = eGenericErr; - goto Exit; - } - - //gains access to the services provided by the component - OpenAComponent(comp, &m_AUHALAudioUnit); - - - retVal = EnableAudioUnitIO(); - if (retVal != eNoErr) - goto Exit; - - //Now setup the device to use by the audio unit... - - //input - if (!m_InputChannels.empty()) - { - err = AudioUnitSetProperty(m_AUHALAudioUnit, kAudioOutputUnitProperty_CurrentDevice, - kAudioUnitScope_Global, AUHAL_INPUT_ELEMENT, - &m_DeviceID, sizeof(m_DeviceID)); - - if (err) - { - DEBUG_MSG("Couldn't Set the audio device property for Input Element Global scope, error = " << err); - retVal = eGenericErr; - goto Exit; - } - } - - //output - if (!m_OutputChannels.empty()) - { - err = AudioUnitSetProperty(m_AUHALAudioUnit, kAudioOutputUnitProperty_CurrentDevice, - kAudioUnitScope_Global, AUHAL_OUTPUT_ELEMENT, - &m_DeviceID, sizeof(m_DeviceID)); - - if (err) - { - DEBUG_MSG("Couldn't Set the audio device property for Output Element Global scope, error = " << err); - retVal = eGenericErr; - goto Exit; - } - } - - //also set Sample Rate... - { - retVal = SetAndCheckCurrentSamplingRate(m_CurrentSamplingRate); - if(retVal != eNoErr) - { - DEBUG_MSG ("Unable to set SR, error = " << err); - goto Exit; - } - } - - //now set the buffer size... - { - err = SetWorkingBufferSize(m_CurrentBufferSize); - if (err) - { - DEBUG_MSG("Couldn't Set the buffer size property, error = " << err); - //we don't really quit here..., just keep going even if this does not work, - //the AUHAL is supposed to take care of this by way of slicing... - m_pMyManager->NotifyClient (WCMRAudioDeviceManagerClient::DeviceDebugInfo, (void *)"Could not set buffer size."); - - } - } - - //convertor quality - { - UInt32 quality = kAudioConverterQuality_Max; - propSize = sizeof (quality); - err = AudioUnitSetProperty(m_AUHALAudioUnit, - kAudioUnitProperty_RenderQuality, kAudioUnitScope_Global, - AUHAL_OUTPUT_ELEMENT, - &quality, sizeof (quality)); - - if (err != kAudioHardwareNoError) - { - DEBUG_MSG ("Unable to set Convertor Quality, error = " << err); - retVal = eGenericErr; - goto Exit; - } - } - - memset (&auhalStreamFormat, 0, sizeof (auhalStreamFormat)); - propSize = sizeof (auhalStreamFormat); - err = AudioUnitGetProperty(m_AUHALAudioUnit, - kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input, - AUHAL_INPUT_ELEMENT, - &auhalStreamFormat, &propSize); - if (err != kAudioHardwareNoError) - { - DEBUG_MSG ("Unable to get Input format, error = " << err); - retVal = eGenericErr; - goto Exit; - } - - if (auhalStreamFormat.mSampleRate != (Float64)m_CurrentSamplingRate) - { - TRACE_MSG ("AUHAL's Input SR differs from expected SR, expected = " << m_CurrentSamplingRate << ", AUHAL's = " << (UInt32)auhalStreamFormat.mSampleRate); - } - - //format, and slice size... - memset (&streamFormatToUse, 0, sizeof (streamFormatToUse)); - streamFormatToUse.mFormatID = kAudioFormatLinearPCM; - streamFormatToUse.mFormatFlags = kAudioFormatFlagsNativeFloatPacked; - streamFormatToUse.mFramesPerPacket = 1; - streamFormatToUse.mBitsPerChannel = sizeof (float) * 8; - streamFormatToUse.mSampleRate = auhalStreamFormat.mSampleRate; - - if (!m_InputChannels.empty()) - { - streamFormatToUse.mChannelsPerFrame = m_InputChannels.size(); - streamFormatToUse.mBytesPerFrame = sizeof (float)*streamFormatToUse.mChannelsPerFrame; - streamFormatToUse.mBytesPerPacket = streamFormatToUse.mBytesPerFrame; - propSize = sizeof (streamFormatToUse); - err = AudioUnitSetProperty(m_AUHALAudioUnit, - kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, - AUHAL_INPUT_ELEMENT, - &streamFormatToUse, sizeof (streamFormatToUse)); - - if (err != kAudioHardwareNoError) - { - DEBUG_MSG ("Unable to set Input format, error = " << err); - retVal = eGenericErr; - goto Exit; - } - - UInt32 bufferSize = m_CurrentBufferSize; - err = AudioUnitSetProperty(m_AUHALAudioUnit, - kAudioUnitProperty_MaximumFramesPerSlice, kAudioUnitScope_Output, - AUHAL_INPUT_ELEMENT, - &bufferSize, sizeof (bufferSize)); - - if (err != kAudioHardwareNoError) - { - DEBUG_MSG ("Unable to set Input frames, error = " << err); - retVal = eGenericErr; - goto Exit; - } - - } - - if (!m_OutputChannels.empty()) - { - err = AudioUnitGetProperty(m_AUHALAudioUnit, - kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, - AUHAL_OUTPUT_ELEMENT, - &auhalStreamFormat, &propSize); - if (err != kAudioHardwareNoError) - { - DEBUG_MSG ("Unable to get Output format, error = " << err); - retVal = eGenericErr; - goto Exit; - } - - if (auhalStreamFormat.mSampleRate != (Float64)m_CurrentSamplingRate) - { - TRACE_MSG ("AUHAL's Output SR differs from expected SR, expected = " << m_CurrentSamplingRate << ", AUHAL's = " << (UInt32)auhalStreamFormat.mSampleRate); - } - - - streamFormatToUse.mChannelsPerFrame = m_OutputChannels.size(); - streamFormatToUse.mBytesPerFrame = sizeof (float)*streamFormatToUse.mChannelsPerFrame; - streamFormatToUse.mBytesPerPacket = streamFormatToUse.mBytesPerFrame; - streamFormatToUse.mSampleRate = auhalStreamFormat.mSampleRate; - propSize = sizeof (streamFormatToUse); - err = AudioUnitSetProperty(m_AUHALAudioUnit, - kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input, - AUHAL_OUTPUT_ELEMENT, - &streamFormatToUse, sizeof (streamFormatToUse)); - - if (err != kAudioHardwareNoError) - { - DEBUG_MSG ("Unable to set Output format, error = " << err); - retVal = eGenericErr; - goto Exit; - } - - UInt32 bufferSize = m_CurrentBufferSize; - err = AudioUnitSetProperty(m_AUHALAudioUnit, - kAudioUnitProperty_MaximumFramesPerSlice, kAudioUnitScope_Input, - AUHAL_OUTPUT_ELEMENT, - &bufferSize, sizeof (bufferSize)); - - if (err != kAudioHardwareNoError) - { - DEBUG_MSG ("Unable to set Output frames, error = " << err); - retVal = eGenericErr; - goto Exit; - } - - } - - //setup callback (IOProc) - { - AURenderCallbackStruct renderCallback; - memset (&renderCallback, 0, sizeof (renderCallback)); - propSize = sizeof (renderCallback); - renderCallback.inputProc = StaticAudioIOProc; - renderCallback.inputProcRefCon = this; - - err = AudioUnitSetProperty(m_AUHALAudioUnit, - (m_OutputChannels.empty() ? (AudioUnitPropertyID)kAudioOutputUnitProperty_SetInputCallback : (AudioUnitPropertyID)kAudioUnitProperty_SetRenderCallback), - kAudioUnitScope_Output, - m_OutputChannels.empty() ? AUHAL_INPUT_ELEMENT : AUHAL_OUTPUT_ELEMENT, - &renderCallback, sizeof (renderCallback)); - - if (err != kAudioHardwareNoError) - { - DEBUG_MSG ("Unable to set callback, error = " << err); - retVal = eGenericErr; - goto Exit; - } - } - - retVal = EnableListeners(); - if (retVal != eNoErr) - goto Exit; - - //initialize the audio-unit now! - err = AudioUnitInitialize(m_AUHALAudioUnit); - if (err != kAudioHardwareNoError) - { - DEBUG_MSG ("Unable to Initialize AudioUnit = " << err); - retVal = eGenericErr; - goto Exit; - } - -Exit: - if (retVal != eNoErr) - TearDownAUHAL(); - - return retVal; -} - - - -//********************************************************************************************** -// WCMRCoreAudioDevice::TearDownAUHAL -// -//! Undoes the work done by SetupAUHAL -//! -//! \param none -//! -//! \return eNoErr on success, an error code on failure. -//! -//********************************************************************************************** -WTErr WCMRCoreAudioDevice::TearDownAUHAL() -{ - WTErr retVal = eNoErr; - - if (m_AUHALAudioUnit) - { - DisableListeners (); - AudioUnitUninitialize(m_AUHALAudioUnit); - CloseComponent(m_AUHALAudioUnit); - m_AUHALAudioUnit = NULL; - } - - return retVal; -} - - -//********************************************************************************************** -// WCMRCoreAudioDevice::SetActive -// -//! Sets the device's activation status. Essentially, opens or closes the PA device. -//! If it's an ASIO device it may result in buffer size change in some cases. -//! -//! \param newState : Should be true to activate, false to deactivate. This roughly corresponds -//! to opening and closing the device handle/stream/audio unit. -//! -//! \return eNoErr on success, an error code otherwise. -//! -//********************************************************************************************** -WTErr WCMRCoreAudioDevice::SetActive (bool newState) -{ - AUTO_FUNC_DEBUG; - - WTErr retVal = eNoErr; - - if (Active() == newState) - goto Exit; - - - if (newState) - { - m_pMyManager->NotifyClient (WCMRAudioDeviceManagerClient::DeviceDebugInfo, (void *)"Setting up AUHAL."); - retVal = SetupAUHAL(); - - if (retVal != eNoErr) - goto Exit; - - m_BufferSizeChangeRequested = 0; - m_BufferSizeChangeReported = 0; - m_ResetRequested = 0; - m_ResetReported = 0; - m_ResyncRequested = 0; - m_ResyncReported = 0; - m_SRChangeRequested = 0; - m_SRChangeReported = 0; - m_DropsDetected = 0; - m_DropsReported = 0; - m_IgnoreThisDrop = true; - } - else - { - if (Streaming()) - { - SetStreaming (false); - } - - m_pMyManager->NotifyClient (WCMRAudioDeviceManagerClient::DeviceDebugInfo, (void *)"Tearing down AUHAL."); - retVal = TearDownAUHAL(); - if (retVal != eNoErr) - goto Exit; - - m_BufferSizeChangeRequested = 0; - m_BufferSizeChangeReported = 0; - m_ResetRequested = 0; - m_ResetReported = 0; - m_ResyncRequested = 0; - m_ResyncReported = 0; - m_SRChangeRequested = 0; - m_SRChangeReported = 0; - m_DropsDetected = 0; - m_DropsReported = 0; - m_IgnoreThisDrop = true; - - UpdateDeviceInfo(); - } - - m_IsActive = newState; - -Exit: - return (retVal); -} - - -#if WV_USE_TONE_GEN -//********************************************************************************************** -// WCMRCoreAudioDevice::SetupToneGenerator -// -//! Sets up the Tone generator - only if a file /tmp/tonegen.txt is present. If the file is -//! present, it reads the value in the file and uses that as the frequency for the tone. This -//! code attempts to create an array of samples that would constitute an integral number of -//! cycles - for the currently active sampling rate. If tonegen is active, then the input -//! from the audio device is ignored, instead a data is supplied from the tone generator's -//! array - for all channels. The array is in m_pToneData, the size of the array is in -//! m_ToneDataSamples, and m_NextSampleToUse holds the index in the array from where -//! the next sample is going to be taken. -//! -//! -//! \return : Nothing -//! -//********************************************************************************************** -void WCMRCoreAudioDevice::SetupToneGenerator () -{ - safe_delete_array(m_pToneData); - m_ToneDataSamples = 0; - - //if tonegen exists? - FILE *toneGenHandle = fopen ("/tmp/tonegen.txt", "r"); - if (toneGenHandle) - { - int toneFreq = 0; - fscanf(toneGenHandle, "%d", &toneFreq); - if ((toneFreq <= 0) || (toneFreq > (m_CurrentSamplingRate/2))) - { - toneFreq = 1000; - } - - - m_ToneDataSamples = m_CurrentSamplingRate / toneFreq; - int toneDataSamplesFrac = m_CurrentSamplingRate % m_ToneDataSamples; - int powerOfTen = 1; - while (toneDataSamplesFrac) - { - m_ToneDataSamples = (uint32_t)((pow(10, powerOfTen) * m_CurrentSamplingRate) / toneFreq); - toneDataSamplesFrac = m_CurrentSamplingRate % m_ToneDataSamples; - powerOfTen++; - } - - //allocate - m_pToneData = new float_t[m_ToneDataSamples]; - - //fill with a -6dB Sine Tone - uint32_t numSamplesLeft = m_ToneDataSamples; - float_t *pNextSample = m_pToneData; - double phase = 0; - double phaseIncrement = (M_PI * 2.0 * toneFreq ) / ((double)m_CurrentSamplingRate); - while (numSamplesLeft) - { - *pNextSample = (float_t)(0.5 * sin(phase)); - phase += phaseIncrement; - pNextSample++; - numSamplesLeft--; - } - - m_NextSampleToUse = 0; - - fclose(toneGenHandle); - } -} -#endif //WV_USE_TONE_GEN - - -//********************************************************************************************** -// WCMRCoreAudioDevice::SetStreaming -// -//! Sets the device's streaming status. Calls PA's Start/Stop stream routines. -//! -//! \param newState : Should be true to start streaming, false to stop streaming. This roughly -//! corresponds to calling Start/Stop on the lower level interface. -//! -//! \return eNoErr always, the derived classes may return appropriate error code. -//! -//********************************************************************************************** -WTErr WCMRCoreAudioDevice::SetStreaming (bool newState) -{ - AUTO_FUNC_DEBUG; - WTErr retVal = eNoErr; - ComponentResult err = 0; - - if (Streaming () == newState) - goto Exit; - - if (newState) - { -#if WV_USE_TONE_GEN - SetupToneGenerator (); -#endif //WV_USE_TONE_GEN - - m_SampleCountAtLastIdle = 0; - m_StalledSampleCounter = 0; - m_SampleCounter = 0; - m_IOProcThreadPort = 0; - m_pMyManager->NotifyClient (WCMRAudioDeviceManagerClient::DeviceDebugInfo, (void *)"Starting AUHAL."); - - // Prepare for streaming - tell Engine to do the initialization for process callback - m_pMyManager->NotifyClient (WCMRAudioDeviceManagerClient::DeviceStartsStreaming); - - if (m_UseMultithreading) - { - //set thread constraints... - unsigned int periodAndConstraintUS = (unsigned int)((1000000.0 * m_CurrentBufferSize) / m_CurrentSamplingRate); - unsigned int computationUS = (unsigned int)(0.8 * periodAndConstraintUS); //assuming we may want to use up to 80% CPU - //ErrandManager().SetRealTimeConstraintsForAllThreads (periodAndConstraintUS, computationUS, periodAndConstraintUS); - } - - err = AudioOutputUnitStart (m_AUHALAudioUnit); - - m_StopRequested = false; - - if(err) - { - DEBUG_MSG( "Failed to start AudioUnit, err " << err ); - m_pMyManager->NotifyClient (WCMRAudioDeviceManagerClient::DeviceDebugInfo, (void *)"Failed to start AudioUnit."); - retVal = eGenericErr; - goto Exit; - } - } - else - { - m_StopRequested = true; - m_pMyManager->NotifyClient (WCMRAudioDeviceManagerClient::DeviceDebugInfo, (void *)"Stopping AUHAL."); - err = AudioOutputUnitStop (m_AUHALAudioUnit); - if (!err) - { - //if (!m_InputChannels.empty()); - { - err = AudioUnitReset (m_AUHALAudioUnit, kAudioUnitScope_Global, AUHAL_INPUT_ELEMENT); - } - //if (!m_OutputChannels.empty()); - { - err = AudioUnitReset (m_AUHALAudioUnit, kAudioUnitScope_Global, AUHAL_OUTPUT_ELEMENT); - } - } - - if(err) - { - DEBUG_MSG( "Failed to stop AudioUnit " << err ); - retVal = eGenericErr; - goto Exit; - } - m_IOProcThreadPort = 0; - } - - // After units restart, reset request for reset and SR change - m_SRChangeReported = m_SRChangeRequested; - m_ResetReported = m_ResetRequested; - - m_IsStreaming = newState; - -Exit: - return (retVal); -} - - -//********************************************************************************************** -// WCMRCoreAudioDevice::DoIdle -// -//! A place for doing idle time processing. The other derived classes will probably do something -//! meaningful. -//! -//! \param none -//! -//! \return eNoErr always. -//! -//********************************************************************************************** -WTErr WCMRCoreAudioDevice::DoIdle () -{ - /* - if (m_BufferSizeChangeRequested != m_BufferSizeChangeReported) - { - m_pMyManager->NotifyClient (WCMRAudioDeviceManagerClient::BufferSizeChanged); - m_BufferSizeChangeReported = m_BufferSizeChangeRequested; - } - - if (m_ResetRequested != m_ResetReported) - { - m_pMyManager->NotifyClient (WCMRAudioDeviceManagerClient::RequestReset); - m_ResetReported = m_ResetRequested; - } - - - if (m_ResyncRequested != m_ResyncReported) - { - m_pMyManager->NotifyClient (WCMRAudioDeviceManagerClient::RequestResync); - m_ResyncReported = m_ResyncRequested; - } - - if (m_SRChangeReported != m_SRChangeRequested) - { - m_SRChangeReported = m_SRChangeRequested; - int newSR = CurrentSamplingRate(); - m_pMyManager->NotifyClient (WCMRAudioDeviceManagerClient::SamplingRateChanged, (void *)newSR); - } - - if (m_DropsReported != m_DropsDetected) - { - m_pMyManager->NotifyClient (WCMRAudioDeviceManagerClient::DeviceDroppedSamples); - m_DropsReported = m_DropsDetected; - } - - - //Perhaps add checks to make sure a stream counter is incrementing if - //stream is supposed to be streaming! - if (Streaming()) - { - //latch the value - int64_t currentSampleCount = m_SampleCounter; - if (m_SampleCountAtLastIdle == currentSampleCount) - m_StalledSampleCounter++; - else - { - m_SampleCountAtLastIdle = (int)currentSampleCount; - m_StalledSampleCounter = 0; - } - - if (m_StalledSampleCounter > NUM_STALLS_FOR_NOTIFICATION) - { - m_StalledSampleCounter = 0; - m_pMyManager->NotifyClient (WCMRAudioDeviceManagerClient::DeviceStoppedStreaming, (void *)currentSampleCount); - } - }*/ - - - return (eNoErr); -} - - - - - -//********************************************************************************************** -// WCMRCoreAudioDevice::SetMonitorChannels -// -//! Used to set the channels to be used for monitoring. -//! -//! \param leftChannel : Left monitor channel index. -//! \param rightChannel : Right monitor channel index. -//! -//! \return eNoErr always, the derived classes may return appropriate errors. -//! -//********************************************************************************************** -WTErr WCMRCoreAudioDevice::SetMonitorChannels (int leftChannel, int rightChannel) -{ - AUTO_FUNC_DEBUG; - //This will most likely be overridden, the base class simply - //changes the member. - m_LeftMonitorChannel = leftChannel; - m_RightMonitorChannel = rightChannel; - return (eNoErr); -} - - - -//********************************************************************************************** -// WCMRCoreAudioDevice::SetMonitorGain -// -//! Used to set monitor gain (or atten). -//! -//! \param newGain : The new gain or atten. value to use. Specified as a linear multiplier (not dB) -//! -//! \return eNoErr always, the derived classes may return appropriate errors. -//! -//********************************************************************************************** -WTErr WCMRCoreAudioDevice::SetMonitorGain (float newGain) -{ - AUTO_FUNC_DEBUG; - //This will most likely be overridden, the base class simply - //changes the member. - - - m_MonitorGain = newGain; - return (eNoErr); -} - - - - -//********************************************************************************************** -// WCMRCoreAudioDevice::ShowConfigPanel -// -//! Used to show device specific config/control panel. Some interfaces may not support it. -//! Some interfaces may require the device to be active before it can display a panel. -//! -//! \param pParam : A device/interface specific parameter, should be the app window handle for ASIO. -//! -//! \return eNoErr always, the derived classes may return errors. -//! -//********************************************************************************************** -WTErr WCMRCoreAudioDevice::ShowConfigPanel (void */*pParam*/) -{ - AUTO_FUNC_DEBUG; - WTErr retVal = eNoErr; - - CFStringRef configAP; - UInt32 propSize = sizeof (configAP); - /* - @constant kAudioDevicePropertyConfigurationApplication - A CFString that contains the bundle ID for an application that provides a - GUI for configuring the AudioDevice. By default, the value of this property - is the bundle ID for Audio MIDI Setup. The caller is responsible for - releasing the returned CFObject. - */ - - if (AudioDeviceGetProperty(m_DeviceID, 0, 0, kAudioDevicePropertyConfigurationApplication, &propSize, &configAP) == kAudioHardwareNoError) - { - // get the FSRef of the config app - FSRef theAppFSRef; - OSStatus theError = LSFindApplicationForInfo(kLSUnknownCreator, configAP, NULL, &theAppFSRef, NULL); - if (!theError) - { - LSOpenFSRef(&theAppFSRef, NULL); - } - else - { - // open default AudioMIDISetup if device app is not found - CFStringRef audiMidiSetupApp = CFStringCreateWithCString(kCFAllocatorDefault, "com.apple.audio.AudioMIDISetup", kCFStringEncodingMacRoman); - theError = LSFindApplicationForInfo(kLSUnknownCreator, audiMidiSetupApp, NULL, &theAppFSRef, NULL); - - if (!theError) - { - LSOpenFSRef(&theAppFSRef, NULL); - } - } - - CFRelease (configAP); - } - - return (retVal); -} - - -//********************************************************************************************** -// WCMRCoreAudioDevice::StaticAudioIOProc -// -//! The AudioIOProc that gets called when the AudioUnit is ready with recorded audio, and wants to get audio. -//! This one simply calls the non-static member. -//! -//! \param inRefCon : What was passed when setting up the Callback (in our case a pointer to teh WCMRCoreAudioDevice object). -//! \param ioActionFlags : What actios has to be taken. -//! \param inTimeStamp: When the data will be played back. -//! \param inBusNumber : The AU element. -//! \param inNumberFrames: Number af Audio frames that are requested. -//! \param ioData : Where the playback data is to be placed. -//! -//! \return 0 always -//! -//********************************************************************************************** -OSStatus WCMRCoreAudioDevice::StaticAudioIOProc(void *inRefCon, AudioUnitRenderActionFlags * ioActionFlags, - const AudioTimeStamp *inTimeStamp, UInt32 inBusNumber, UInt32 inNumberFrames, - AudioBufferList *ioData) -{ - WCMRCoreAudioDevice *pMyDevice = (WCMRCoreAudioDevice *)inRefCon; - if (pMyDevice) - return pMyDevice->AudioIOProc (ioActionFlags, inTimeStamp, inBusNumber, inNumberFrames, ioData); - else - return 0; -} - - - - -//********************************************************************************************** -// WCMRCoreAudioDevice::AudioIOProc -// -//! The non-static AudioIOProc that gets called when the AudioUnit is ready with recorded audio, and wants to get audio. -//! We retrieve the recorded audio, and then do our processing, to generate audio to be played back. -//! -//! \param ioActionFlags : What actios has to be taken. -//! \param inTimeStamp: When the data will be played back. -//! \param inBusNumber : The AU element. -//! \param inNumberFrames: Number af Audio frames that are requested. -//! \param ioData : Where the playback data is to be placed. -//! -//! \return 0 always -//! -//********************************************************************************************** -OSStatus WCMRCoreAudioDevice::AudioIOProc(AudioUnitRenderActionFlags * ioActionFlags, - const AudioTimeStamp *inTimeStamp, UInt32 /*inBusNumber*/, UInt32 inNumberFrames, - AudioBufferList *ioData) -{ - UInt64 theStartTime = AudioGetCurrentHostTime(); - - OSStatus retVal = 0; - - if (m_StopRequested) - return retVal; - - if (m_IOProcThreadPort == 0) - m_IOProcThreadPort = mach_thread_self (); - - //cannot really deal with it unless the number of frames are the same as our buffer size! - if (inNumberFrames != (UInt32)m_CurrentBufferSize) - return retVal; - - //Retrieve the input data... - if (!m_InputChannels.empty()) - { - UInt32 expectedDataSize = m_InputChannels.size() * m_CurrentBufferSize * sizeof(float); - AudioBufferList inputAudioBufferList; - inputAudioBufferList.mNumberBuffers = 1; - inputAudioBufferList.mBuffers[0].mNumberChannels = m_InputChannels.size(); - inputAudioBufferList.mBuffers[0].mDataByteSize = expectedDataSize; - inputAudioBufferList.mBuffers[0].mData = NULL;//new float[expectedDataSize]; // we are going to get buffer from CoreAudio - - retVal = AudioUnitRender(m_AUHALAudioUnit, ioActionFlags, inTimeStamp, AUHAL_INPUT_ELEMENT, inNumberFrames, &inputAudioBufferList); - - if (retVal == kAudioHardwareNoError && - inputAudioBufferList.mBuffers[0].mNumberChannels == m_InputChannels.size() && - inputAudioBufferList.mBuffers[0].mDataByteSize == expectedDataSize ) - { - m_pInputData = (float*)inputAudioBufferList.mBuffers[0].mData; - } - else - { - m_pInputData = NULL; - return retVal; - } - } - - //is this an input only device? - if (m_OutputChannels.empty()) - AudioCallback (NULL, inNumberFrames, (int64_t)inTimeStamp->mSampleTime, theStartTime); - else if ((!m_OutputChannels.empty()) && (ioData->mBuffers[0].mNumberChannels == m_OutputChannels.size())) - AudioCallback ((float *)ioData->mBuffers[0].mData, inNumberFrames, (int64_t)inTimeStamp->mSampleTime, theStartTime); - - return retVal; -} - - -//********************************************************************************************** -// WCMRCoreAudioDevice::AudioCallback -// -//! Here's where the actual audio processing happens. We call upon all the active connections' -//! sinks to provide data to us which can be put/mixed in the output buffer! Also, we make the -//! input data available to any sources that may call upon us during this time! -//! -//! \param *pOutputBuffer : Points to a buffer to receive playback data. For Input only devices, this will be NULL -//! \param framesPerBuffer : Number of sample frames in input and output buffers. Number of channels, -//! which are interleaved, is fixed at Device Open (Active) time. In this implementation, -//! the number of channels are fixed to use the maximum available. -//! -//! \return true -//! -//********************************************************************************************** -int WCMRCoreAudioDevice::AudioCallback (float *pOutputBuffer, unsigned long framesPerBuffer, int64_t inSampleTime, uint64_t inCycleStartTime) -{ - struct WCMRAudioDeviceManagerClient::AudioCallbackData audioCallbackData = - { - m_pInputData, - pOutputBuffer, - framesPerBuffer, - inSampleTime, - AudioConvertHostTimeToNanos(inCycleStartTime) - }; - - m_pMyManager->NotifyClient (WCMRAudioDeviceManagerClient::AudioCallback, (void *)&audioCallbackData); - - m_SampleCounter += framesPerBuffer; - return m_StopRequested; -} - - -//********************************************************************************************** -// WCMRCoreAudioDevice::GetLatency -// -//! Get Latency for device. -//! -//! Use 'kAudioDevicePropertyLatency' and 'kAudioDevicePropertySafetyOffset' + GetStreamLatencies -//! -//! \param isInput : Return latency for the input if isInput is true, otherwise the output latency -//! wiil be returned. -//! \return Latency in samples. -//! -//********************************************************************************************** -uint32_t WCMRCoreAudioDevice::GetLatency(bool isInput) -{ - WTErr retVal = eNoErr; - OSStatus err = kAudioHardwareNoError; - - UInt32 propSize = sizeof(UInt32); - UInt32 value1 = 0; - UInt32 value2 = 0; - - UInt32 latency = 0; - std::vector<int> streamLatencies; - - - err = AudioDeviceGetProperty(m_DeviceID, 0, isInput, kAudioDevicePropertyLatency, &propSize, &value1); - if (err != kAudioHardwareNoError) - { - DEBUG_MSG("GetLatency kAudioDevicePropertyLatency err = " << err); - } - - err = AudioDeviceGetProperty(m_DeviceID, 0, isInput, kAudioDevicePropertySafetyOffset, &propSize, &value2); - if (err != kAudioHardwareNoError) - { - DEBUG_MSG("GetLatency kAudioDevicePropertySafetyOffset err = " << err); - } - - latency = value1 + value2; - - err = GetStreamLatency(m_DeviceID, isInput, streamLatencies); - if (err == kAudioHardwareNoError) - { - for ( int i = 0; i < streamLatencies.size(); i++) { - latency += streamLatencies[i]; - } - } - - return latency; -} - -//********************************************************************************************** -// WCMRCoreAudioDevice::GetStreamLatency -// -//! Get stream latency for device. -//! -//! \param deviceID : The audio device ID. -//! -//! \param isInput : Return latency for the input if isInput is true, otherwise the output latency -//! wiil be returned. -//********************************************************************************************** -OSStatus WCMRCoreAudioDevice::GetStreamLatency(AudioDeviceID device, bool isInput, std::vector<int>& latencies) -{ - OSStatus err = kAudioHardwareNoError; - UInt32 outSize1, outSize2, outSize3; - Boolean outWritable; - - err = AudioDeviceGetPropertyInfo(device, 0, isInput, kAudioDevicePropertyStreams, &outSize1, &outWritable); - if (err == noErr) { - int stream_count = outSize1 / sizeof(UInt32); - AudioStreamID streamIDs[stream_count]; - AudioBufferList bufferList[stream_count]; - UInt32 streamLatency; - outSize2 = sizeof(UInt32); - - err = AudioDeviceGetProperty(device, 0, isInput, kAudioDevicePropertyStreams, &outSize1, streamIDs); - if (err != noErr) { - DEBUG_MSG("GetStreamLatencies kAudioDevicePropertyStreams err = " << err); - return err; - } - - err = AudioDeviceGetPropertyInfo(device, 0, isInput, kAudioDevicePropertyStreamConfiguration, &outSize3, &outWritable); - if (err != noErr) { - DEBUG_MSG("GetStreamLatencies kAudioDevicePropertyStreamConfiguration err = " << err); - return err; - } - - for (int i = 0; i < stream_count; i++) { - err = AudioStreamGetProperty(streamIDs[i], 0, kAudioStreamPropertyLatency, &outSize2, &streamLatency); - if (err != noErr) { - DEBUG_MSG("GetStreamLatencies kAudioStreamPropertyLatency err = " << err); - return err; - } - err = AudioDeviceGetProperty(device, 0, isInput, kAudioDevicePropertyStreamConfiguration, &outSize3, bufferList); - if (err != noErr) { - DEBUG_MSG("GetStreamLatencies kAudioDevicePropertyStreamConfiguration err = " << err); - return err; - } - latencies.push_back(streamLatency); - } - } - return err; -} - - -//********************************************************************************************** -// WCMRCoreAudioDeviceManager::WCMRCoreAudioDeviceManager -// -//! The constructuor, we initialize PA, and build the device list. -//! -//! \param *pTheClient : The manager's client object (which receives notifications). -//! \param useMultithreading : Whether to use multi-threading for audio processing. Default is true. -//! -//! \return Nothing. -//! -//********************************************************************************************** -WCMRCoreAudioDeviceManager::WCMRCoreAudioDeviceManager(WCMRAudioDeviceManagerClient *pTheClient, - eAudioDeviceFilter eCurAudioDeviceFilter, bool useMultithreading, bool bNocopy) - : WCMRAudioDeviceManager (pTheClient, eCurAudioDeviceFilter) - , m_UseMultithreading (useMultithreading) - , m_bNoCopyAudioBuffer(bNocopy) -{ - AUTO_FUNC_DEBUG; - - //first of all, tell HAL to use it's own run loop, not to wait for our runloop to do - //it's dirty work... - //Essentially, this makes the HAL on Snow Leopard behave like Leopard. - //It's not yet (as of October 2009 documented), but the following discussion - //has the information provided by Jeff Moore @ Apple: - // http://lists.apple.com/archives/coreaudio-api/2009/Oct/msg00214.html - // - // As per Jeff's suggestion, opened an Apple Bug on this - ID# 7364011 - - CFRunLoopRef nullRunLoop = 0; - OSStatus err = AudioHardwareSetProperty (kAudioHardwarePropertyRunLoop, sizeof(CFRunLoopRef), &nullRunLoop); - - if (err != kAudioHardwareNoError) - { - syslog (LOG_NOTICE, "Unable to set RunLoop for Audio Hardware"); - } - - //add a listener to find out when devices change... - AudioHardwareAddPropertyListener (kAudioHardwarePropertyDevices, HardwarePropertyChangeCallback, this); - - //Always add the None device first... - m_NoneDevice = new WCMRNativeAudioNoneDevice(this); - - //prepare our initial list... - generateDeviceListImpl(); - - return; -} - - - -//********************************************************************************************** -// WCMRCoreAudioDeviceManager::~WCMRCoreAudioDeviceManager -// -//! It clears the device list, releasing each of the device. -//! -//! \param none -//! -//! \return Nothing. -//! -//********************************************************************************************** -WCMRCoreAudioDeviceManager::~WCMRCoreAudioDeviceManager() -{ - AUTO_FUNC_DEBUG; - - try - { - delete m_NoneDevice; - } - catch (...) - { - //destructors should absorb exceptions, no harm in logging though!! - DEBUG_MSG ("Exception during destructor"); - } - -} - - -WCMRAudioDevice* WCMRCoreAudioDeviceManager::initNewCurrentDeviceImpl(const std::string & deviceName) -{ - destroyCurrentDeviceImpl(); - - std::cout << "API::PortAudioDeviceManager::initNewCurrentDevice " << deviceName << std::endl; - if (deviceName == m_NoneDevice->DeviceName() ) - { - m_CurrentDevice = m_NoneDevice; - return m_CurrentDevice; - } - - DeviceInfo devInfo; - WTErr err = GetDeviceInfoByName(deviceName, devInfo); - - if (eNoErr == err) - { - try - { - std::cout << "API::PortAudioDeviceManager::Creating PA device: " << devInfo.m_DeviceId << ", Device Name: " << devInfo.m_DeviceName << std::endl; - TRACE_MSG ("API::PortAudioDeviceManager::Creating PA device: " << devInfo.m_DeviceId << ", Device Name: " << devInfo.m_DeviceName); - - m_CurrentDevice = new WCMRCoreAudioDevice (this, devInfo.m_DeviceId, m_UseMultithreading, m_bNoCopyAudioBuffer); - } - catch (...) - { - std::cout << "Unabled to create PA Device: " << devInfo.m_DeviceId << std::endl; - DEBUG_MSG ("Unabled to create PA Device: " << devInfo.m_DeviceId); - } - } - - return m_CurrentDevice; -} - - -void WCMRCoreAudioDeviceManager::destroyCurrentDeviceImpl() -{ - if (m_CurrentDevice != m_NoneDevice) - delete m_CurrentDevice; - - m_CurrentDevice = 0; -} - - -WTErr WCMRCoreAudioDeviceManager::getDeviceAvailableSampleRates(DeviceID deviceId, std::vector<int>& sampleRates) -{ - AUTO_FUNC_DEBUG; - - WTErr retVal = eNoErr; - OSStatus err = kAudioHardwareNoError; - UInt32 propSize = 0; - - sampleRates.clear(); - - //! 1. Get sample rate property size. - err = AudioDeviceGetPropertyInfo(deviceId, 0, 0, kAudioDevicePropertyAvailableNominalSampleRates, &propSize, NULL); - if (err == kAudioHardwareNoError) - { - //! 2. Get property: cannels output. - - // Allocate size according to the number of audio values - int numRates = propSize / sizeof(AudioValueRange); - AudioValueRange* supportedRates = new AudioValueRange[numRates]; - - // Get sampling rates from Audio device - err = AudioDeviceGetProperty(deviceId, 0, 0, kAudioDevicePropertyAvailableNominalSampleRates, &propSize, supportedRates); - if (err == kAudioHardwareNoError) - { - //! 3. Update sample rates - - // now iterate through our standard SRs - for(int ourSR=0; gAllSampleRates[ourSR] > 0; ourSR++) - { - //check to see if our SR is in the supported rates... - for (int deviceSR = 0; deviceSR < numRates; deviceSR++) - { - if ((supportedRates[deviceSR].mMinimum <= gAllSampleRates[ourSR]) && - (supportedRates[deviceSR].mMaximum >= gAllSampleRates[ourSR])) - { - sampleRates.push_back ((int)gAllSampleRates[ourSR]); - break; - } - } - } - } - else - { - retVal = eCoreAudioFailed; - DEBUG_MSG("Failed to get device Sample rates. Device Name: " << m_DeviceName.c_str()); - } - - delete [] supportedRates; - } - else - { - retVal = eCoreAudioFailed; - DEBUG_MSG("Failed to get device Sample rates property size. Device Name: " << m_DeviceName.c_str()); - } - - return retVal; -} - - -WTErr WCMRCoreAudioDeviceManager::getDeviceMaxInputChannels(DeviceID deviceId, unsigned int& inputChannels) -{ - AUTO_FUNC_DEBUG; - WTErr retVal = eNoErr; - OSStatus err = kAudioHardwareNoError; - UInt32 propSize = 0; - inputChannels = 0; - - // 1. Get property cannels input size. - err = AudioDeviceGetPropertyInfo (deviceId, 0, 1/* Input */, kAudioDevicePropertyStreamConfiguration, &propSize, NULL); - if (err == kAudioHardwareNoError) - { - //! 2. Get property: cannels input. - - // Allocate size according to the property size. Note that this is a variable sized struct... - AudioBufferList *pStreamBuffers = (AudioBufferList *)malloc(propSize); - - if (pStreamBuffers) - { - memset (pStreamBuffers, 0, propSize); - - // Get the Input channels - err = AudioDeviceGetProperty (deviceId, 0, 1/* Input */, kAudioDevicePropertyStreamConfiguration, &propSize, pStreamBuffers); - if (err == kAudioHardwareNoError) - { - // Calculate the number of input channels - for (UInt32 streamIndex = 0; streamIndex < pStreamBuffers->mNumberBuffers; streamIndex++) - { - inputChannels += pStreamBuffers->mBuffers[streamIndex].mNumberChannels; - } - } - else - { - retVal = eCoreAudioFailed; - DEBUG_MSG("Failed to get device Input channels. Device Name: " << m_DeviceName.c_str()); - } - - free (pStreamBuffers); - } - else - { - retVal = eMemOutOfMemory; - DEBUG_MSG("Faild to allocate memory. Device Name: " << m_DeviceName.c_str()); - } - } - else - { - retVal = eCoreAudioFailed; - DEBUG_MSG("Failed to get device Input channels property size. Device Name: " << m_DeviceName.c_str()); - } - - return retVal; -} - - -WTErr WCMRCoreAudioDeviceManager::getDeviceMaxOutputChannels(DeviceID deviceId, unsigned int& outputChannels) -{ - AUTO_FUNC_DEBUG; - - WTErr retVal = eNoErr; - OSStatus err = kAudioHardwareNoError; - UInt32 propSize = 0; - outputChannels = 0; - - //! 1. Get property cannels output size. - err = AudioDeviceGetPropertyInfo (deviceId, 0, 0/* Output */, kAudioDevicePropertyStreamConfiguration, &propSize, NULL); - if (err == kAudioHardwareNoError) - { - //! 2. Get property: cannels output. - - // Allocate size according to the property size. Note that this is a variable sized struct... - AudioBufferList *pStreamBuffers = (AudioBufferList *)malloc(propSize); - if (pStreamBuffers) - { - memset (pStreamBuffers, 0, propSize); - - // Get the Output channels - err = AudioDeviceGetProperty (deviceId, 0, 0/* Output */, kAudioDevicePropertyStreamConfiguration, &propSize, pStreamBuffers); - if (err == kAudioHardwareNoError) - { - // Calculate the number of output channels - for (UInt32 streamIndex = 0; streamIndex < pStreamBuffers->mNumberBuffers; streamIndex++) - { - outputChannels += pStreamBuffers->mBuffers[streamIndex].mNumberChannels; - } - } - else - { - retVal = eCoreAudioFailed; - DEBUG_MSG("Failed to get device Output channels. Device Name: " << m_DeviceName.c_str()); - } - free (pStreamBuffers); - } - else - { - retVal = eMemOutOfMemory; - DEBUG_MSG("Faild to allocate memory. Device Name: " << m_DeviceName.c_str()); - } - } - else - { - retVal = eCoreAudioFailed; - DEBUG_MSG("Failed to get device Output channels property size. Device Name: " << m_DeviceName.c_str()); - } - - return retVal; -} - - -WTErr WCMRCoreAudioDeviceManager::generateDeviceListImpl() -{ - AUTO_FUNC_DEBUG; - - // lock the list first - wvNS::wvThread::ThreadMutex::lock theLock(m_AudioDeviceInfoVecMutex); - m_DeviceInfoVec.clear(); - - //First, get info from None device which is always present - if (m_NoneDevice) - { - DeviceInfo *pDevInfo = new DeviceInfo(NONE_DEVICE_ID, m_NoneDevice->DeviceName() ); - pDevInfo->m_AvailableSampleRates = m_NoneDevice->SamplingRates(); - m_DeviceInfoVec.push_back(pDevInfo); - } - - WTErr retVal = eNoErr; - OSStatus osErr = noErr; - AudioDeviceID* deviceIDs = 0; - - openlog("WCMRCoreAudioDeviceManager", LOG_PID | LOG_CONS, LOG_USER); - - try - { - //Get device count... - UInt32 propSize = 0; - osErr = AudioHardwareGetPropertyInfo (kAudioHardwarePropertyDevices, &propSize, NULL); - ASSERT_ERROR(osErr, "AudioHardwareGetProperty 1"); - if (WUIsError(osErr)) - throw osErr; - - size_t numDevices = propSize / sizeof (AudioDeviceID); - deviceIDs = new AudioDeviceID[numDevices]; - - //retrieve the device IDs - propSize = numDevices * sizeof (AudioDeviceID); - osErr = AudioHardwareGetProperty (kAudioHardwarePropertyDevices, &propSize, deviceIDs); - ASSERT_ERROR(osErr, "Error while getting audio devices: AudioHardwareGetProperty 2"); - if (WUIsError(osErr)) - throw osErr; - - //now add the ones that are not there... - for (size_t deviceIndex = 0; deviceIndex < numDevices; deviceIndex++) - { - DeviceInfo* pDevInfo = 0; - - //Get device name and create new DeviceInfo entry - //Get property name size. - osErr = AudioDeviceGetPropertyInfo(deviceIDs[deviceIndex], 0, 0, kAudioDevicePropertyDeviceName, &propSize, NULL); - if (osErr == kAudioHardwareNoError) - { - //Get property: name. - char* deviceName = new char[propSize]; - osErr = AudioDeviceGetProperty(deviceIDs[deviceIndex], 0, 0, kAudioDevicePropertyDeviceName, &propSize, deviceName); - if (osErr == kAudioHardwareNoError) - { - pDevInfo = new DeviceInfo(deviceIDs[deviceIndex], deviceName); - } - else - { - retVal = eCoreAudioFailed; - DEBUG_MSG("Failed to get device name. Device ID: " << m_DeviceID); - } - - delete [] deviceName; - } - else - { - retVal = eCoreAudioFailed; - DEBUG_MSG("Failed to get device name property size. Device ID: " << m_DeviceID); - } - - if (pDevInfo) - { - //Retrieve all the information we need for the device - WTErr wErr = eNoErr; - - //Get available sample rates for the device - std::vector<int> availableSampleRates; - wErr = getDeviceAvailableSampleRates(pDevInfo->m_DeviceId, availableSampleRates); - - if (wErr != eNoErr) - { - DEBUG_MSG ("Failed to get device available sample rates. Device ID: " << m_DeviceID); - delete pDevInfo; - continue; //proceed to the next device - } - - pDevInfo->m_AvailableSampleRates = availableSampleRates; - - //Get max input channels - uint32_t maxInputChannels; - wErr = getDeviceMaxInputChannels(pDevInfo->m_DeviceId, maxInputChannels); - - if (wErr != eNoErr) - { - DEBUG_MSG ("Failed to get device max input channels count. Device ID: " << m_DeviceID); - delete pDevInfo; - continue; //proceed to the next device - } - - pDevInfo->m_MaxInputChannels = maxInputChannels; - - //Get max output channels - uint32_t maxOutputChannels; - wErr = getDeviceMaxOutputChannels(pDevInfo->m_DeviceId, maxOutputChannels); - - if (wErr != eNoErr) - { - DEBUG_MSG ("Failed to get device max output channels count. Device ID: " << m_DeviceID); - delete pDevInfo; - continue; //proceed to the next device - } - - pDevInfo->m_MaxOutputChannels = maxOutputChannels; - - //Now check if this device is acceptable according to current input/output settings - bool bRejectDevice = false; - switch(m_eAudioDeviceFilter) - { - case eInputOnlyDevices: - if (pDevInfo->m_MaxInputChannels != 0) - { - m_DeviceInfoVec.push_back(pDevInfo); - } - else - { - // Delete unnecesarry device - bRejectDevice = true; - } - break; - case eOutputOnlyDevices: - if (pDevInfo->m_MaxOutputChannels != 0) - { - m_DeviceInfoVec.push_back(pDevInfo); - } - else - { - // Delete unnecesarry device - bRejectDevice = true; - } - break; - case eFullDuplexDevices: - if (pDevInfo->m_MaxInputChannels != 0 && pDevInfo->m_MaxOutputChannels != 0) - { - m_DeviceInfoVec.push_back(pDevInfo); - } - else - { - // Delete unnecesarry device - bRejectDevice = true; - } - break; - case eAllDevices: - default: - m_DeviceInfoVec.push_back(pDevInfo); - break; - } - - if(bRejectDevice) - { - syslog (LOG_NOTICE, "%s rejected, In Channels = %d, Out Channels = %d\n", - pDevInfo->m_DeviceName.c_str(), pDevInfo->m_MaxInputChannels, pDevInfo->m_MaxOutputChannels); - // In case of Input and Output both channels being Zero, we will release memory; since we created CoreAudioDevice but we are Not adding it in list. - delete pDevInfo; - } - } - } - - - //If no devices were found, that's not a good thing! - if (m_DeviceInfoVec.empty()) - { - DEBUG_MSG ("No matching CoreAudio devices were found\n"); - } - } - catch (...) - { - if (WUNoError(retVal)) - retVal = eCoreAudioFailed; - } - - delete[] deviceIDs; - closelog(); - - return retVal; -} - - -WTErr WCMRCoreAudioDeviceManager::updateDeviceListImpl() -{ - wvNS::wvThread::ThreadMutex::lock theLock(m_AudioDeviceInfoVecMutex); - WTErr err = generateDeviceListImpl(); - - if (eNoErr != err) - { - std::cout << "API::PortAudioDeviceManager::updateDeviceListImpl: Device list update error: "<< err << std::endl; - } - - if (m_CurrentDevice) - { - // if we have device initialized we should find out if this device is still connected - DeviceInfo devInfo; - WTErr deviceLookUpErr = GetDeviceInfoByName(m_CurrentDevice->DeviceName(), devInfo ); - - if (eNoErr != deviceLookUpErr) - { - NotifyClient (WCMRAudioDeviceManagerClient::IODeviceDisconnected); - return err; - } - - WCMRCoreAudioDevice* current_device = dynamic_cast<WCMRCoreAudioDevice*>(m_CurrentDevice); - - if ( current_device && - (current_device->DeviceID() != devInfo.m_DeviceId ) ) - { - NotifyClient (WCMRAudioDeviceManagerClient::RequestReset); - return err; - } - } - - NotifyClient (WCMRAudioDeviceManagerClient::DeviceListChanged); - - return err; -} - - -WTErr WCMRCoreAudioDeviceManager::getDeviceSampleRatesImpl(const std::string & deviceName, std::vector<int>& sampleRates) const -{ - AUTO_FUNC_DEBUG; - - WTErr retVal = eNoErr; - OSStatus err = kAudioHardwareNoError; - UInt32 propSize = 0; - - sampleRates.clear(); - - //first check if the request has been made for None device - if (deviceName == m_NoneDevice->DeviceName() ) - { - sampleRates = m_NoneDevice->SamplingRates(); - return retVal; - } - - if (m_CurrentDevice && m_CurrentDevice->DeviceName () == deviceName) { - sampleRates.assign(m_CurrentDevice->SamplingRates().begin(), m_CurrentDevice->SamplingRates().end() ); - return retVal; - } - - DeviceInfo devInfo; - retVal = GetDeviceInfoByName(deviceName, devInfo); - - //! 1. Get sample rate property size. - err = AudioDeviceGetPropertyInfo(devInfo.m_DeviceId, 0, 0, kAudioDevicePropertyAvailableNominalSampleRates, &propSize, NULL); - - if (err == kAudioHardwareNoError) - { - //! 2. Get property: cannels output. - - // Allocate size accrding to the number of audio values - int numRates = propSize / sizeof(AudioValueRange); - AudioValueRange* supportedRates = new AudioValueRange[numRates]; - - // Get sampling rates from Audio device - err = AudioDeviceGetProperty(devInfo.m_DeviceId, 0, 0, kAudioDevicePropertyAvailableNominalSampleRates, &propSize, supportedRates); - - if (err == kAudioHardwareNoError) - { - //! 3. Update sample rates - - // now iterate through our standard SRs - for(int ourSR=0; gAllSampleRates[ourSR] > 0; ourSR++) - { - //check to see if our SR is in the supported rates... - for (int deviceSR = 0; deviceSR < numRates; deviceSR++) - { - if ((supportedRates[deviceSR].mMinimum <= gAllSampleRates[ourSR]) && - (supportedRates[deviceSR].mMaximum >= gAllSampleRates[ourSR])) - { - sampleRates.push_back ((int)gAllSampleRates[ourSR]); - break; - } - } - } - } - else - { - retVal = eCoreAudioFailed; - DEBUG_MSG("Failed to get device Sample rates. Device Name: " << m_DeviceName.c_str()); - } - - delete [] supportedRates; - } - else - { - retVal = eCoreAudioFailed; - DEBUG_MSG("Failed to get device Sample rates property size. Device Name: " << m_DeviceName.c_str()); - } - - devInfo.m_AvailableSampleRates.assign(sampleRates.begin(), sampleRates.end() ); - - return retVal; -} - - -WTErr WCMRCoreAudioDeviceManager::getDeviceBufferSizesImpl(const std::string & deviceName, std::vector<int>& bufferSizes) const -{ - AUTO_FUNC_DEBUG; - - WTErr retVal = eNoErr; - OSStatus err = kAudioHardwareNoError; - UInt32 propSize = 0; - - bufferSizes.clear(); - - //first check if the request has been made for None device - if (deviceName == m_NoneDevice->DeviceName() ) - { - bufferSizes = m_NoneDevice->BufferSizes(); - return retVal; - } - - if (m_CurrentDevice && m_CurrentDevice->DeviceName () == deviceName) { - bufferSizes.assign(m_CurrentDevice->BufferSizes().begin(), m_CurrentDevice->BufferSizes().end() ); - return retVal; - } - - DeviceInfo devInfo; - retVal = GetDeviceInfoByName(deviceName, devInfo); - - if (eNoErr == retVal) - { - // 1. Get buffer size range - AudioValueRange bufferSizesRange; - propSize = sizeof (AudioValueRange); - err = AudioDeviceGetProperty (devInfo.m_DeviceId, 0, 0, kAudioDevicePropertyBufferFrameSizeRange, &propSize, &bufferSizesRange); - if(err == kAudioHardwareNoError) - { - // 2. Run on all ranges and add them to the list - for(int bsize=0; gAllBufferSizes[bsize] > 0; bsize++) - { - if ((bufferSizesRange.mMinimum <= gAllBufferSizes[bsize]) && (bufferSizesRange.mMaximum >= gAllBufferSizes[bsize])) - { - bufferSizes.push_back (gAllBufferSizes[bsize]); - } - } - - //if we didn't get a single hit, let's simply add the min. and the max... - if (bufferSizes.empty()) - { - bufferSizes.push_back ((int)bufferSizesRange.mMinimum); - bufferSizes.push_back ((int)bufferSizesRange.mMaximum); - } - } - else - { - retVal = eCoreAudioFailed; - DEBUG_MSG("Failed to get device buffer sizes range. Device Name: " << m_DeviceName.c_str()); - } - } - else - { - retVal = eRMResNotFound; - std::cout << "API::PortAudioDeviceManager::GetBufferSizes: Device not found: "<< deviceName << std::endl; - } - - - return retVal; -} - - -OSStatus WCMRCoreAudioDeviceManager::HardwarePropertyChangeCallback (AudioHardwarePropertyID inPropertyID, void* inClientData) -{ - switch (inPropertyID) - { - case kAudioHardwarePropertyDevices: - { - WCMRCoreAudioDeviceManager* pManager = (WCMRCoreAudioDeviceManager*)inClientData; - if (pManager) - pManager->updateDeviceListImpl(); - } - break; - - default: - break; - } - - return 0; -} diff --git a/libs/backends/wavesaudio/wavesapi/devicemanager/WCMRCoreAudioDeviceManager.h b/libs/backends/wavesaudio/wavesapi/devicemanager/WCMRCoreAudioDeviceManager.h deleted file mode 100644 index 0d92493b51..0000000000 --- a/libs/backends/wavesaudio/wavesapi/devicemanager/WCMRCoreAudioDeviceManager.h +++ /dev/null @@ -1,209 +0,0 @@ -/* - Copyright (C) 2014 Waves Audio Ltd. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. - -*/ - -//---------------------------------------------------------------------------------- -// -// -//! \file WCMRCoreAudioDeviceManager.h -//! -//! WCMRCoreAudioDeviceManager and related class declarations -//! -//---------------------------------------------------------------------------------*/ -#ifndef __WCMRCoreAudioDeviceManager_h_ - #define __WCMRCoreAudioDeviceManager_h_ - -#include "WCMRAudioDeviceManager.h" -#include "WCMRNativeAudio.h" -#include "Threads/WCThreadSafe.h" - -#include <AudioUnit/AudioUnit.h> -#include <AudioToolbox/AudioToolbox.h> - -#include <mach/mach.h> - -#include <CoreAudio/CoreAudio.h> - -//forward decl. -class WCMRCoreAudioDeviceManager; - -#define WV_USE_TONE_GEN 0 ///! Set this to 1 to use a tone generator for input. See description at SetupToneGenerator for details. - -// This enum is for choosing filter for audio devices scan -typedef enum eCABS_Method -{ - eCABS_Simple = 0, - eCABS_DestructiveCache, - eCABS_CacheOnDeviceSet, - eCABS_MethodNum // Must be last -} eCABS_Method; - -//! Manages a port audio device, providing information -//! about the device, and managing audio callbacks. -class WCMRCoreAudioDevice : public WCMRNativeAudioDevice -{ -public: - - WCMRCoreAudioDevice (WCMRCoreAudioDeviceManager *pManager, AudioDeviceID deviceID, bool useMultithreading = true, bool bNocopy = false);///<Constructor - virtual ~WCMRCoreAudioDevice ();///<Destructor - - virtual const std::string& DeviceName() const;///<Name? - virtual const std::vector<std::string>& InputChannels();///<Current Input Channel List? - note that this may change with change in sampling rate. - virtual const std::vector<std::string>& OutputChannels();///<Current Output Channel List? - note that this may change with change in sampling rate. - - - virtual const std::vector<int>& SamplingRates();///<Supported Sampling Rate List? - virtual int CurrentSamplingRate(); ///<Current Sampling rate.? - virtual WTErr SetCurrentSamplingRate(int newRate);///<Change Current Sampling Rate : This is a requset, might not be successful at run time! - - virtual const std::vector<int>& BufferSizes();///<Supported Buffer Size List? - note that this may change with change in sampling rate. - virtual int CurrentBufferSize();///<Current Buffer Size.? - note that this may change with change in sampling rate. - virtual WTErr SetCurrentBufferSize (int newSize);///<Change Current Buffer Size : This is a requset, might not be successful at run time! - - virtual ConnectionStates ConnectionStatus();///< Connection Status - device available, gone, disconnected - - virtual WTErr SetActive (bool newState);///<Prepare/Activate device. - virtual WTErr SetStreaming (bool newState);///<Start/Stop Streaming - should reconnect connections when streaming starts! - - virtual WTErr DoIdle();///<Do Idle Processing - - virtual WTErr SetMonitorChannels (int leftChannel, int rightChannel);///<Set monitor channels. - optional, will not be available with AG - virtual WTErr SetMonitorGain (float newGain);///<Set monitor gain. - optional, will not be available with AG - - virtual WTErr ShowConfigPanel (void *pParam);///< Show Control Panel - in case of ASIO this will work only with Active device! - - virtual int AudioCallback (float *pOutputBuffer, unsigned long framesPerBuffer, int64_t inSampleTime, uint64_t inCycleStartTime); - - AudioDeviceID DeviceID () {return m_DeviceID;} - - virtual uint32_t GetLatency (bool isInput); ///< Get latency. - virtual OSStatus GetStreamLatency(AudioDeviceID deviceID, bool isInput, std::vector<int>& latencies); - - -protected: - - AudioDeviceID m_DeviceID; ///< The CoreAudio device id - bool m_StopRequested; ///< should be set to true when want to stop, set to false otherwise. - float *m_pInputData; ///< This is what came in with the most recent callback. - int64_t m_SampleCounter; ///< The current running sample counter, updated by the audio callback. - int64_t m_SampleCountAtLastIdle; ///< What was the sample count last time we checked... - int m_StalledSampleCounter; ///< The number of idle calls with same sample count detected - int m_ChangeCheckCounter; ///< The number of idle calls passed since we checked the buffer size change. - - wvNS::wvThread::timestamp m_LastCPULog; ///< The time when the last CPU details log was sent as a notification. -// unsigned int m_IOCyclesTimesTaken[MAX_IOCYCLE_TIMES]; ///< This stores the times taken by each IOCycle, in host-time units. -// int m_CurrentIOCycle; ///< The location in m_IOCyclesTymesTaken array, where the next cycle's value will go. -// int m_CyclesToAccumulate; ///< The number of cycles to accumulate the values for - maximum for last one second. -// unsigned int m_CyclePeriod; ///< The number of host time units for a cycle period - determined by buffer size and sampling rate - - - AudioUnit m_AUHALAudioUnit;///< The AUHAL AudioUnit - - int m_BufferSizeChangeRequested; - int m_BufferSizeChangeReported; - int m_ResetRequested; - int m_ResetReported; - int m_ResyncRequested; - int m_ResyncReported; - int m_SRChangeRequested; - int m_SRChangeReported; - - int m_DropsDetected; ///< Number of times audio drops have been detected so far. - int m_DropsReported; ///< Number of times audio drops have been reported so far to the client. - bool m_IgnoreThisDrop; ///< Allows disregarding the first drop - - thread_t m_IOProcThreadPort; ///< Thread handle to calculate CPU consumption. - int m_CPUCount; ///< Number of processors/core to normalize cpu consumption calculation. - -#if WV_USE_TONE_GEN - //The Tone Generator... - float_t *m_pToneData; - uint32_t m_ToneDataSamples; - uint32_t m_NextSampleToUse; -#endif //WV_USE_TONE_GEN - - WTErr UpdateDeviceInfo (); - WTErr UpdateDeviceId (); - WTErr UpdateDeviceName(); - WTErr UpdateDeviceInputs(); - WTErr UpdateDeviceOutputs(); - WTErr UpdateDeviceSampleRates(); - WTErr UpdateDeviceBufferSizes(); - WTErr SetWorkingBufferSize(int newSize); - OSStatus SetBufferSizesByIO(int newSize); - WTErr SetAndCheckCurrentSamplingRate (int newRate); - - WTErr EnableAudioUnitIO(); - WTErr virtual EnableListeners(); - WTErr virtual DisableListeners(); - WTErr SetupAUHAL(); - WTErr TearDownAUHAL(); - -#if WV_USE_TONE_GEN - void SetupToneGenerator (); -#endif //WV_USE_TONE_GEN - - static OSStatus StaticAudioIOProc(void *inRefCon, AudioUnitRenderActionFlags * ioActionFlags, - const AudioTimeStamp *inTimeStamp, UInt32 inBusNumber, UInt32 inNumberFrames, - AudioBufferList *ioData); - OSStatus AudioIOProc(AudioUnitRenderActionFlags * ioActionFlags, - const AudioTimeStamp *inTimeStamp, UInt32 inBusNumber, UInt32 inNumberFrames, - AudioBufferList *ioData); - - static OSStatus StaticPropertyChangeProc (AudioDeviceID inDevice, UInt32 inChannel, Boolean isInput, - AudioDevicePropertyID inPropertyID, void *inClientData); - void PropertyChangeProc (AudioDevicePropertyID inPropertyID); - -private: - -}; - - -//! WCMRCoreAudioDeviceManager -/*! The CoreAudio Device Manager class */ -class WCMRCoreAudioDeviceManager : public WCMRAudioDeviceManager -{ -public: - - WCMRCoreAudioDeviceManager(WCMRAudioDeviceManagerClient *pTheClient, eAudioDeviceFilter eCurAudioDeviceFilter, - bool useMultithreading = true, bool bNocopy = false); ///< constructor - virtual ~WCMRCoreAudioDeviceManager(void); ///< Destructor - -protected: - static OSStatus HardwarePropertyChangeCallback (AudioHardwarePropertyID inPropertyID, void* inClientData); - - virtual WCMRAudioDevice* initNewCurrentDeviceImpl(const std::string & deviceName); - virtual void destroyCurrentDeviceImpl(); - virtual WTErr generateDeviceListImpl(); - virtual WTErr updateDeviceListImpl(); - virtual WTErr getDeviceSampleRatesImpl(const std::string & deviceName, std::vector<int>& sampleRates) const; - virtual WTErr getDeviceBufferSizesImpl(const std::string & deviceName, std::vector<int>& bufferSizes) const; - - bool m_UseMultithreading; ///< Flag indicates whether to use multi-threading for audio processing. - bool m_bNoCopyAudioBuffer; - -private: - // helper functions for this class only - WTErr getDeviceAvailableSampleRates(DeviceID deviceId, std::vector<int>& sampleRates); - WTErr getDeviceMaxInputChannels(DeviceID deviceId, unsigned int& inputChannels); - WTErr getDeviceMaxOutputChannels(DeviceID deviceId, unsigned int& outputChannels); - - WCMRAudioDevice* m_NoneDevice; -}; - -#endif //#ifndef __WCMRCoreAudioDeviceManager_h_ diff --git a/libs/backends/wavesaudio/wavesapi/devicemanager/WCMRNativeAudio.cpp b/libs/backends/wavesaudio/wavesapi/devicemanager/WCMRNativeAudio.cpp deleted file mode 100644 index bf5e4fbb90..0000000000 --- a/libs/backends/wavesaudio/wavesapi/devicemanager/WCMRNativeAudio.cpp +++ /dev/null @@ -1,266 +0,0 @@ -//---------------------------------------------------------------------------------- -// -// Copyright (c) 2008 Waves Audio Ltd. All rights reserved. -// -//! \file WCMRNativeAudio.cpp -//! -//! WCMRNativeAudioConnection and related class defienitions -//! -//---------------------------------------------------------------------------------*/ -#if defined(__APPLE__) -#include <CoreAudio/CoreAudio.h> -#endif - -#include "WCMRNativeAudio.h" -#include "MiscUtils/pthread_utils.h" -#include "MiscUtils/safe_delete.h" -#include <iostream> -#include <sstream> -#include <boost/assign/list_of.hpp> - -#define NONE_DEVICE_NAME "None" -#define NONE_DEVICE_INPUT_NAMES "Input " -#define NONE_DEVICE_OUTPUT_NAMES "Output " - -//********************************************************************************************** -// WCMRNativeAudioNoneDevice::WCMRNativeAudioNoneDevice -// -//! Constructor for the dummy "None" device. This constructor simply adds supported SRs, -//! buffer sizes, and channels, so that it may look like a real native device to -//! the applications. -//! -//! \param pManager : The managing device manager - simply passed on to the base class. -//! -//! -//********************************************************************************************** -WCMRNativeAudioNoneDevice::WCMRNativeAudioNoneDevice (WCMRAudioDeviceManager *pManager) - : WCMRNativeAudioDevice (pManager, false /*useMultiThreading*/) -#ifndef PTW32_VERSION - , m_SilenceThread(0) -#endif -#if defined (PLATFORM_WINDOWS) - , _waitableTimerForUsleep (CreateWaitableTimer(NULL, TRUE, NULL)) -#endif -{ - mark_pthread_inactive (m_SilenceThread); - - m_DeviceName = NONE_DEVICE_NAME; - - m_SamplingRates = boost::assign::list_of (m_CurrentSamplingRate=44100)(48000)(88200)(96000)(176400)(192000); - - m_BufferSizes = boost::assign::list_of (32)(64)(128)(m_CurrentBufferSize=256)(512)(1024); - - for (int channel = 0; channel < __m_NumInputChannels; channel++) - { - std::stringstream name; - name << NONE_DEVICE_INPUT_NAMES; - name << (channel + 1); - m_InputChannels.push_back(name.str()); - } - - for (int channel = 0; channel < __m_NumOutputChannels; channel++) - { - std::stringstream name; - name << NONE_DEVICE_INPUT_NAMES; - name << (channel + 1); - m_OutputChannels.push_back(name.str()); - } - _m_inputBuffer = new float[__m_NumInputChannels * m_BufferSizes.back()]; - _m_outputBuffer = new float[__m_NumOutputChannels * m_BufferSizes.back()]; - m_CurrentBufferSize = m_BufferSizes.back(); -} - - -WCMRNativeAudioNoneDevice::~WCMRNativeAudioNoneDevice () -{ -#if defined (PLATFORM_WINDOWS) - if(_waitableTimerForUsleep) { - CloseHandle(_waitableTimerForUsleep); - } -#endif -} - -WTErr WCMRNativeAudioNoneDevice::SetActive (bool newState) -{ - //This will most likely be overridden, the base class simply - //changes the member. - if (Active() == newState) - { - return (eNoErr); - } - - if (Active() && Streaming()) - { - SetStreaming(false); - } - return WCMRAudioDevice::SetActive(newState); -} - -WTErr WCMRNativeAudioNoneDevice::SetCurrentBufferSize (int newSize) -{ - - //changes the status. - int oldSize = CurrentBufferSize(); - bool oldActive = Active(); - - //same size, nothing to do. - if (oldSize == newSize) - return eNoErr; - - //see if this is one of our supported rates... - std::vector<int>::iterator intIter = find(m_BufferSizes.begin(), m_BufferSizes.end(), newSize); - if (intIter == m_BufferSizes.end()) - { - //Can't change, perhaps use an "invalid param" type of error - return eCommandLineParameter; - } - - if (Streaming()) - { - //Can't change, perhaps use an "in use" type of error - return eGenericErr; - } - - - return WCMRAudioDevice::SetCurrentBufferSize(newSize); -} - - -WTErr WCMRNativeAudioNoneDevice::UpdateDeviceInfo () -{ - return eNoErr; -} - - -WTErr WCMRNativeAudioNoneDevice::SetStreaming (bool newState) -{ - if (Streaming() == newState) - { - return (eNoErr); - } - - WCMRAudioDevice::SetStreaming(newState); - - if (Streaming()) - { - if (is_pthread_active (m_SilenceThread)) - std::cerr << "\t\t\t\t\t !!!!!!!!!!!!!!! Warning: the inactive NONE-DEVICE was streaming!" << std::endl; - - pthread_attr_t attributes; - size_t stack_size = 100000; -#ifdef __APPLE__ - stack_size = (((stack_size - 1) / PTHREAD_STACK_MIN) + 1) * PTHREAD_STACK_MIN; -#endif - if (pthread_attr_init (&attributes)) { - std::cerr << "WCMRNativeAudioNoneDevice::SetStreaming (): pthread_attr_init () failed!" << std::endl; - return eGenericErr; - } - - if (pthread_attr_setstacksize (&attributes, stack_size)) { - std::cerr << "WCMRNativeAudioNoneDevice::SetStreaming (): pthread_attr_setstacksize () failed!" << std::endl; - return eGenericErr; - } - - if (pthread_create (&m_SilenceThread, &attributes, __SilenceThread, this)) { - mark_pthread_inactive (m_SilenceThread); - std::cerr << "WCMRNativeAudioNoneDevice::SetStreaming (): pthread_create () failed!" << std::endl; - return eGenericErr; - } - } - else - { - if (!is_pthread_active (m_SilenceThread)) - { - std::cerr << "\t\t\t\t\t !!!!!!!!!!!!!!! Warning: the active NONE-DEVICE was NOT streaming!" << std::endl; - } - - while (is_pthread_active (m_SilenceThread)) - { - _usleep(1); //now wait for ended thread; - } - } - - return eNoErr; -} - -void WCMRNativeAudioNoneDevice::_SilenceThread() -{ -#if defined(PLATFORM_WINDOWS) - float* theInpBuffers[__m_NumInputChannels]; - for(int i = 0; i < __m_NumInputChannels; ++i) - { - theInpBuffers[i] = _m_inputBuffer + m_BufferSizes.back() * i; - } -#else - float* theInpBuffers = _m_inputBuffer; -#endif - - const size_t buffer_size = CurrentBufferSize(); - const uint64_t cyclePeriodNanos = (1000000000.0 * buffer_size) / CurrentSamplingRate(); - - struct WCMRAudioDeviceManagerClient::AudioCallbackData audioCallbackData = - { - (const float*)theInpBuffers, - _m_outputBuffer, - buffer_size, - 0, - 0 - }; - - audioCallbackData.acdCycleStartTimeNanos =__get_time_nanos(); - - // VERY ROUGH IMPLEMENTATION: - while(Streaming()) { - - uint64_t cycleEndTimeNanos = audioCallbackData.acdCycleStartTimeNanos + cyclePeriodNanos; - - m_pMyManager->NotifyClient (WCMRAudioDeviceManagerClient::AudioCallback, (void *)&audioCallbackData); - - audioCallbackData.acdSampleTime += buffer_size; - - int64_t timeToSleepUsecs = ((int64_t)cycleEndTimeNanos - (int64_t)__get_time_nanos())/1000; - - if (timeToSleepUsecs > 0) { - _usleep (timeToSleepUsecs); - } - audioCallbackData.acdCycleStartTimeNanos = cycleEndTimeNanos+1; - } - mark_pthread_inactive (m_SilenceThread); -} - -void* WCMRNativeAudioNoneDevice::__SilenceThread(void *This) -{ - ((WCMRNativeAudioNoneDevice*)This)->_SilenceThread(); - return 0; -} - -#if defined(PLATFORM_WINDOWS) -void WCMRNativeAudioNoneDevice::_usleep(uint64_t duration_usec) -{ - LARGE_INTEGER ft; - - ft.QuadPart = -(10*duration_usec); // Convert to 100 nanosecond interval, negative value indicates relative time - - SetWaitableTimer(_waitableTimerForUsleep, &ft, 0, NULL, NULL, 0); - WaitForSingleObject(_waitableTimerForUsleep, INFINITE); -} -#endif - -uint64_t -WCMRNativeAudioNoneDevice::__get_time_nanos () -{ -#ifdef __APPLE__ - // here we exploit the time counting API which is used by the WCMRCoreAudioDeviceManager. However, - // the API should be a part of WCMRCoreAudioDeviceManager to give a chance of being tied to the - // audio device transport timeß. - return AudioConvertHostTimeToNanos (AudioGetCurrentHostTime ()); - -#elif PLATFORM_WINDOWS - - LARGE_INTEGER Frequency, Count ; - - QueryPerformanceFrequency (&Frequency) ; - QueryPerformanceCounter (&Count); - return uint64_t ((Count.QuadPart * 1000000000.0 / Frequency.QuadPart)); -#endif -} diff --git a/libs/backends/wavesaudio/wavesapi/devicemanager/WCMRNativeAudio.h b/libs/backends/wavesaudio/wavesapi/devicemanager/WCMRNativeAudio.h deleted file mode 100644 index 238d36fd74..0000000000 --- a/libs/backends/wavesaudio/wavesapi/devicemanager/WCMRNativeAudio.h +++ /dev/null @@ -1,96 +0,0 @@ -/* - Copyright (C) 2014 Waves Audio Ltd. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. - -*/ - -//---------------------------------------------------------------------------------- -// -// -//! \file WCMRNativeAudio.h -//! -//! WCMRNativeAudio and related class declarations -//! -//---------------------------------------------------------------------------------*/ -#ifndef __WCMRNativeAudio_h_ - #define __WCMRNativeAudio_h_ - -#if defined(PLATFORM_WINDOWS) -#include "windows.h" -#endif -#include "pthread.h" -#include "WCRefManager.h" -#include "WCMRAudioDeviceManager.h" - -#if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_9 -#include <unistd.h> -#endif - -class WCMRNativeAudioDevice; //forward - - - -class WCMRNativeAudioDevice : public WCMRAudioDevice -{ -public: - - WCMRNativeAudioDevice (WCMRAudioDeviceManager *pManager, bool useMultithreading = true, bool bNoCopy = false) : - WCMRAudioDevice (pManager) - , m_UseMultithreading (useMultithreading) - , m_bNoCopyAudioBuffer(bNoCopy) - {} - virtual ~WCMRNativeAudioDevice () {} - -protected: - bool m_UseMultithreading; - bool m_bNoCopyAudioBuffer; ///< This flag determines whether the audio callback performs a copy of audio, or the source/sink perform the copy. It should be true to let source/sink do the copies. - -}; - - -//! A dummy device to allow apps to choose "None" in case no real device connection is required. -class WCMRNativeAudioNoneDevice : public WCMRNativeAudioDevice -{ -public: - WCMRNativeAudioNoneDevice (WCMRAudioDeviceManager *pManager); - virtual ~WCMRNativeAudioNoneDevice (); - virtual WTErr SetActive (bool newState);///<Prepare/Activate device. - virtual WTErr SetStreaming (bool newState);///<Start/Stop Streaming - should reconnect connections when streaming starts! - virtual WTErr SetCurrentBufferSize (int newSize);///<Change Current Buffer Size : This is a requset, might not be successful at run time! - virtual WTErr UpdateDeviceInfo (); - -private: - - static void* __SilenceThread(void *This); - void _SilenceThread(); -#if defined(PLATFORM_WINDOWS) - void _usleep(uint64_t usec); -#else - inline void _usleep(uint64_t usec) { ::usleep(usec); } -#endif - static const size_t __m_NumInputChannels = 0; - static const size_t __m_NumOutputChannels = 0; - pthread_t m_SilenceThread; - float *_m_inputBuffer; - float *_m_outputBuffer; - static uint64_t __get_time_nanos (); -#if defined (PLATFORM_WINDOWS) - HANDLE _waitableTimerForUsleep; -#endif -}; - - -#endif //#ifndef __WCMRNativeAudio_h_ diff --git a/libs/backends/wavesaudio/wavesapi/devicemanager/WCMRPortAudioDeviceManager.cpp b/libs/backends/wavesaudio/wavesapi/devicemanager/WCMRPortAudioDeviceManager.cpp deleted file mode 100644 index 8e63887d37..0000000000 --- a/libs/backends/wavesaudio/wavesapi/devicemanager/WCMRPortAudioDeviceManager.cpp +++ /dev/null @@ -1,1782 +0,0 @@ -//---------------------------------------------------------------------------------- -// -// Copyright (c) 2008 Waves Audio Ltd. All rights reserved. -// -//! \file WCMRPortAudioDeviceManager.cpp -//! -//! WCMRPortAudioDeviceManager and related class declarations -//! -//---------------------------------------------------------------------------------*/ -#include "WCMRPortAudioDeviceManager.h" -#include "MiscUtils/safe_delete.h" -#include "UMicroseconds.h" -#include <iostream> -#include <sstream> -#include <algorithm> -#include <list> -using namespace wvNS; -#include "IncludeWindows.h" -#include <mmsystem.h> -#include "pa_asio.h" -#include "asio.h" - -#define PROPERTY_CHANGE_SLEEP_TIME_MILLISECONDS 200 -#define DEVICE_INFO_UPDATE_SLEEP_TIME_MILLISECONDS 500 -#define PROPERTY_CHANGE_TIMEOUT_SECONDS 2 -#define PROPERTY_CHANGE_RETRIES 3 - -///< Supported Sample rates -static const double gAllSampleRates[] = - { - 44100.0, 48000.0, 88200.0, 96000.0, 176400.0, 192000.0, -1 /* negative terminated list */ - }; - - - -///< Default Supported Buffer Sizes. -static const int gAllBufferSizes[] = - { - 32, 64, 96, 128, 192, 256, 512, 1024, 2048 - }; - - -///< The default SR. -static const int DEFAULT_SR = 44100; -///< The default buffer size. -static const int DEFAULT_BUFFERSIZE = 128; - -static const int NONE_DEVICE_ID = -1; - -///< Number of stalls to wait before notifying user... -static const int NUM_STALLS_FOR_NOTIFICATION = 100; // 100 corresponds to 100 x 42 ms idle timer - about 4 seconds. -static const int CHANGE_CHECK_COUNTER_PERIOD = 100; // 120 corresponds to 120 x 42 ms idle timer - about 4 seconds. - -#define HUNDRED_NANO_TO_MILLI_CONSTANT 10000 -#define CONSUMPTION_CALCULATION_INTERVAL 500 // Milli Seconds - - -// This wrapper is used to adapt device DoIdle method as entry point for MS thread -DWORD WINAPI WCMRPortAudioDevice::__DoIdle__(LPVOID lpThreadParameter) -{ - WCMRPortAudioDevice* pDevice = (WCMRPortAudioDevice*)lpThreadParameter; - pDevice->DoIdle(); - return 0; -} - -//********************************************************************************************** -// WCMRPortAudioDevice::WCMRPortAudioDevice -// -//! Constructor for the audio device. Opens the PA device -//! and gets information about the device. -//! Starts the thread which will process requests to this device -//! such as determining supported sampling rates, buffer sizes, and channel counts. -//! -//! \param *pManager : The audio device manager that's managing this device. -//! \param deviceID : The port audio device ID. -//! \param useMultithreading : Whether to use multi-threading for audio processing. Default is true. -//! -//! \return Nothing. -//! -//********************************************************************************************** -WCMRPortAudioDevice::WCMRPortAudioDevice (WCMRPortAudioDeviceManager *pManager, unsigned int deviceID, bool useMultithreading, bool bNoCopy) : - WCMRNativeAudioDevice (pManager, useMultithreading, bNoCopy) - , m_SampleCounter(0) - , m_BufferSizeChangeRequested (0) - , m_BufferSizeChangeReported (0) - , m_ResetRequested (0) - , m_ResetReported (0) - , m_ResyncRequested (0) - , m_ResyncReported (0) - , m_DropsDetected(0) - , m_DropsReported(0) - , m_IgnoreThisDrop(true) - , m_hDeviceProcessingThread(NULL) - , m_DeviceProcessingThreadID(0) - , m_hUpdateDeviceInfoRequestedEvent(CreateEvent(NULL, FALSE, FALSE, NULL)) - , m_hUpdateDeviceInfoDone(CreateEvent(NULL, FALSE, FALSE, NULL)) - , m_hActivateRequestedEvent(CreateEvent(NULL, FALSE, FALSE, NULL)) - , m_hActivationDone(CreateEvent(NULL, FALSE, FALSE, NULL)) - , m_hDeActivateRequestedEvent(CreateEvent(NULL, FALSE, FALSE, NULL)) - , m_hDeActivationDone(CreateEvent(NULL, FALSE, FALSE, NULL)) - , m_hStartStreamingRequestedEvent(CreateEvent(NULL, FALSE, FALSE, NULL)) - , m_hStartStreamingDone(CreateEvent(NULL, FALSE, FALSE, NULL)) - , m_hStopStreamingRequestedEvent(CreateEvent(NULL, FALSE, FALSE, NULL)) - , m_hStopStreamingDone(CreateEvent(NULL, FALSE, FALSE, NULL)) - , m_hResetRequestedEvent(CreateEvent(NULL, FALSE, FALSE, NULL)) - , m_hResetDone(CreateEvent(NULL, FALSE, FALSE, NULL)) - , m_hResetFromDevRequestedEvent(CreateEvent(NULL, FALSE, FALSE, NULL)) - , m_hBufferSizeChangedEvent(CreateEvent(NULL, FALSE, FALSE, NULL)) - , m_hSampleRateChangedEvent(CreateEvent(NULL, FALSE, FALSE, NULL)) - , m_hExitIdleThread(CreateEvent(NULL, FALSE, FALSE, NULL)) - , m_hDeviceInitialized(CreateEvent(NULL, FALSE, FALSE, NULL)) - , m_lastErr(eNoErr) -{ - AUTO_FUNC_DEBUG; - - //Set initial device info... - m_DeviceID = deviceID; - m_PortAudioStream = NULL; - m_CurrentSamplingRate = DEFAULT_SR; - m_CurrentBufferSize = DEFAULT_BUFFERSIZE; - m_StopRequested = true; - m_pInputData = NULL; - - //initialize device processing thread - //the divice become alive and now is able to process requests - m_hDeviceProcessingThread = CreateThread( NULL, 0, __DoIdle__, (LPVOID)this, 0, &m_DeviceProcessingThreadID ); - - if (!m_hDeviceProcessingThread) - { - DEBUG_MSG("API::Device " << m_DeviceName << " cannot create processing thread"); - throw eGenericErr; - } - - WaitForSingleObject(m_hDeviceInitialized, INFINITE); - - if (ConnectionStatus() == DeviceErrors) - { - throw m_lastErr; - } -} - - -void WCMRPortAudioDevice::initDevice() -{ - // Initialize COM for this thread - std::cout << "API::Device " << m_DeviceID << " initializing COM" << std::endl; - - if (S_OK == CoInitialize(NULL) ) - { - // Initialize PA - Pa_Initialize(); - - updateDeviceInfo(); - - //should use a valid current SR... - if (m_SamplingRates.size()) - { - //see if the current sr is present in the sr list, if not, use the first one! - std::vector<int>::iterator intIter = find(m_SamplingRates.begin(), m_SamplingRates.end(), m_CurrentSamplingRate); - if (intIter == m_SamplingRates.end()) - { - //not found... use the first one - m_CurrentSamplingRate = m_SamplingRates[0]; - } - } - else - std::cout << "API::Device " << m_DeviceName << " Device does not support any sample rate of ours" << std::endl; - - //should use a valid current buffer size - if (m_BufferSizes.size()) - { - //see if the current sr is present in the buffersize list, if not, use the first one! - std::vector<int>::iterator intIter = find(m_BufferSizes.begin(), m_BufferSizes.end(), m_CurrentBufferSize); - if (intIter == m_BufferSizes.end()) - { - //not found... use the first one - m_CurrentBufferSize = m_BufferSizes[0]; - } - } - - //build our input/output level lists - for (unsigned int currentChannel = 0; currentChannel < m_InputChannels.size(); currentChannel++) - { - m_InputLevels.push_back (0.0); - } - - //build our input/output level lists - for (unsigned int currentChannel = 0; currentChannel < m_OutputChannels.size(); currentChannel++) - { - m_OutputLevels.push_back (0.0); - } - - std::cout << "API::Device " << m_DeviceName << " Device has been initialized" << std::endl; - m_ConnectionStatus = DeviceDisconnected; - m_lastErr = eNoErr; - } - else - { - /*Replace with debug trace*/std::cout << "API::Device " << m_DeviceName << " cannot initialize COM" << std::endl; - DEBUG_MSG("Device " << m_DeviceName << " cannot initialize COM"); - m_ConnectionStatus = DeviceErrors; - m_lastErr = eSomeThingNotInitailzed; - SetEvent(m_hExitIdleThread); - } - - SetEvent(m_hDeviceInitialized); -} - -void WCMRPortAudioDevice::terminateDevice() -{ - std::cout << "API::Device " << m_DeviceName << " Terminating DEVICE" << std::endl; - - //If device is streaming, need to stop it! - if (Streaming()) - { - stopStreaming(); - } - - //If device is active (meaning stream is open) we need to close it. - if (Active()) - { - deactivateDevice(); - } - - std::cout << "API::Device " << m_DeviceName << " Terminating PA" << std::endl; - - //Deinitialize PA - Pa_Terminate(); -} - - -//********************************************************************************************** -// WCMRPortAudioDevice::~WCMRPortAudioDevice -// -//! Destructor for the audio device. The base release all the connections that were created, if -//! they have not been already destroyed! Here we simply stop streaming, and close device -//! handles if necessary. -//! -//! \param none -//! -//! \return Nothing. -//! -//********************************************************************************************** -WCMRPortAudioDevice::~WCMRPortAudioDevice () -{ - AUTO_FUNC_DEBUG; - - std::cout << "API::Destroying Device Instance: " << DeviceName() << std::endl; - try - { - //Stop deviceprocessing thread - SignalObjectAndWait(m_hExitIdleThread, m_hDeviceProcessingThread, INFINITE, false); - - std::cout << "API::Device " << m_DeviceName << " Processing Thread is stopped" << std::endl; - - CloseHandle(m_hDeviceProcessingThread); - - //Now it's safe to free all event handlers - CloseHandle(m_hUpdateDeviceInfoRequestedEvent); - CloseHandle(m_hUpdateDeviceInfoDone); - CloseHandle(m_hActivateRequestedEvent); - CloseHandle(m_hActivationDone); - CloseHandle(m_hDeActivateRequestedEvent); - CloseHandle(m_hDeActivationDone); - CloseHandle(m_hStartStreamingRequestedEvent); - CloseHandle(m_hStartStreamingDone); - CloseHandle(m_hStopStreamingRequestedEvent); - CloseHandle(m_hStopStreamingDone); - CloseHandle(m_hResetRequestedEvent); - CloseHandle(m_hResetDone); - CloseHandle(m_hResetFromDevRequestedEvent); - CloseHandle(m_hBufferSizeChangedEvent); - CloseHandle(m_hSampleRateChangedEvent); - CloseHandle(m_hExitIdleThread); - CloseHandle(m_hDeviceInitialized); - } - catch (...) - { - //destructors should absorb exceptions, no harm in logging though!! - DEBUG_MSG ("Exception during destructor"); - } -} - - -WTErr WCMRPortAudioDevice::UpdateDeviceInfo () -{ - std::cout << "API::Device (ID:)" << m_DeviceID << " Updating device info" << std::endl; - - SignalObjectAndWait(m_hUpdateDeviceInfoRequestedEvent, m_hUpdateDeviceInfoDone, INFINITE, false); - - return eNoErr; -} - - -//********************************************************************************************** -// WCMRPortAudioDevice::updateDeviceInfo -// -//! Must be called be device processing thread -//! Updates Device Information about channels, sampling rates, buffer sizes. -//! -//! \return Nothing. -//! -//********************************************************************************************** -void WCMRPortAudioDevice::updateDeviceInfo (bool callerIsWaiting/*=false*/) -{ - AUTO_FUNC_DEBUG; - - //get device info - const PaDeviceInfo *pDeviceInfo = Pa_GetDeviceInfo(m_DeviceID); - - //update name. - m_DeviceName = pDeviceInfo->name; - - //following parameters are needed opening test stream and for sample rates validation - PaStreamParameters inputParameters, outputParameters; - PaStreamParameters *pInS = NULL, *pOutS = NULL; - - inputParameters.device = m_DeviceID; - inputParameters.channelCount = pDeviceInfo->maxInputChannels; - inputParameters.sampleFormat = paFloat32 | paNonInterleaved; - inputParameters.suggestedLatency = 0; /* ignored by Pa_IsFormatSupported() */ - inputParameters.hostApiSpecificStreamInfo = 0; - - if (inputParameters.channelCount) - pInS = &inputParameters; - - outputParameters.device = m_DeviceID; - outputParameters.channelCount = pDeviceInfo->maxOutputChannels; - outputParameters.sampleFormat = paFloat32; - outputParameters.suggestedLatency = 0; /* ignored by Pa_IsFormatSupported() */ - outputParameters.hostApiSpecificStreamInfo = 0; - - if (outputParameters.channelCount) - pOutS = &outputParameters; - - //////////////////////////////////////////////////////////////////////////////////// - //update list of supported SRs... - m_SamplingRates.clear(); - - // now iterate through our standard SRs and check if they are supported by device - // store them for this device - for(int sr=0; gAllSampleRates[sr] > 0; sr++) - { - PaError err = Pa_IsFormatSupported(pInS, pOutS, gAllSampleRates[sr]); - if( err == paFormatIsSupported) - { - m_SamplingRates.push_back ((int)gAllSampleRates[sr]); - } - } - - /////////////////////////////////////////////////////////////////////////////////// - //update buffer sizes - m_BufferSizes.clear(); - bool useDefaultBuffers = true; - - // In ASIO Windows, the buffer size is set from the sound device manufacturer's control panel - long minSize, maxSize, preferredSize, granularity; - PaError err = PaAsio_GetAvailableBufferSizes(m_DeviceID, &minSize, &maxSize, &preferredSize, &granularity); - - if (err == paNoError) - { - std::cout << "API::Device " << m_DeviceName << " Buffers: " << minSize << " " << maxSize << " " << preferredSize << std::endl; - - m_BufferSizes.push_back (preferredSize); - useDefaultBuffers = false; - } - else - { - std::cout << "API::Device" << m_DeviceName << " Preffered buffer size is not supported" << std::endl; - } - - if (useDefaultBuffers) - { - std::cout << "API::Device" << m_DeviceName << " Using default buffer sizes " <<std::endl; - for(int bsize=0; bsize < (sizeof(gAllBufferSizes)/sizeof(gAllBufferSizes[0])); bsize++) - m_BufferSizes.push_back (gAllBufferSizes[bsize]); - } - - ///////////////////////////////////////////////////////////////////////////////////////// - //update channels info - { - int maxInputChannels = pDeviceInfo->maxInputChannels; - int maxOutputChannels = pDeviceInfo->maxOutputChannels; - - //Update input channels - m_InputChannels.clear(); - for (int channel = 0; channel < maxInputChannels; channel++) - { - const char* channelName[32]; // 32 is max leth declared by PortAudio for this operation - std::stringstream chNameStream; - - PaError error = PaAsio_GetInputChannelName(m_DeviceID, channel, channelName); - - chNameStream << (channel+1) << " - "; - - if (error == paNoError) - { - chNameStream << *channelName; - } - else - { - chNameStream << "Input " << (channel+1); - } - - m_InputChannels.push_back (chNameStream.str()); - } - - - //Update output channels - m_OutputChannels.clear(); - for (int channel = 0; channel < maxOutputChannels; channel++) - { - const char* channelName[32]; // 32 is max leth declared by PortAudio for this operation - std::stringstream chNameStream; - - PaError error = PaAsio_GetOutputChannelName(m_DeviceID, channel, channelName); - - chNameStream << (channel+1) << " - "; - - if (error == paNoError) - { - chNameStream << *channelName; - } - else - { - chNameStream << "Output " << (channel+1); - } - - m_OutputChannels.push_back (chNameStream.str()); - } - } - - std::cout << "API::Device" << m_DeviceName << " Device info update has been finished" << std::endl; - - if (callerIsWaiting) - SetEvent(m_hUpdateDeviceInfoDone); -} - - -PaError WCMRPortAudioDevice::testStateValidness(int sampleRate, int bufferSize) -{ - PaError paErr = paNoError; - - //get device info - const PaDeviceInfo *pDeviceInfo = Pa_GetDeviceInfo(m_DeviceID); - - //following parameters are needed opening test stream and for sample rates validation - PaStreamParameters inputParameters, outputParameters; - PaStreamParameters *pInS = NULL, *pOutS = NULL; - - inputParameters.device = m_DeviceID; - inputParameters.channelCount = pDeviceInfo->maxInputChannels; - inputParameters.sampleFormat = paFloat32 | paNonInterleaved; - inputParameters.suggestedLatency = 0; - inputParameters.hostApiSpecificStreamInfo = 0; - - if (inputParameters.channelCount) - pInS = &inputParameters; - - outputParameters.device = m_DeviceID; - outputParameters.channelCount = pDeviceInfo->maxOutputChannels; - outputParameters.sampleFormat = paFloat32; - outputParameters.suggestedLatency = 0; - outputParameters.hostApiSpecificStreamInfo = 0; - - if (outputParameters.channelCount) - pOutS = &outputParameters; - - PaStream *portAudioStream = NULL; - - //sometimes devices change buffer size if sample rate changes - //it updates buffer size during stream opening - //we need to find out how device would behave with current sample rate - //try opening test stream to load device driver for current sample rate and buffer size - paErr = Pa_OpenStream (&portAudioStream, pInS, pOutS, sampleRate, bufferSize, paDitherOff, NULL, NULL); - - if (portAudioStream) - { - // close test stream - Pa_CloseStream (portAudioStream); - portAudioStream = NULL; - } - - return paErr; -} - - -//********************************************************************************************** -// WCMRPortAudioDevice::CurrentSamplingRate -// -//! The device's current sampling rate. This may be overridden, if the device needs to -//! query the driver for the current rate. -//! -//! \param none -//! -//! \return The device's current sampling rate. -1 on error. -//! -//********************************************************************************************** -int WCMRPortAudioDevice::CurrentSamplingRate () -{ - AUTO_FUNC_DEBUG; - //ToDo: Perhaps for ASIO devices that are active, we should retrive the SR from the device... - - return (m_CurrentSamplingRate); -} - - -WTErr WCMRPortAudioDevice::SetActive (bool newState) -{ - if (newState == true) - { - std::cout << "API::Device " << m_DeviceName << " Activation requested" << std::endl; - SignalObjectAndWait(m_hActivateRequestedEvent, m_hActivationDone, INFINITE, false); - } - else - { - std::cout << "API::Device " << m_DeviceName << " Deactivation requested" << std::endl; - SignalObjectAndWait(m_hDeActivateRequestedEvent, m_hDeActivationDone, INFINITE, false); - } - - if (newState == Active() ) - return eNoErr; - else - return eGenericErr; -} - - -WTErr WCMRPortAudioDevice::SetStreaming (bool newState) -{ - if (newState == true) - { - std::cout << "API::Device " << m_DeviceName << " Stream start requested" << std::endl; - SignalObjectAndWait(m_hStartStreamingRequestedEvent, m_hStartStreamingDone, INFINITE, false); - } - else - { - std::cout << "API::Device " << m_DeviceName << " Stream stop requested" << std::endl; - SignalObjectAndWait(m_hStopStreamingRequestedEvent, m_hStopStreamingDone, INFINITE, false); - } - - if (newState == Streaming() ) - return eNoErr; - else - return eGenericErr; -} - - -WTErr WCMRPortAudioDevice::ResetDevice() -{ - std::cout << "API::Device: " << m_DeviceName << " Reseting device" << std::endl; - - SignalObjectAndWait(m_hResetRequestedEvent, m_hResetDone, INFINITE, false); - - if (ConnectionStatus() == DeviceErrors) - { - return m_lastErr; - } - - return eNoErr; -} - - -//********************************************************************************************** -// WCMRPortAudioDevice::SetCurrentSamplingRate -// -//! Change the sampling rate to be used by the device. -//! -//! \param newRate : The rate to use (samples per sec). -//! -//! \return eNoErr always. The derived classes may return error codes. -//! -//********************************************************************************************** -WTErr WCMRPortAudioDevice::SetCurrentSamplingRate (int newRate) -{ - AUTO_FUNC_DEBUG; - std::vector<int>::iterator intIter; - WTErr retVal = eNoErr; - - //changes the status. - int oldRate = CurrentSamplingRate(); - bool oldActive = Active(); - - //no change, nothing to do - if (oldRate == newRate) - return (retVal); - - //see if this is one of our supported rates... - intIter = find(m_SamplingRates.begin(), m_SamplingRates.end(), newRate); - - if (intIter == m_SamplingRates.end()) - { - //Can't change, perhaps use an "invalid param" type of error - retVal = eCommandLineParameter; - return (retVal); - } - - if (Streaming()) - { - //Can't change, perhaps use an "in use" type of error - retVal = eGenericErr; - return (retVal); - } - - //make the change... - m_CurrentSamplingRate = newRate; - PaError paErr = PaAsio_SetStreamSampleRate (m_PortAudioStream, m_CurrentSamplingRate); - Pa_Sleep(PROPERTY_CHANGE_SLEEP_TIME_MILLISECONDS); // sleep some time to make sure the change has place - - if (paErr != paNoError) - { - std::cout << "Sample rate change failed: " << Pa_GetErrorText (paErr) << std::endl; - if (paErr == paUnanticipatedHostError) - std::cout << "Details: "<< Pa_GetLastHostErrorInfo ()->errorText << "; code: " << Pa_GetLastHostErrorInfo ()->errorCode << std::endl; - - retVal = eWrongObjectState; - } - - return (retVal); -} - - -//********************************************************************************************** -// WCMRPortAudioDevice::CurrentBufferSize -// -//! The device's current buffer size in use. This may be overridden, if the device needs to -//! query the driver for the current size. -//! -//! \param none -//! -//! \return The device's current buffer size. 0 on error. -//! -//********************************************************************************************** -int WCMRPortAudioDevice::CurrentBufferSize () -{ - return m_CurrentBufferSize; -} - - -//********************************************************************************************** -// WCMRPortAudioDevice::SetCurrentBufferSize -// -//! Change the buffer size to be used by the device. This will most likely be overridden, -//! the base class simply updates the member variable. -//! -//! \param newSize : The buffer size to use (in sample-frames) -//! -//! \return eNoErr always. The derived classes may return error codes. -//! -//********************************************************************************************** -WTErr WCMRPortAudioDevice::SetCurrentBufferSize (int newSize) -{ - AUTO_FUNC_DEBUG; - WTErr retVal = eNoErr; - std::vector<int>::iterator intIter; - - if (Streaming()) - { - //Can't change, perhaps use an "in use" type of error - retVal = eGenericErr; - return (retVal); - } - - // Buffer size for ASIO devices can be changed from the control panel only - // We have driver driven logi here - if (m_CurrentBufferSize != newSize ) - { - // we have only one aloved buffer size which is preffered by PA - // this is the only value which could be set - newSize = m_BufferSizes[0]; - int bufferSize = newSize; - // notify client to update buffer size - m_pMyManager->NotifyClient (WCMRAudioDeviceManagerClient::BufferSizeChanged, (void *)&bufferSize); - return retVal; - } - - return (retVal); -} - - -//********************************************************************************************** -// WCMRPortAudioDevice::ConnectionStatus -// -//! Retrieves the device's current connection status. This will most likely be overridden, -//! in case some driver communication is required to query the status. -//! -//! \param none -//! -//! \return A ConnectionStates value. -//! -//********************************************************************************************** -WCMRPortAudioDevice::ConnectionStates WCMRPortAudioDevice::ConnectionStatus () -{ - AUTO_FUNC_DEBUG; - //ToDo: May want to do something more to extract the actual status! - return (m_ConnectionStatus); - -} - - -//********************************************************************************************** -// WCMRPortAudioDevice::activateDevice -// -//! IS CALLED BY PROCESS THREAD -//! Sets the device into "active" state. Essentially, opens the PA device. -//! If it's an ASIO device it may result in buffer size change in some cases. -//! -//********************************************************************************************** -void WCMRPortAudioDevice::activateDevice (bool callerIsWaiting/*=false*/) -{ - AUTO_FUNC_DEBUG; - - PaError paErr = paNoError; - - // if device is not active activate it - if (!Active() ) - { - PaStreamParameters inputParameters, outputParameters; - PaStreamParameters *pInS = NULL, *pOutS = NULL; - - const PaDeviceInfo *pDeviceInfo = Pa_GetDeviceInfo(m_DeviceID); - const PaHostApiInfo *pHostApiInfo = Pa_GetHostApiInfo(pDeviceInfo->hostApi); - - inputParameters.device = m_DeviceID; - inputParameters.channelCount = (int)m_InputChannels.size(); - inputParameters.sampleFormat = paFloat32 | paNonInterleaved; - inputParameters.suggestedLatency = Pa_GetDeviceInfo(m_DeviceID)->defaultLowInputLatency; - inputParameters.hostApiSpecificStreamInfo = 0; - - if (inputParameters.channelCount) - pInS = &inputParameters; - - outputParameters.device = m_DeviceID; - outputParameters.channelCount = (int)m_OutputChannels.size(); - outputParameters.sampleFormat = paFloat32; - outputParameters.suggestedLatency = Pa_GetDeviceInfo(m_DeviceID)->defaultLowOutputLatency; - outputParameters.hostApiSpecificStreamInfo = 0; - - if (outputParameters.channelCount) - pOutS = &outputParameters; - - std::cout << "API::Device " << m_DeviceName << " Opening device stream " << std::endl; - std::cout << "Sample rate: " << m_CurrentSamplingRate << " buffer size: " << m_CurrentBufferSize << std::endl; - paErr = Pa_OpenStream(&m_PortAudioStream, - pInS, - pOutS, - m_CurrentSamplingRate, - m_CurrentBufferSize, - paDitherOff, - WCMRPortAudioDevice::TheCallback, - this); - - if(paErr != paNoError) - { - std::cout << "Cannot open streamm with buffer: "<< m_CurrentBufferSize << " Error: " << Pa_GetErrorText (paErr) << std::endl; - - if (paErr == paUnanticipatedHostError) - std::cout << "Error details: "<< Pa_GetLastHostErrorInfo ()->errorText << "; code: " << Pa_GetLastHostErrorInfo ()->errorCode << std::endl; - } - - if(paErr == paNoError) - { - std::cout << "Stream has been opened! "<< std::endl; - - // check for possible changes - long minSize, maxSize, preferredSize, granularity; - PaError paErr = PaAsio_GetAvailableBufferSizes(m_DeviceID, &minSize, &maxSize, &preferredSize, &granularity); - - std::cout << "Checked if buffer size changed "<< std::endl; - if (paErr == paNoError && m_CurrentBufferSize != preferredSize) - { - std::cout << "Buffer size has changed "<< std::endl; - m_CurrentBufferSize = preferredSize; - m_BufferSizes.clear(); - m_BufferSizes.push_back(preferredSize); - m_pMyManager->NotifyClient (WCMRAudioDeviceManagerClient::BufferSizeChanged, (void *)&preferredSize); - } - - m_DropsDetected = 0; - m_DropsReported = 0; - m_IgnoreThisDrop = true; - - if (pHostApiInfo->type == paASIO) - { - m_BufferSizeChangeRequested = 0; - m_BufferSizeChangeReported = 0; - m_ResetRequested = 0; - m_ResetReported = 0; - m_ResyncRequested = 0; - m_ResyncReported = 0; - std::cout << "Installing new mesage hook "<< std::endl; - PaAsio_SetMessageHook (StaticASIOMessageHook, this); - } - m_IsActive = true; - m_ConnectionStatus = DeviceAvailable; - m_lastErr = eNoErr; - } - else - { - //failed, do not update device state - std::cout << "Failed to open pa stream: " << Pa_GetErrorText (paErr) << std::endl; - DEBUG_MSG( "Failed to open pa stream: " << Pa_GetErrorText (paErr) ); - m_ConnectionStatus = DeviceErrors; - m_lastErr = eAsioFailed; - } - - - } - - std::cout << "Activation is DONE "<< std::endl; - - if (callerIsWaiting) - SetEvent(m_hActivationDone); -} - - -//********************************************************************************************** -// WCMRPortAudioDevice::deactivateDevice -// -//! IS CALLED BY PROCESS THREAD -//! Sets the device into "inactive" state. Essentially, closes the PA device. -//! -//********************************************************************************************** -void WCMRPortAudioDevice::deactivateDevice (bool callerIsWaiting/*=false*/) -{ - AUTO_FUNC_DEBUG; - - PaError paErr = paNoError; - - if (Active() ) - { - if (Streaming()) - { - stopStreaming (); - } - - if (m_PortAudioStream) - { - //close the stream first - std::cout << "API::Device" << m_DeviceName << " Closing device stream" << std::endl; - paErr = Pa_CloseStream (m_PortAudioStream); - if(paErr == paNoError) - { - m_PortAudioStream = NULL; - m_DropsDetected = 0; - m_DropsReported = 0; - m_IgnoreThisDrop = true; - m_BufferSizeChangeRequested = 0; - m_BufferSizeChangeReported = 0; - m_ResetRequested = 0; - m_ResetReported = 0; - m_ResyncRequested = 0; - m_ResyncReported = 0; - PaAsio_SetMessageHook (NULL, NULL); - - //finaly set device state to "not active" - m_IsActive = false; - m_ConnectionStatus = DeviceDisconnected; - m_lastErr = eNoErr; - } - else - { - //failed, do not update device state - std::cout << "Failed to close pa stream stream " << Pa_GetErrorText (paErr) << std::endl; - DEBUG_MSG( "Failed to open pa stream stream " << Pa_GetErrorText (paErr) ); - m_ConnectionStatus = DeviceErrors; - m_lastErr = eAsioFailed; - } - } - } - - if (callerIsWaiting) - SetEvent(m_hDeActivationDone); -} - - -//********************************************************************************************** -// WCMRPortAudioDevice::startStreaming -// -//! Sets the devices into "streaming" state. Calls PA's Start stream routines. -//! This roughly corresponds to calling Start on the lower level interface. -//! -//********************************************************************************************** -void WCMRPortAudioDevice::startStreaming (bool callerIsWaiting/*=false*/) -{ - AUTO_FUNC_DEBUG; - - // proceed if the device is not streaming - if (!Streaming () ) - { - PaError paErr = paNoError; - m_StopRequested = false; - m_SampleCounter = 0; - - std::cout << "API::Device" << m_DeviceName << " Starting device stream" << std::endl; - - //get device info - const PaDeviceInfo *pDeviceInfo = Pa_GetDeviceInfo(m_DeviceID); - - unsigned int inChannelCount = pDeviceInfo->maxInputChannels; - unsigned int outChannelCount = pDeviceInfo->maxOutputChannels; - - // Prepare for streaming - tell Engine to do the initialization for process callback - m_pMyManager->NotifyClient (WCMRAudioDeviceManagerClient::DeviceStartsStreaming); - - paErr = Pa_StartStream( m_PortAudioStream ); - - if(paErr == paNoError) - { - // if the stream was started successfully - m_IsStreaming = true; - std::cout << "API::Device" << m_DeviceName << " Device is streaming" << std::endl; - } - else - { - std::cout << "Failed to start PA stream: " << Pa_GetErrorText (paErr) << std::endl; - DEBUG_MSG( "Failed to start PA stream: " << Pa_GetErrorText (paErr) ); - m_lastErr = eGenericErr; - } - } - - if (callerIsWaiting) - SetEvent(m_hStartStreamingDone); -} - - -//********************************************************************************************** -// WCMRPortAudioDevice::stopStreaming -// -//! Sets the devices into "not streaming" state. Calls PA's Stop stream routines. -//! This roughly corresponds to calling Stop on the lower level interface. -//! -//********************************************************************************************** -void WCMRPortAudioDevice::stopStreaming (bool callerIsWaiting/*=false*/) -{ - AUTO_FUNC_DEBUG; - - // proceed if the device is streaming - if (Streaming () ) - { - PaError paErr = paNoError; - m_StopRequested = true; - - std::cout << "API::Device " << m_DeviceName << " Stopping device stream" << std::endl; - paErr = Pa_StopStream( m_PortAudioStream ); - - if(paErr == paNoError || paErr == paStreamIsStopped) - { - // if the stream was stopped successfully - m_IsStreaming = false; - m_pInputData = NULL; - } - else - { - std::cout << "Failed to stop PA stream normaly! Error:" << Pa_GetErrorText (paErr) << std::endl; - DEBUG_MSG( "Failed to stop PA stream normaly! Error:" << Pa_GetErrorText (paErr) ); - m_lastErr = eGenericErr; - } - } - - if (callerIsWaiting) - SetEvent(m_hStopStreamingDone); -} - - -//********************************************************************************************** -// WCMRPortAudioDevice::resetDevice -// -//! Resets the device, updates device info. Importnat: does PA reinitialization calling -//! Pa_terminate/Pa_initialize functions. -//! -//! \param none -//! -//! \return nothing -//! -//********************************************************************************************** -void WCMRPortAudioDevice::resetDevice (bool callerIsWaiting /*=false*/ ) -{ - PaError paErr = paNoError; - - // Keep device sates - bool wasStreaming = Streaming(); - bool wasActive = Active(); - - // Reset the device - stopStreaming(); - deactivateDevice(); - - // Cache device buffer size as it might be changed during reset - int oldBufferSize = m_CurrentBufferSize; - - // Now, validate the state and update device info if required - unsigned int retry = PROPERTY_CHANGE_RETRIES; - while (retry-- ) - { - // Reinitialize PA - Pa_Terminate(); - Pa_Initialize(); - - std::cout << "Updating device state... " << std::endl; - // update device info - updateDeviceInfo(); - - // take up buffers - long minSize, maxSize, preferredSize, granularity; - PaError paErr = PaAsio_GetAvailableBufferSizes(m_DeviceID, &minSize, &maxSize, &preferredSize, &granularity); - - if (paErr != paNoError) - { - continue; - } - m_CurrentBufferSize = preferredSize; - - paErr = testStateValidness(m_CurrentSamplingRate, m_CurrentBufferSize); - if (paNoError == paErr) - { - std::cout << "Device state is valid" << std::endl; - break; - } - - std::cout << "Cannot start with current state: sr: " << m_CurrentSamplingRate << " bs:" << m_CurrentBufferSize \ - << "\nReason: " << Pa_GetErrorText (paErr) << std::endl; - if (paErr == paUnanticipatedHostError) - std::cout << "Details: "<< Pa_GetLastHostErrorInfo ()->errorText << "; code: " << Pa_GetLastHostErrorInfo ()->errorCode << std::endl; - - std::cout << "Will try again in " << DEVICE_INFO_UPDATE_SLEEP_TIME_MILLISECONDS << "msec" << std::endl; - - Pa_Sleep(DEVICE_INFO_UPDATE_SLEEP_TIME_MILLISECONDS); - } - - if (paErr == paNoError) - { - // Notify the Application about device setting changes - if (oldBufferSize != m_CurrentBufferSize) - { - std::cout << "API::Device" << m_DeviceName << " buffer size changed" << std::endl; - int bufferSize = m_CurrentBufferSize; - m_pMyManager->NotifyClient (WCMRAudioDeviceManagerClient::BufferSizeChanged, (void *)&bufferSize); - } - - // Activate the device if it was active before - if (wasActive) - activateDevice(); - - // Resume streaming if the device was streaming before - if(wasStreaming && m_lastErr == eNoErr && m_ConnectionStatus == DeviceAvailable) - { - // start streaming - startStreaming(); - } - } else { - m_ConnectionStatus = DeviceErrors; - m_lastErr = eWrongObjectState; - } - - if (callerIsWaiting) - SetEvent(m_hResetDone); -} - - -#ifdef PLATFORM_WINDOWS - -long WCMRPortAudioDevice::StaticASIOMessageHook (void *pRefCon, long selector, long value, void* message, double* opt) -{ - if (pRefCon) - { - return ((WCMRPortAudioDevice*)(pRefCon))->ASIOMessageHook (selector, value, message, opt); - } - else - return -1; -} - -long WCMRPortAudioDevice::ASIOMessageHook (long selector, long WCUNUSEDPARAM(value), void* WCUNUSEDPARAM(message), double* WCUNUSEDPARAM(opt)) -{ - switch(selector) - { - case kAsioResyncRequest: - m_ResyncRequested++; - std::cout << "\t\t\tWCMRPortAudioDevice::ASIOMessageHook -- kAsioResyncRequest" << std::endl; - break; - - case kAsioLatenciesChanged: - m_BufferSizeChangeRequested++; - std::cout << "\t\t\tWCMRPortAudioDevice::ASIOMessageHook -- kAsioLatenciesChanged" << std::endl; - if (m_ResetRequested == 0) { - m_ResetRequested++; - m_pMyManager->NotifyClient (WCMRAudioDeviceManagerClient::RequestReset); - } - break; - - case kAsioBufferSizeChange: - m_BufferSizeChangeRequested++; - std::cout << "\t\t\tWCMRPortAudioDevice::ASIOMessageHook -- m_BufferSizeChangeRequested" << std::endl; - if (m_ResetRequested == 0) { - m_ResetRequested++; - m_pMyManager->NotifyClient (WCMRAudioDeviceManagerClient::RequestReset); - } - break; - - case kAsioResetRequest: - std::cout << "\t\t\tWCMRPortAudioDevice::ASIOMessageHook -- kAsioResetRequest" << std::endl; - m_ResetRequested++; - m_pMyManager->NotifyClient (WCMRAudioDeviceManagerClient::RequestReset); - break; - - case kAsioOverload: - m_DropsDetected++; - std::cout << "\t\t\tWCMRPortAudioDevice::ASIOMessageHook -- kAsioOverload" << std::endl; - m_pMyManager->NotifyClient (WCMRAudioDeviceManagerClient::Dropout); - break; - } - return 0; -} - -#endif - - -//********************************************************************************************** -// WCMRPortAudioDevice::DoIdle -// -//! A place for doing idle time processing. The other derived classes will probably do something -//! meaningful. -//! -//! \param none -//! -//! \return eNoErr always. -//! -//********************************************************************************************** -WTErr WCMRPortAudioDevice::DoIdle () -{ - WTErr retVal = eNoErr; - - std::cout << "WCMRPortAudioDevice::DoIdle ()" << std::endl; - HANDLE hEvents[] = - { - m_hUpdateDeviceInfoRequestedEvent, - m_hActivateRequestedEvent, - m_hDeActivateRequestedEvent, - m_hStartStreamingRequestedEvent, - m_hStopStreamingRequestedEvent, - m_hBufferSizeChangedEvent, - m_hSampleRateChangedEvent, - m_hResetRequestedEvent, - m_hResetFromDevRequestedEvent, - m_hExitIdleThread - }; - - const size_t hEventsSize = sizeof(hEvents)/sizeof(hEvents[0]); - - initDevice(); - - for(;;) - { - DWORD result = WaitForMultipleObjects (hEventsSize, hEvents, FALSE, INFINITE); - result = result - WAIT_OBJECT_0; - - if ((result < 0) || (result >= hEventsSize)) { - std::cout << "\t\t\t\t\t\t\tWCMRPortAudioDevice::DoIdle () -> (result < 0) || (result >= hEventsSize):" << result << std::endl; - retVal = eGenericErr; - break; - } - - if (hEvents[result] == m_hExitIdleThread) { - std::cout << "\t\t\t\t\t\t\tWCMRPortAudioDevice::DoIdle () -> m_hExitIdleThread" << result << std::endl; - retVal = eNoErr; - break; - } - - if (hEvents[result] == m_hUpdateDeviceInfoRequestedEvent) { - std::cout << "\t\t\t\t\t\tupdate requested ..." << std::endl; - updateDeviceInfo(true); - } - - if (hEvents[result] == m_hActivateRequestedEvent) { - std::cout << "\t\t\t\t\t\tactivation requested ..." << std::endl; - activateDevice(true); - } - - if (hEvents[result] == m_hDeActivateRequestedEvent) { - std::cout << "\t\t\t\t\t\tdeactivation requested ..." << std::endl; - deactivateDevice(true); - } - - if (hEvents[result] == m_hStartStreamingRequestedEvent) { - std::cout << "\t\t\t\t\t\tStart stream requested ..." << std::endl; - startStreaming(true); - } - - if (hEvents[result] == m_hStopStreamingRequestedEvent) { - std::cout << "\t\t\t\t\t\tStop stream requested ..." << std::endl; - stopStreaming(true); - } - - if (hEvents[result] == m_hResetRequestedEvent) { - std::cout << "\t\t\t\t\t\treset requested ..." << std::endl; - resetDevice(true); - } - - if (hEvents[result] == m_hResetFromDevRequestedEvent) { - std::cout << "\t\t\t\t\t\treset requested from device..." << std::endl; - resetDevice(); - } - - if (hEvents[result] == m_hBufferSizeChangedEvent) { - std::cout << "\t\t\t\t\t\tbuffer size changed from device..." << std::endl; - m_pMyManager->NotifyClient (WCMRAudioDeviceManagerClient::BufferSizeChanged); - } - - if (hEvents[result] == m_hSampleRateChangedEvent) { - std::cout << "\t\t\t\t\t\tsample rate changed from device..." << std::endl; - m_pMyManager->NotifyClient (WCMRAudioDeviceManagerClient::SamplingRateChanged); - } - } - - terminateDevice(); - - return retVal; -} - - -//********************************************************************************************** -// WCMRPortAudioDevice::SetMonitorChannels -// -//! Used to set the channels to be used for monitoring. -//! -//! \param leftChannel : Left monitor channel index. -//! \param rightChannel : Right monitor channel index. -//! -//! \return eNoErr always, the derived classes may return appropriate errors. -//! -//********************************************************************************************** -WTErr WCMRPortAudioDevice::SetMonitorChannels (int leftChannel, int rightChannel) -{ - AUTO_FUNC_DEBUG; - //This will most likely be overridden, the base class simply - //changes the member. - m_LeftMonitorChannel = leftChannel; - m_RightMonitorChannel = rightChannel; - return (eNoErr); -} - - - -//********************************************************************************************** -// WCMRPortAudioDevice::SetMonitorGain -// -//! Used to set monitor gain (or atten). -//! -//! \param newGain : The new gain or atten. value to use. Specified as a linear multiplier (not dB) -//! -//! \return eNoErr always, the derived classes may return appropriate errors. -//! -//********************************************************************************************** -WTErr WCMRPortAudioDevice::SetMonitorGain (float newGain) -{ - AUTO_FUNC_DEBUG; - //This will most likely be overridden, the base class simply - //changes the member. - - m_MonitorGain = newGain; - return (eNoErr); -} - - - - -//********************************************************************************************** -// WCMRPortAudioDevice::ShowConfigPanel -// -//! Used to show device specific config/control panel. Some interfaces may not support it. -//! Some interfaces may require the device to be active before it can display a panel. -//! -//! \param pParam : A device/interface specific parameter, should be the app window handle for ASIO. -//! -//! \return eNoErr always, the derived classes may return errors. -//! -//********************************************************************************************** -WTErr WCMRPortAudioDevice::ShowConfigPanel (void *pParam) -{ - AUTO_FUNC_DEBUG; - WTErr retVal = eNoErr; - - if (Active() && !m_ResetRequested ) - { -#ifdef PLATFORM_WINDOWS - if(Pa_GetHostApiInfo(Pa_GetDeviceInfo(m_DeviceID)->hostApi)->type == paASIO) - { - // stop and deactivate the device - bool wasStreaming = Streaming(); - SetActive(false); - - // show control panel for the device - if (PaAsio_ShowControlPanel (m_DeviceID, pParam) != paNoError) - retVal = eGenericErr; - - // restore previous state for the device - SetActive(true); - if (wasStreaming) - SetStreaming(true); - - - // reset device to pick up changes - if (!m_ResetRequested) { - m_pMyManager->NotifyClient (WCMRAudioDeviceManagerClient::RequestReset); - } - } -#else - pParam = pParam; -#endif //_windows - } - - return (retVal); -} - - -//***************************************************************************************************** -// WCMRPortAudioDevice::TheCallback -// -//! The (static) Port Audio Callback function. This is a static member. It calls on the AudioCallback in the -//! WCMRPortAudioDevice to do the real work. -//! -//! \param pInputBuffer: pointer to input buffer. -//! \param pOutputBuffer: pointer to output buffer. -//! \param framesPerBuffer: number of sample frames per buffer. -//! \param pTimeInfo: time info for PaStream callback. -//! \param statusFlags: -//! \param pUserData: pointer to user data, in our case the WCMRPortAudioDevice object. -//! -//! \return true to stop streaming else returns false. -//****************************************************************************************************** -int WCMRPortAudioDevice::TheCallback (const void *pInputBuffer, void *pOutputBuffer, unsigned long framesPerBuffer, - const PaStreamCallbackTimeInfo* /*pTimeInfo*/, PaStreamCallbackFlags statusFlags, void *pUserData ) -{ - WCMRPortAudioDevice *pMyDevice = (WCMRPortAudioDevice *)pUserData; - if (pMyDevice) - return pMyDevice->AudioCallback ((float *)pInputBuffer, (float *)pOutputBuffer, framesPerBuffer, - (statusFlags & (paInputOverflow | paOutputUnderflow)) != 0); - else - return (true); - -} - - - -//********************************************************************************************** -// WCMRPortAudioDevice::AudoiCallback -// -//! Here's where the actual audio processing happens. We call upon all the active connections' -//! sinks to provide data to us which can be put/mixed in the output buffer! Also, we make the -//! input data available to any sources that may call upon us during this time! -//! -//! \param *pInputBuffer : Points to a buffer with recorded data. -//! \param *pOutputBuffer : Points to a buffer to receive playback data. -//! \param framesPerBuffer : Number of sample frames in input and output buffers. Number of channels, -//! which are interleaved, is fixed at Device Open (Active) time. In this implementation, -//! the number of channels are fixed to use the maximum available. -//! \param dropsDetected : True if dropouts were detected in input or output. Can be used to signal the GUI. -//! -//! \return true -//! -//********************************************************************************************** -int WCMRPortAudioDevice::AudioCallback( const float *pInputBuffer, float *pOutputBuffer, unsigned long framesPerBuffer, bool dropsDetected ) -{ - UMicroseconds theStartTime; - - // detect drops - if (dropsDetected) - { - if (m_IgnoreThisDrop) - m_IgnoreThisDrop = false; //We'll ignore once, just once! - else - m_DropsDetected++; - } - - m_pInputData = pInputBuffer; - - // VKamyshniy: Is this a right place to call the client???: - struct WCMRAudioDeviceManagerClient::AudioCallbackData audioCallbackData = - { - m_pInputData, - pOutputBuffer, - framesPerBuffer, - m_SampleCounter, - theStartTime.MicroSeconds()*1000 - }; - - m_pMyManager->NotifyClient (WCMRAudioDeviceManagerClient::AudioCallback, (void *)&audioCallbackData ); - - //Don't try to access after this call returns! - m_pInputData = NULL; - - m_SampleCounter += framesPerBuffer; - - return m_StopRequested; -} - - - - -//********************************************************************************************** -// WCMRPortAudioDeviceManager::WCMRPortAudioDeviceManager -// -//! The constructuor, we initialize PA, and build the device list. -//! -//! \param *pTheClient : The manager's client object (which receives notifications). -//! \param interfaceType : The PortAudio interface type to use for this manager - acts as a filter. -//! \param useMultithreading : Whether to use multi-threading for audio processing. Default is true. -//! -//! \return Nothing. -//! -//********************************************************************************************** -WCMRPortAudioDeviceManager::WCMRPortAudioDeviceManager (WCMRAudioDeviceManagerClient *pTheClient, - eAudioDeviceFilter eCurAudioDeviceFilter, bool useMultithreading, bool bNocopy) - : WCMRAudioDeviceManager (pTheClient, eCurAudioDeviceFilter) - , m_NoneDevice(0) - , m_UseMultithreading(useMultithreading) - , m_bNoCopyAudioBuffer(bNocopy) -{ - AUTO_FUNC_DEBUG; - std::cout << "API::PortAudioDeviceManager::PA Device manager constructor" << std::endl; - - //Always create the None device first... - m_NoneDevice = new WCMRNativeAudioNoneDevice(this); - - WTErr err = generateDeviceListImpl(); - - if (eNoErr != err) - throw err; - - timeBeginPeriod (1); -} - - -//********************************************************************************************** -// WCMRPortAudioDeviceManager::~WCMRPortAudioDeviceManager -// -//! It clears the device list, releasing each of the device. -//! -//! \param none -//! -//! \return Nothing. -//! -//********************************************************************************************** -WCMRPortAudioDeviceManager::~WCMRPortAudioDeviceManager() -{ - AUTO_FUNC_DEBUG; - - std::cout << "API::Destroying PortAudioDeviceManager " << std::endl; - - try - { - delete m_NoneDevice; - } - catch (...) - { - //destructors should absorb exceptions, no harm in logging though!! - DEBUG_MSG ("Exception during destructor"); - } - - timeEndPeriod (1); -} - - -WCMRAudioDevice* WCMRPortAudioDeviceManager::initNewCurrentDeviceImpl(const std::string & deviceName) -{ - destroyCurrentDeviceImpl(); - - std::cout << "API::PortAudioDeviceManager::initNewCurrentDevice " << deviceName << std::endl; - if (deviceName == m_NoneDevice->DeviceName() ) - { - m_CurrentDevice = m_NoneDevice; - return m_CurrentDevice; - } - - DeviceInfo devInfo; - WTErr err = GetDeviceInfoByName(deviceName, devInfo); - - if (eNoErr == err) - { - try - { - std::cout << "API::PortAudioDeviceManager::Creating PA device: " << devInfo.m_DeviceId << ", Device Name: " << devInfo.m_DeviceName << std::endl; - TRACE_MSG ("API::PortAudioDeviceManager::Creating PA device: " << devInfo.m_DeviceId << ", Device Name: " << devInfo.m_DeviceName); - - m_CurrentDevice = new WCMRPortAudioDevice (this, devInfo.m_DeviceId, m_UseMultithreading, m_bNoCopyAudioBuffer); - } - catch (...) - { - std::cout << "Unabled to create PA Device: " << devInfo.m_DeviceId << std::endl; - DEBUG_MSG ("Unabled to create PA Device: " << devInfo.m_DeviceId); - } - } - - return m_CurrentDevice; -} - - -void WCMRPortAudioDeviceManager::destroyCurrentDeviceImpl() -{ - if (m_CurrentDevice != m_NoneDevice) - delete m_CurrentDevice; - - m_CurrentDevice = 0; -} - - -WTErr WCMRPortAudioDeviceManager::getDeviceAvailableSampleRates(DeviceID deviceId, std::vector<int>& sampleRates) -{ - WTErr retVal = eNoErr; - - sampleRates.clear(); - const PaDeviceInfo *pPaDeviceInfo = Pa_GetDeviceInfo(deviceId); - - //now find supported sample rates - //following parameters are needed for sample rates validation - PaStreamParameters inputParameters, outputParameters; - PaStreamParameters *pInS = NULL, *pOutS = NULL; - - inputParameters.device = deviceId; - inputParameters.channelCount = std::min<int>(2, pPaDeviceInfo->maxInputChannels); - inputParameters.sampleFormat = paFloat32 | paNonInterleaved; - inputParameters.suggestedLatency = 0; /* ignored by Pa_IsFormatSupported() */ - inputParameters.hostApiSpecificStreamInfo = 0; - - if (inputParameters.channelCount) - pInS = &inputParameters; - - outputParameters.device = deviceId; - outputParameters.channelCount = std::min<int>(2, pPaDeviceInfo->maxOutputChannels); - outputParameters.sampleFormat = paFloat32; - outputParameters.suggestedLatency = 0; /* ignored by Pa_IsFormatSupported() */ - outputParameters.hostApiSpecificStreamInfo = 0; - - if (outputParameters.channelCount) - pOutS = &outputParameters; - - for(int sr=0; gAllSampleRates[sr] > 0; sr++) - { - if( paFormatIsSupported == Pa_IsFormatSupported(pInS, pOutS, gAllSampleRates[sr]) ) - { - sampleRates.push_back ((int)gAllSampleRates[sr]); - } - } - - return retVal; -} - - -WTErr WCMRPortAudioDeviceManager::getDeviceAvailableBufferSizes(DeviceID deviceId, std::vector<int>& buffers) -{ - WTErr retVal = eNoErr; - - buffers.clear(); - - //make PA request to get actual device buffer sizes - long minSize, maxSize, preferredSize, granularity; - - PaError paErr = PaAsio_GetAvailableBufferSizes(deviceId, &minSize, &maxSize, &preferredSize, &granularity); - - //for Windows ASIO devices we always use prefferes buffer size ONLY - if (paNoError == paErr ) - { - buffers.push_back(preferredSize); - } - else - { - retVal = eAsioFailed; - std::cout << "API::PortAudioDeviceManager::GetBufferSizes: error: " << Pa_GetErrorText (paErr) << " getting buffer sizes for device: "<< deviceId << std::endl; - } - - return retVal; -} - - -WTErr WCMRPortAudioDeviceManager::generateDeviceListImpl() -{ - std::cout << "API::PortAudioDeviceManager::Generating device list" << std::endl; - - WTErr retVal = eNoErr; - - //Initialize PortAudio and ASIO first - PaError paErr = Pa_Initialize(); - - if (paErr != paNoError) - { - //ToDo: throw an exception here! - retVal = eSomeThingNotInitailzed; - return retVal; - } - - // lock DeviceInfoVec firts - wvNS::wvThread::ThreadMutex::lock theLock(m_AudioDeviceInfoVecMutex); - - if (m_NoneDevice) - { - DeviceInfo *pDevInfo = new DeviceInfo(NONE_DEVICE_ID, m_NoneDevice->DeviceName() ); - pDevInfo->m_AvailableSampleRates = m_NoneDevice->SamplingRates(); - m_DeviceInfoVec.push_back(pDevInfo); - } - - //Get device count... - int numDevices = Pa_GetDeviceCount(); - - //for each device, - for (int thisDeviceID = 0; thisDeviceID < numDevices; thisDeviceID++) - { - //if it's of the required type... - const PaDeviceInfo *pPaDeviceInfo = Pa_GetDeviceInfo(thisDeviceID); - - if (Pa_GetHostApiInfo(pPaDeviceInfo->hostApi)->type == paASIO) - { - //build a device object... - try - { - std::cout << "API::PortAudioDeviceManager::DeviceID: " << thisDeviceID << ", Device Name: " << pPaDeviceInfo->name << std::endl; - TRACE_MSG ("PA DeviceID: " << thisDeviceID << ", Device Name: " << pPaDeviceInfo->name); - - DeviceInfo *pDevInfo = new DeviceInfo(thisDeviceID, pPaDeviceInfo->name); - if (pDevInfo) - { - //Get available sample rates - std::vector<int> availableSampleRates; - WTErr wErr = WCMRPortAudioDeviceManager::getDeviceAvailableSampleRates(thisDeviceID, availableSampleRates); - - if (wErr != eNoErr) - { - DEBUG_MSG ("Failed to get device available sample rates. Device ID: " << m_DeviceID); - delete pDevInfo; - continue; //proceed to the next device - } - - pDevInfo->m_AvailableSampleRates = availableSampleRates; - pDevInfo->m_MaxInputChannels = pPaDeviceInfo->maxInputChannels; - pDevInfo->m_MaxOutputChannels = pPaDeviceInfo->maxOutputChannels; - - //Get available buffer sizes - std::vector<int> availableBuffers; - wErr = getDeviceAvailableBufferSizes(thisDeviceID, availableBuffers); - - if (wErr != eNoErr) - { - DEBUG_MSG ("Failed to get device available buffer sizes. Device ID: " << m_DeviceID); - delete pDevInfo; - continue; //proceed to the next device - } - - pDevInfo->m_AvailableBufferSizes = availableBuffers; - - //Now check if this device is acceptable according to current input/output settings - bool bRejectDevice = false; - switch(m_eAudioDeviceFilter) - { - case eInputOnlyDevices: - if (pDevInfo->m_MaxInputChannels != 0) - { - m_DeviceInfoVec.push_back(pDevInfo); - } - else - { - // Delete unnecesarry device - bRejectDevice = true; - } - break; - case eOutputOnlyDevices: - if (pDevInfo->m_MaxOutputChannels != 0) - { - m_DeviceInfoVec.push_back(pDevInfo); - } - else - { - // Delete unnecesarry device - bRejectDevice = true; - } - break; - case eFullDuplexDevices: - if (pDevInfo->m_MaxInputChannels != 0 && pDevInfo->m_MaxOutputChannels != 0) - { - m_DeviceInfoVec.push_back(pDevInfo); - } - else - { - // Delete unnecesarry device - bRejectDevice = true; - } - break; - case eAllDevices: - default: - m_DeviceInfoVec.push_back(pDevInfo); - break; - } - - if(bRejectDevice) - { - TRACE_MSG ("API::PortAudioDeviceManager::Device " << pDevInfo->m_DeviceName << "Rejected. \ - In Channels = " << pDevInfo->m_MaxInputChannels << "Out Channels = " <<pDevInfo->m_MaxOutputChannels ); - delete pDevInfo; - } - } - } - catch (...) - { - std::cout << "API::PortAudioDeviceManager::Unabled to create PA Device: " << std::endl; - DEBUG_MSG ("Unabled to create PA Device: " << thisDeviceID); - } - } - } - - //If no devices were found, that's not a good thing! - if (m_DeviceInfoVec.empty() ) - { - std::cout << "API::PortAudioDeviceManager::No matching PortAudio devices were found, total PA devices = " << numDevices << std::endl; - DEBUG_MSG ("No matching PortAudio devices were found, total PA devices = " << numDevices); - } - - //we don't need PA initialized right now - Pa_Terminate(); - - return retVal; -} - - -WTErr WCMRPortAudioDeviceManager::getDeviceSampleRatesImpl(const std::string & deviceName, std::vector<int>& sampleRates) const -{ - sampleRates.clear (); - - WTErr retVal = eNoErr; - - if (m_CurrentDevice && deviceName == m_CurrentDevice->DeviceName() ) - { - sampleRates=m_CurrentDevice->SamplingRates(); - return retVal; - } - - DeviceInfo devInfo; - retVal = GetDeviceInfoByName(deviceName, devInfo); - - if (eNoErr == retVal) - { - sampleRates=devInfo.m_AvailableSampleRates; - } - else - { - std::cout << "API::PortAudioDeviceManager::GetSampleRates: Device not found: "<< deviceName << std::endl; - } - - return retVal; -} - - -WTErr WCMRPortAudioDeviceManager::getDeviceBufferSizesImpl(const std::string & deviceName, std::vector<int>& buffers) const -{ - WTErr retVal = eNoErr; - - buffers.clear(); - - //first check if the request has been made for None device - if (deviceName == m_NoneDevice->DeviceName() ) - { - buffers=m_NoneDevice->BufferSizes(); - return retVal; - } - - if (m_CurrentDevice && deviceName == m_CurrentDevice->DeviceName() ) - { - buffers=m_CurrentDevice->BufferSizes(); - return retVal; - } - - DeviceInfo devInfo; - retVal = GetDeviceInfoByName(deviceName, devInfo); - - if (eNoErr == retVal) - { - std::cout << "API::PortAudioDeviceManager::GetBufferSizes: got buffer :"<< devInfo.m_AvailableBufferSizes.front() << std::endl; - buffers = devInfo.m_AvailableBufferSizes; - } - else - { - std::cout << "API::PortAudioDeviceManager::GetBufferSizes: Device not found: "<< deviceName << std::endl; - } - - return retVal; -} diff --git a/libs/backends/wavesaudio/wavesapi/devicemanager/WCMRPortAudioDeviceManager.h b/libs/backends/wavesaudio/wavesapi/devicemanager/WCMRPortAudioDeviceManager.h deleted file mode 100644 index c028d09511..0000000000 --- a/libs/backends/wavesaudio/wavesapi/devicemanager/WCMRPortAudioDeviceManager.h +++ /dev/null @@ -1,180 +0,0 @@ -/* - Copyright (C) 2014 Waves Audio Ltd. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. - -*/ - -//---------------------------------------------------------------------------------- -// -// -//! \file WCMRPortAudioDeviceManager.h -//! -//! WCMRPortAudioDeviceManager and related class declarations -//! -//---------------------------------------------------------------------------------*/ -#ifndef __WCMRPortAudioDeviceManager_h_ - #define __WCMRPortAudioDeviceManager_h_ - -#include "WCMRAudioDeviceManager.h" -#include "WCMRNativeAudio.h" -#include "portaudio.h" - -//forward decl. -class WCMRPortAudioDeviceManager; - -//! Manages a port audio device, providing information -//! about the device, and managing audio callbacks. -class WCMRPortAudioDevice : public WCMRNativeAudioDevice -{ -public: - - WCMRPortAudioDevice (WCMRPortAudioDeviceManager *pManager, unsigned int deviceID, bool useMultiThreading = true, bool bNoCopy = false);///<Constructor - virtual ~WCMRPortAudioDevice ();///<Destructor - - virtual int CurrentSamplingRate(); ///<Current Sampling rate.? - virtual WTErr SetCurrentSamplingRate(int newRate);///<Change Current Sampling Rate : This is a requset, might not be successful at run time! - - virtual int CurrentBufferSize();///<Current Buffer Size.? - note that this may change with change in sampling rate. - virtual WTErr SetCurrentBufferSize (int newSize);///<Change Current Buffer Size : This is a requset, might not be successful at run time! - - virtual ConnectionStates ConnectionStatus();///< Connection Status - device available, gone, disconnected - - virtual WTErr SetActive (bool newState);///<Prepare/Activate device. - - virtual WTErr SetStreaming (bool newState);///<Start/Stop Streaming - should reconnect connections when streaming starts! - - virtual WTErr SetMonitorChannels (int leftChannel, int rightChannel);///<Set monitor channels. - optional, will not be available with AG - virtual WTErr SetMonitorGain (float newGain);///<Set monitor gain. - optional, will not be available with AG - - virtual WTErr ShowConfigPanel (void *pParam);///< Show Control Panel - in case of ASIO this will work only with Active device! - - virtual int AudioCallback (const float *pInputBuffer, float *pOutputBuffer, unsigned long framesPerBuffe, bool dropsDetectedr); - - virtual WTErr UpdateDeviceInfo (); - - virtual WTErr ResetDevice(); - -#ifdef PLATFORM_WINDOWS - static long StaticASIOMessageHook (void *pRefCon, long selector, long value, void* message, double* opt); - long ASIOMessageHook (long selector, long value, void* message, double* opt); -#endif //PLATFORM_WINDOWS - -protected: - static DWORD WINAPI __DoIdle__(LPVOID lpThreadParameter); - - // Methods which are executed by device processing thread - WTErr DoIdle();///<Do Idle Processing - void initDevice(); - void terminateDevice(); - void updateDeviceInfo(bool callerIsWaiting = false); - void activateDevice(bool callerIsWaiting = false); - void deactivateDevice(bool callerIsWaiting = false); - void startStreaming(bool callerIsWaiting = false); - void stopStreaming(bool callerIsWaiting = false); - void resetDevice (bool callerIsWaiting = false);///<Reset device - close and reopen stream, update device information! - - PaError testStateValidness(int sampleRate, int bufferSize); - /////////////////////////////////////////////////////////// - - static int TheCallback (const void *pInputBuffer, void *pOutputBuffer, unsigned long framesPerBuffer, - const PaStreamCallbackTimeInfo* /*pTimeInfo*/, PaStreamCallbackFlags /*statusFlags*/, void *pUserData ); - - unsigned int m_DeviceID; ///< The PA device id - PaStream* m_PortAudioStream; ///< Port audio stream, when the device is active! - bool m_StopRequested; ///< should be set to true when want to stop, set to false otherwise. - const float *m_pInputData; ///< This is what came in with the most recent callback. - int64_t m_SampleCounter; ///< The current running sample counter, updated by the audio callback. - int64_t m_SampleCountAtLastIdle; - - int m_DropsDetected; ///< Number of times audio drops have been detected so far. - int m_DropsReported; ///< Number of times audio drops have been reported so far to the client. - bool m_IgnoreThisDrop; ///< Allows disregarding the first drop - - int m_BufferSizeChangeRequested; - int m_BufferSizeChangeReported; - int m_ResetRequested; - int m_ResetReported; - int m_ResyncRequested; - int m_ResyncReported; - - HANDLE m_hDeviceProcessingThread; - DWORD m_DeviceProcessingThreadID; - - ///< Backend request events - HANDLE m_hResetRequestedEvent; - HANDLE m_hResetDone; - - HANDLE m_hUpdateDeviceInfoRequestedEvent; - HANDLE m_hUpdateDeviceInfoDone; - - HANDLE m_hActivateRequestedEvent; - HANDLE m_hActivationDone; - - HANDLE m_hDeActivateRequestedEvent; - HANDLE m_hDeActivationDone; - - HANDLE m_hStartStreamingRequestedEvent; - HANDLE m_hStartStreamingDone; - - HANDLE m_hStopStreamingRequestedEvent; - HANDLE m_hStopStreamingDone; - ///////////////////////// - - ///< Device request events - HANDLE m_hResetFromDevRequestedEvent; - HANDLE m_hBufferSizeChangedEvent; - HANDLE m_hSampleRateChangedEvent; - ///////////////////////////// - - ///< Sync events - HANDLE m_hDeviceInitialized; - HANDLE m_hExitIdleThread; - - //Should be set if the device connection status is "DeviceErrors" - WTErr m_lastErr; -}; - -//! WCMRPortAudioDeviceManager -/*! The PortAudio Device Manager class */ -class WCMRPortAudioDeviceManager : public WCMRAudioDeviceManager -{ -public: - WCMRPortAudioDeviceManager(WCMRAudioDeviceManagerClient *pTheClient, eAudioDeviceFilter eCurAudioDeviceFilter, - bool useMultithreading = true, bool bNocopy = false); ///< constructor - - virtual ~WCMRPortAudioDeviceManager(void); ///< destructor - -protected: - - virtual WCMRAudioDevice* initNewCurrentDeviceImpl(const std::string & deviceName); - virtual void destroyCurrentDeviceImpl(); - virtual WTErr generateDeviceListImpl(); // use this in derived class to fill device list - virtual WTErr updateDeviceListImpl() {return eNoErr; } // not supported - virtual WTErr getDeviceBufferSizesImpl(const std::string & deviceName, std::vector<int>& buffers) const; - virtual WTErr getDeviceSampleRatesImpl(const std::string & deviceName, std::vector<int>& sampleRates) const; - - bool m_UseMultithreading; ///< Flag indicates whether to use multi-threading for audio processing. - bool m_bNoCopyAudioBuffer; - -private: - // helper functions for this class only - WTErr getDeviceAvailableSampleRates(DeviceID deviceId, std::vector<int>& sampleRates); - WTErr getDeviceAvailableBufferSizes(DeviceID deviceId, std::vector<int>& buffers); - - WCMRAudioDevice* m_NoneDevice; -}; - -#endif //#ifndef __WCMRPortAudioDeviceManager_h_ diff --git a/libs/backends/wavesaudio/wavesapi/refmanager/WCRefManager.cpp b/libs/backends/wavesaudio/wavesapi/refmanager/WCRefManager.cpp deleted file mode 100644 index 8353a758c8..0000000000 --- a/libs/backends/wavesaudio/wavesapi/refmanager/WCRefManager.cpp +++ /dev/null @@ -1,26 +0,0 @@ -#include "WCRefManager.h" - -/// Construcotr. -WCRefManager::WCRefManager() -{ - m_RefCount = 1; -} - -/// Destructor. -WCRefManager::~WCRefManager() -{ -} - -/// Adds a reference to class. -void WCRefManager::AddRef() -{ - m_RefCount++; -} - -/// Decrements reference count and deletes the object if reference count becomes zero. -void WCRefManager::Release() -{ - m_RefCount--; - if( m_RefCount <= 0 ) - delete this; -}
\ No newline at end of file diff --git a/libs/backends/wavesaudio/wavesapi/refmanager/WCRefManager.h b/libs/backends/wavesaudio/wavesapi/refmanager/WCRefManager.h deleted file mode 100644 index 2e56dcd99d..0000000000 --- a/libs/backends/wavesaudio/wavesapi/refmanager/WCRefManager.h +++ /dev/null @@ -1,81 +0,0 @@ -/* - Copyright (C) 2014 Waves Audio Ltd. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. - -*/ - -#ifndef WCREFMANAGER_H -#define WCREFMANAGER_H - - -#define SAFE_RELEASE(p) if (p) {p->Release(); p = NULL;} - - -//In order to use this interface, derive the Interface class -//from WCRefManager_Interface and derive the implementation class -//from WCRefManager_Impl. Further, in the implementation class -//declaration, place the macro WCREFMANAGER_IMPL. -class WCRefManager_Interface -{ -public: - /// Constructor. - WCRefManager_Interface() {}; - /// Destructor. - virtual ~WCRefManager_Interface() {}; - /// Adds a reference to class. - virtual void AddRef() = 0; - /// Decrements reference count and deletes the object if reference count becomes zero. - virtual void Release() = 0; -}; - -///! See details at WCRefManager_Interface for how to use this. -class WCRefManager_Impl -{ -public: - WCRefManager_Impl () : m_RefCount(1) {} - virtual ~WCRefManager_Impl() {} -protected: - /// Variable to store reference count. - unsigned int m_RefCount; - -/// Helper to put implementation in an interface derived class, don't forget to -/// derive the impl from WCRefManager_Impl -#define WCREFMAN_IMPL \ - public: \ - virtual void AddRef() {m_RefCount++;} \ - virtual void Release() {m_RefCount--; if (m_RefCount<=0) delete this;} - -}; - - -class WCRefManager -{ -public: - /// Construcotr. - WCRefManager(); - /// Destructor. - virtual ~WCRefManager(); - /// Adds a reference to class. - void AddRef(); - /// Decrements reference count and deletes the object if reference count becomes zero. - void Release(); - -private: - /// Variable to store reference count. - unsigned int m_RefCount; -}; - -#endif // WCREFMANAGER_H |