📄 pa_mac_core.c
字号:
/* * $Id: pa_mac_core.c,v 1.2 2004/04/22 04:19:50 mbrubeck Exp $ * pa_mac_core.c * Implementation of PortAudio for Mac OS X Core Audio * * PortAudio Portable Real-Time Audio Library * Latest Version at: http://www.portaudio.com * * Authors: Ross Bencina and Phil Burk * Copyright (c) 1999-2000 Ross Bencina and Phil Burk * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files * (the "Software"), to deal in the Software without restriction, * including without limitation the rights to use, copy, modify, merge, * publish, distribute, sublicense, and/or sell copies of the Software, * and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * Any person wishing to distribute modifications to the Software is * requested to send the modifications to the original developer so that * they can be incorporated into the canonical version. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * * CHANGE HISTORY: 3.29.2001 - Phil Burk - First pass... converted from Window MME code with help from Darren. 3.30.2001 - Darren Gibbs - Added more support for dynamically querying device info. 12.7.2001 - Gord Peters - Tweaks to compile on PA V17 and OS X 10.1 2.7.2002 - Darren and Phil - fixed isInput so GetProperty works better, fixed device queries for numChannels and sampleRates, one CoreAudio device now maps to separate input and output PaDevices, audio input works if using same CoreAudio device (some HW devices make separate CoreAudio devices). 2.22.2002 - Stephane Letz - Explicit cast needed for compilation with Code Warrior 7 3.19.2002 - Phil Burk - Added paInt16, paInt8, format using new "pa_common/pa_convert.c" file. Return error if opened in mono mode cuz not supported. Add support for Pa_GetCPULoad(); Fixed timestamp in callback and Pa_StreamTime() (Thanks n++k for the advice!) Check for invalid sample rates and return an error. Check for getenv("PA_MIN_LATEWNCY_MSEC") to set latency externally. Better error checking for invalid channel counts and invalid devices. 3.29.2002 - Phil Burk - Fixed Pa_GetCPULoad() for small buffers. 3.31.2002 - Phil Burk - Use getrusage() instead of gettimeofday() for CPU Load calculation.TODO:O- how do mono output?O- FIFO between input and output callbacks if different devices, like in pa_mac.c*/#include <CoreServices/CoreServices.h>#include <CoreAudio/CoreAudio.h>#include <sys/time.h>#include <sys/resource.h>#include <unistd.h>#include "portaudio.h"#include "pa_host.h"#include "pa_trace.h"/************************************************* Constants ********//* To trace program, enable TRACE_REALTIME_EVENTS in pa_trace.h */#define PA_TRACE_RUN (0)#define PA_TRACE_START_STOP (1)#define PA_MIN_LATENCY_MSEC (8)#define MIN_TIMEOUT_MSEC (1000)#define PRINT(x) { printf x; fflush(stdout); }#define ERR_RPT(x) PRINT(x)#define DBUG(x) /* PRINT(x) /**/#define DBUGX(x) /* PRINT(x) /**/// define value of isInput passed to CoreAudio routines#define IS_INPUT (true)#define IS_OUTPUT (false)/************************************************************** * Structure for internal host specific stream data. * This is allocated on a per stream basis. */typedef struct PaHostSoundControl{ AudioDeviceID pahsc_AudioDeviceID; // Must be the same for input and output for now. /* Input -------------- */ int pahsc_BytesPerUserNativeInputBuffer; /* native buffer size in bytes per user chunk */ /* Output -------------- */ int pahsc_BytesPerUserNativeOutputBuffer; /* native buffer size in bytes per user chunk */ /* Init Time -------------- */ int pahsc_FramesPerHostBuffer; int pahsc_UserBuffersPerHostBuffer; /* For measuring CPU utilization. */ struct rusage pahsc_EntryRusage; double pahsc_InverseMicrosPerHostBuffer; /* 1/Microseconds of real-time audio per user buffer. */}PaHostSoundControl;/************************************************************** * Structure for internal extended device info. * There will be one or two PortAudio devices for each Core Audio device: * one input and or one output. */typedef struct PaHostDeviceInfo{ PaDeviceInfo paInfo; AudioDeviceID audioDeviceID;}PaHostDeviceInfo;/************************************************* Shared Data ********//* FIXME - put Mutex around this shared data. */static int sNumPaDevices = 0; /* Total number of PaDeviceInfos */static int sNumInputDevices = 0; /* Total number of input PaDeviceInfos */static int sNumOutputDevices = 0;static PaHostDeviceInfo *sDeviceInfos = NULL;static int sDefaultInputDeviceID = paNoDevice;static int sDefaultOutputDeviceID = paNoDevice;static int sPaHostError = 0;static int sNumCoreDevices = 0;static AudioDeviceID *sCoreDeviceIDs; // Array of Core AudioDeviceIDsstatic const char sMapperSuffixInput[] = " - Input";static const char sMapperSuffixOutput[] = " - Output";/* We index the input devices first, then the output devices. */#define LOWEST_INPUT_DEVID (0)#define HIGHEST_INPUT_DEVID (sNumInputDevices - 1)#define LOWEST_OUTPUT_DEVID (sNumInputDevices)#define HIGHEST_OUTPUT_DEVID (sNumPaDevices - 1)/************************************************* Macros ********//************************************************* Prototypes **********/static PaError Pa_QueryDevices( void );PaError PaHost_GetTotalBufferFrames( internalPortAudioStream *past );static int PaHost_ScanDevices( Boolean isInput );static int PaHost_QueryDeviceInfo( PaHostDeviceInfo *hostDeviceInfo, int coreDeviceIndex, Boolean isInput );static PaDeviceID Pa_QueryDefaultInputDevice( void );static PaDeviceID Pa_QueryDefaultOutputDevice( void );static void PaHost_CalcHostBufferSize( internalPortAudioStream *past );/********************************* BEGIN CPU UTILIZATION MEASUREMENT ****/static void Pa_StartUsageCalculation( internalPortAudioStream *past ){ PaHostSoundControl *pahsc = (PaHostSoundControl *) past->past_DeviceData; if( pahsc == NULL ) return; /* Query user CPU timer for usage analysis and to prevent overuse of CPU. */ getrusage( RUSAGE_SELF, &pahsc->pahsc_EntryRusage );}static long SubtractTime_AminusB( struct timeval *timeA, struct timeval *timeB ){ long secs = timeA->tv_sec - timeB->tv_sec; long usecs = secs * 1000000; usecs += (timeA->tv_usec - timeB->tv_usec); return usecs;}/******************************************************************************** Measure fractional CPU load based on real-time it took to calculate** buffers worth of output.*/static void Pa_EndUsageCalculation( internalPortAudioStream *past ){ struct rusage currentRusage; long usecsElapsed; double newUsage;#define LOWPASS_COEFFICIENT_0 (0.95)#define LOWPASS_COEFFICIENT_1 (0.99999 - LOWPASS_COEFFICIENT_0) PaHostSoundControl *pahsc = (PaHostSoundControl *) past->past_DeviceData; if( pahsc == NULL ) return; if( getrusage( RUSAGE_SELF, ¤tRusage ) == 0 ) { usecsElapsed = SubtractTime_AminusB( ¤tRusage.ru_utime, &pahsc->pahsc_EntryRusage.ru_utime ); /* Use inverse because it is faster than the divide. */ newUsage = usecsElapsed * pahsc->pahsc_InverseMicrosPerHostBuffer; past->past_Usage = (LOWPASS_COEFFICIENT_0 * past->past_Usage) + (LOWPASS_COEFFICIENT_1 * newUsage); }}/****************************************** END CPU UTILIZATION *******//************************************************************************/static PaDeviceID Pa_QueryDefaultInputDevice( void ){ OSStatus err = noErr; UInt32 count; int i; AudioDeviceID tempDeviceID = kAudioDeviceUnknown; PaDeviceID defaultDeviceID = paNoDevice; // get the default output device for the HAL // it is required to pass the size of the data to be returned count = sizeof(tempDeviceID); err = AudioHardwareGetProperty( kAudioHardwarePropertyDefaultInputDevice, &count, (void *) &tempDeviceID); if (err != noErr) goto Bail; // scan input devices to see which one matches this device defaultDeviceID = paNoDevice; for( i=LOWEST_INPUT_DEVID; i<=HIGHEST_INPUT_DEVID; i++ ) { DBUG(("Pa_QueryDefaultInputDevice: i = %d, aDevId = %d\n", i, sDeviceInfos[i].audioDeviceID )); if( sDeviceInfos[i].audioDeviceID == tempDeviceID ) { defaultDeviceID = i; break; } }Bail: return defaultDeviceID;}/************************************************************************/static PaDeviceID Pa_QueryDefaultOutputDevice( void ){ OSStatus err = noErr; UInt32 count; int i; AudioDeviceID tempDeviceID = kAudioDeviceUnknown; PaDeviceID defaultDeviceID = paNoDevice; // get the default output device for the HAL // it is required to pass the size of the data to be returned count = sizeof(tempDeviceID); err = AudioHardwareGetProperty( kAudioHardwarePropertyDefaultOutputDevice, &count, (void *) &tempDeviceID); if (err != noErr) goto Bail; // scan output devices to see which one matches this device defaultDeviceID = paNoDevice; for( i=LOWEST_OUTPUT_DEVID; i<=HIGHEST_OUTPUT_DEVID; i++ ) { DBUG(("Pa_QueryDefaultOutputDevice: i = %d, aDevId = %d\n", i, sDeviceInfos[i].audioDeviceID )); if( sDeviceInfos[i].audioDeviceID == tempDeviceID ) { defaultDeviceID = i; break; } }Bail: return defaultDeviceID;}/******************************************************************/static PaError Pa_QueryDevices( void ){ OSStatus err = noErr; UInt32 outSize; Boolean outWritable; int numBytes; // find out how many Core Audio devices there are, if any err = AudioHardwareGetPropertyInfo(kAudioHardwarePropertyDevices, &outSize, &outWritable); if (err != noErr) ERR_RPT(("Couldn't get info about list of audio devices\n")); // calculate the number of device available sNumCoreDevices = outSize / sizeof(AudioDeviceID); // Bail if there aren't any devices if (sNumCoreDevices < 1) ERR_RPT(("No Devices Available\n")); // make space for the devices we are about to get sCoreDeviceIDs = (AudioDeviceID *)malloc(outSize); // get an array of AudioDeviceIDs err = AudioHardwareGetProperty(kAudioHardwarePropertyDevices, &outSize, (void *)sCoreDeviceIDs); if (err != noErr) ERR_RPT(("Couldn't get list of audio device IDs\n")); // Allocate structures to hold device info pointers. // There will be a maximum of two Pa devices per Core Audio device, input and/or output. numBytes = sNumCoreDevices * 2 * sizeof(PaHostDeviceInfo); sDeviceInfos = (PaHostDeviceInfo *) PaHost_AllocateFastMemory( numBytes ); if( sDeviceInfos == NULL ) return paInsufficientMemory; // Scan all the Core Audio devices to see which support input and allocate a // PaHostDeviceInfo structure for each one. PaHost_ScanDevices( IS_INPUT ); sNumInputDevices = sNumPaDevices; // Now scan all the output devices. PaHost_ScanDevices( IS_OUTPUT ); sNumOutputDevices = sNumPaDevices - sNumInputDevices; // Figure out which of the devices that we scanned is the default device. sDefaultInputDeviceID = Pa_QueryDefaultInputDevice(); sDefaultOutputDeviceID = Pa_QueryDefaultOutputDevice(); return paNoError;}/************************************************************************************/long Pa_GetHostError(){ return sPaHostError;}/*************************************************************************/int Pa_CountDevices(){ if( sNumPaDevices <= 0 ) Pa_Initialize(); return sNumPaDevices;}/*************************************************************************//* Allocate a string containing the device name. */static char *PaHost_DeviceNameFromID(AudioDeviceID deviceID, Boolean isInput ){ OSStatus err = noErr; UInt32 outSize; Boolean outWritable; char *deviceName = nil; // query size of name err = AudioDeviceGetPropertyInfo(deviceID, 0, isInput, kAudioDevicePropertyDeviceName, &outSize, &outWritable); if (err == noErr) { deviceName = (char*)malloc( outSize + 1); if( deviceName ) { err = AudioDeviceGetProperty(deviceID, 0, isInput, kAudioDevicePropertyDeviceName, &outSize, deviceName); if (err != noErr) ERR_RPT(("Couldn't get audio device name.\n")); } } return deviceName;}/*************************************************************************/// An AudioStreamBasicDescription is passed in to query whether or not// the format is supported. A kAudioDeviceUnsupportedFormatError will// be returned if the format is not supported and kAudioHardwareNoError// will be returned if it is supported. AudioStreamBasicDescription// fields set to 0 will be ignored in the query, but otherwise values// must match exactly.Boolean deviceDoesSupportFormat(AudioDeviceID deviceID, AudioStreamBasicDescription *desc, Boolean isInput ){ OSStatus err = noErr; UInt32 outSize; outSize = sizeof(*desc); err = AudioDeviceGetProperty(deviceID, 0, isInput, kAudioDevicePropertyStreamFormatSupported, &outSize, desc); if (err == kAudioHardwareNoError) return true; else return false;}/*************************************************************************/// return an error stringchar* coreAudioErrorString (int errCode ){ char *str; switch (errCode) { case kAudioHardwareUnspecifiedError: str = "kAudioHardwareUnspecifiedError"; break; case kAudioHardwareNotRunningError: str = "kAudioHardwareNotRunningError"; break; case kAudioHardwareUnknownPropertyError: str = "kAudioHardwareUnknownPropertyError"; break; case kAudioDeviceUnsupportedFormatError: str = "kAudioDeviceUnsupportedFormatError"; break; case kAudioHardwareBadPropertySizeError: str = "kAudioHardwareBadPropertySizeError"; break; case kAudioHardwareIllegalOperationError: str = "kAudioHardwareIllegalOperationError"; break; default: str = "Unknown CoreAudio Error!"; break; } return str;}/*************************************************************************** PaDeviceInfo structures have already been created** so just return the pointer.***/const PaDeviceInfo* Pa_GetDeviceInfo( PaDeviceID id ){ if( id < 0 || id >= sNumPaDevices ) return NULL; return &sDeviceInfos[id].paInfo;}/*************************************************************************** Scan all of the Core Audio devices to see which support input or output.** Changes sNumDevices, and fills in sDeviceInfos.*/
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -