IOAudioEngine

Inherits from
IOService
Availability
Available in OS X v10.1 and later.
Declared in
IOAudioEngine.h

Overview

Abstract base class for a single audio audio / I/O engine.

An IOAudioEngine is defined by a single I/O engine to transfer data to or from one or more sample buffers. Each sample buffer is represented by a single IOAudioStream instance. A single IOAudioEngine must contain at least one IOAudioStream, but has no upper limit on the number of IOAudioStreams it may contain. An IOAudioEngine instance may contain both input and output IOAudioStreams.

An audio driver must subclass IOAudioEngine in order to provide certain services. An IOAudioEngine subclass must start and stop the I/O engine when requested. The I/O engine should be continuously running and loop around from end to beginning. While the audio engine is running, it must take a timestamp as the sample buffer(s) wrap around and start at the beginning. The CoreAudio.framework uses the timestamp to calculate the exact position of the audio engine. An IOAudioEngine subclass must implement getCurrentSampleFrame() to provide a sample position on demand. Finally, an IOAudioEngine subclass must provide clipping and format conversion routines to go to/from the CoreAudio.framework's native float format.

If multiple stream formats or sample rates are allowed, the IOAudioEngine subclass must provide support for changing the hardware when a format or sample rate is changed.

There are several attributes associated with a single IOAudioEngine:

The IOAudioEngine superclass provides a shared status buffer that contains all of the dynamic pieces of information about the audio engine (type IOAudioEngineStatus). It runs an erase process on all of the output streams. The erase head is used to zero out the mix and sample buffers after the samples have been played. Additionally, the IOAudioEngine superclass handles the communication with the CoreAudio.framework and makes the decision to start and stop the audio engine when it detects it is in use.

In order for an audio device to play back or record sound, an IOAudioEngine subclass must be created. The subclass must initialize all of the necessary hardware resources to prepare for starting the audio I/O engine. It typically will perform these tasks in the initHardware() method. A subclass may also implement a stop() method which is called as the driver is being torn down. This is typically called in preparation of removing the device from the system for removable devices.

In addition to initializing the necessary hardware, there are a number of other tasks an IOAudioEngine must do during initHardware(). It must create the necessary IOAudioStream objects to match the device capabilities. Each IOAudioStream must be added using addAudioStream(). It also should create the IOAudioControls needed to control the various attributes of the audio engine: output volume, mute, input gain, input selection, analog passthru. To do that, addDefaultAudioControl() should be called with each IOAudioControl to be attached to the IOAudioEngine. In order to provide for proper synchronization, the latency of the audio engine should be specified with setSampleLatency(). This value represents the latency between the timestamp taken at the beginning of the buffer and when the audio is actually played (or recorded) by the device. If a device is block based or if there is a need to keep the CoreAudio.framework a certain number of samples ahead of (or behind for input) the I/O head, that value should be specified using setSampleOffset(). If this is not specified the CoreAudio.framework may attempt to get as close to the I/O head as possible.

The following fields in the shared IOAudioEngineStatus struct must be maintained by the subclass implementation:

 
  <t>  fCurrentLoopCount - the number of times the sample buffer has wrapped around to the beginning
  <t>  fLastLoopTime - timestamp of the most recent time that the I/O engine looped back to the
  beginning of the sample buffer
 

It is critically important that the fLastLoopTime field be as accurate as possible. It is the basis for the entire timer and synchronization mechanism used by the audio system.

At init time, the IOAudioEngine subclass must call setNumSampleFramesPerBuffer() to indicate how large each of the sample buffers are (measured in sample frames). Within a single IOAudioEngine, all sample buffers must be the same size and be running at the same sample rate. If different buffers/streams can be run at different rates, separate IOAudioEngines should be used. The IOAudioEngine subclass must also call setSampleRate() at init time to indicate the starting sample rate of the device.

Tasks

Miscellaneous

Instance Methods

addAudioStream

Adds an IOAudioStream to the audio engine.

virtual IOReturn addAudioStream( IOAudioStream *stream);
Parameters
stream

The IOAudioStream to be added.

Return Value

Returns kIOReturnSuccess if the stream was successfully added.

Discussion

This function is called by the driver to add an IOAudioStream to the audio engine. This must be called at least once to make sure the audio engine has at least one IOAudioStream.

addTimer

Enables the timer event for the audio engine.

virtual void addTimer();
Discussion

There is a timer event needed by the IOAudioEngine for processing the erase head and performing flushing operations. When the timer fires, the method timerFired() is ultimately called which in turn calls performErase() and performFlush(). This is called automatically to enable the timer event for this audio engine. It is called by setState() when the audio engine state is set to kIOAudioEngineRunning. When the timer is no longer needed, removeTimer() is called. There is no need to call this directly.

clearAllSampleBuffers

Zeros out all of the sample and mix buffers associated with the IOAudioEngine

virtual void clearAllSampleBuffers();
Discussion

This is called during resumeAudioEngine() since the audio engine gets started back at the beginning of the sample buffer.

clientClosed

Called automatically when a user client closes its connection to the audio engine.

virtual void clientClosed( IOAudioEngineUserClient *client);
Parameters
client

The user client that has disconnected.

Discussion

This method decrements the number of connections to the audio engine and if they reach zero, the audio engine is called with a call to stopAudioEngine(). This method should not be called directly.

convertInputSamplesVBR

Override this method if you want to return a different number of sample frames than was requested.

virtual IOReturn convertInputSamplesVBR( const void *sampleBuf, void *destBuf, UInt32 firstSampleFrame, UInt32 &numSampleFrames, const IOAudioStreamFormat *streamFormat, IOAudioStream *audioStream);

createDictionaryFromSampleRate

Generates a dictionary matching the given sample rate.

static OSDictionary *createDictionaryFromSampleRate( const IOAudioSampleRate *sampleRate, OSDictionary *rateDict = 0);
Return Value

Returns the newly create OSDictionary.

Discussion

This is an internal routine used to generate a dictionary matching the given sample rate. It is used to generate a sample rate dictionary for the I/O Registry - used by the CoreAudio.framework.

createSampleRateFromDictionary

Generates a sample rate from an OSDictionary.

static IOAudioSampleRate *createSampleRateFromDictionary( const OSDictionary *rateDict, IOAudioSampleRate *sampleRate = 0);
Return Value

Returns the sample rate.

Discussion

This is an internal routine used to generate a sample rate from an OSDictionary. It is used to generate a sample rate give a new OSDictionary from the IORegistry - coming from the CoreAudio.framework.

eraseOutputSamples

This function allows for the actual erasing of the mix and sample buffer to be overridden by a child class.

virtual IOReturn eraseOutputSamples( const void *mixBuf, void *sampleBuf, UInt32 firstSampleFrame, UInt32 numSampleFrames, const IOAudioStreamFormat *streamFormat, IOAudioStream *audioStream);
Parameters
mixBuf

Pointer to the IOAudioFamily allocated mix buffer.

sampleBuf

Pointer to the child class' sample buffer.

firstSampleFrame

Index to the first sample frame to erase.

numSampleFrames

Number of sample frames to erase.

streamFormat

Format of the data to be erased.

audioStream

Pointer to stream object that corresponds to the sample buffer being erased.

Return Value

Must return kIOReturnSuccess if the samples have been erased.

free

Frees all of the resources allocated by the IOAudioEngine.

virtual void free();
Discussion

Do not call this directly. This is called automatically by the system when the instance's refcount goes to 0. To decrement the refcount, call release() on the object.

getAttributeForConnection

Generic method to retrieve some attribute of the audio engine, specific to one connection.

virtual IOReturn getAttributeForConnection( SInt32 connectIndex, UInt32 attribute, uintptr_t *value );
Parameters
attribute

Defines the attribute to be returned. Some defined attributes are:

value

Returns the value for the attribute.

Return Value

an IOReturn code.

Discussion

IOAudioEngine subclasses may implement this method to allow arbitrary attribute/value pairs to be returned, specific to one connection.

getCommandGate

Returns the IOCommandGate for this IOAudioEngine.

virtual IOCommandGate *getCommandGate() const;

getCurrentSampleFrame

Gets the current sample frame from the IOAudioEngine subclass.

virtual UInt32 getCurrentSampleFrame() = 0;

getRunEraseHead

Returns true if the audio engine will run the erase head when the audio engine is running.

virtual bool getRunEraseHead();

getSampleRate

Returns the sample rate of the IOAudioEngine in samples per second.

virtual const IOAudioSampleRate *getSampleRate();

getState

Returns the current state of the IOAudioEngine.

virtual IOAudioEngineState getState();
Return Value

The current state of the IOAudioEngine: kIOAudioEngineRunning, kIOAudioEngineStopped.

Discussion

If this method is called in preparation for calling setState(), the stateLock must be acquired before the first call to getState() and held until after the last call to setState(). Be careful not to return from the code acquiring the lock while the lock is being held. That will cause a deadlock situation.

getStatus

Returns a pointer to the shared status buffer.

virtual const IOAudioEngineStatus *getStatus();

getTimerInterval

Gets the timer interval for use by the timer event.

virtual AbsoluteTime getTimerInterval();
Return Value

Returns the interval for the timer event.

Discussion

This method is called each time the timer event is enabled through addTimer(). The default implementation is set to return a value such that the timer event runs n times each cycle of the audio engine through the sample buffer. The value n is stored as the instance variable: numErasesPerBuffer. The default value of numErasesPerBuffer is set to IOAUDIOENGINE_DEFAULT_NUM_ERASES_PER_BUFFER which is 4. A subclass may change the value of numErasesPerBuffer or override getTimerInterval. If it is overridden, the subclass should call the superclass's implementation, compare its interval with the superclass's and return the smaller of the two.

getWorkLoop

Returns the IOWorkLoop for the driver.

virtual IOWorkLoop *getWorkLoop() const;

init

Performs initialization of a newly allocated IOAudioEngine.

virtual bool init( OSDictionary *properties);
Parameters
properties

The default properties for the IOAudioEngine.

Return Value

Returns true if initialization was successful.

Discussion

This function is responsible for initialization of all of the general attributes of a new IOAudioEngine. It initializes instance variables to their default values and allocates the shared status buffer. Subclasses will likely want to override this method and do all of their common initialization in their implementation. They do need to be sure to call IOAudioEngine's implementation of init and pay attention to the return value.

initHardware

This function is called by start() to provide a convenient place for the subclass to perform its hardware initialization.

virtual bool initHardware( IOService *provider);
Parameters
provider

The service provider numb for this audio engine - typically the IOAudioDevice.

Return Value

Returns true if the hardware was successfully initialized.

Discussion

Upon return from this function, all IOAudioStreams and IOAudioControls should be created and the audio engine should be ready to be started when a client requests that playback begin.

initKeys

Generates the OSSymbols with the keys.

static void initKeys();
Discussion

Do not call this directly. This is an internal initialization routine.

newUserClient

Requests a new user client object for this service.

virtual IOReturn newUserClient( task_t task, void *securityID, UInt32 type, IOUserClient **handler);
Parameters
task

The task requesting the new user client.

securityID

Optional security paramater passed in by the client - ignored.

type

Optional user client type passed in by the client - ignored.

handler

The new IOUserClient * must be stored in this param on a successful completion.

properties

A dictionary of additional properties for the connection.

Return Value

Returns kIOReturnSuccess on success. May also result kIOReturnError or kIOReturnNoMemory.

Discussion

This function is called automatically by I/O Kit when a user process attempts to connect to this service. It allocates a new IOAudioEngineUserClient object and increments the number of connections for this audio engine. If this is the first user client for this IOAudioEngine, it calls startAudioEngine(). There is no need to call this function directly. A derived class that requires overriding of newUserClient should override the version with the properties parameter for Intel targets, and without the properties parameter for PPC targets. The #if __i386__ directive can be used to select between the two behaviors.

performAudioEngineStart

Called to start the audio I/O engine

virtual IOReturn performAudioEngineStart();
Return Value

Must return kIOReturnSuccess on a successful start of the engine.

Discussion

This method is called by startAudioEngine(). This must be overridden by the subclass. No call to the superclass' implementation is necessary. The subclass' implementation must start up the audio I/O engine. This includes any audio engine that needs to be started as well as any interrupts that need to be enabled.

performAudioEngineStop

Called to stop the audio I/O engine

virtual IOReturn performAudioEngineStop();
Return Value

Must return kIOReturnSuccess on a successful stop of the engine.

Discussion

This method is called by stopAudioEngine() and pauseAudioEngine. This must be overridden by the subclass. No call to the superclass' implementation is necessary. The subclass' implementation must stop the audio I/O engine. This includes any audio engine that needs to be stopped as well as any interrupts that need to be disabled.

performErase

Performs erase head processing.

virtual void performErase();
Discussion

This method is called automatically each time the timer event fires and erases the sample buffer and mix buffer from the previous location up to the current location of the audio engine.

performFlush

Performs the flush operation.

virtual void performFlush();
Discussion

This method is called automatically each time the timer event fires. It stops the audio engine if there are no more clients and the audio engine is passed the latest flush ending position.

registerService

Called when this audio engine is ready to begin vending services.

virtual void registerService( IOOptionBits options = 0);
Parameters
options
Discussion

This function is called by IOAudioDevice::activateAudioEngine() once the audio engine has been fully initialized and is ready to begin audio playback.

removeTimer

Disables the timer event for the audio engine.

virtual void removeTimer();
Discussion

This method is called automatically to disable the timer event for this audio engine. There is need to call it directly. This method is called by setState() when the audio engine state is changed from kIOAudioEngineRunning to one of the stopped states.

resetStatusBuffer

Resets the status buffer to its default values.

virtual void resetStatusBuffer();
Discussion

This is called during startAudioEngine() and resumeAudioEngine() to clear out the status buffer in preparation of starting up the I/O engine. There is no need to call this directly.

setAttributeForConnection

Generic method to set some attribute of the audio engine, specific to one connection.

virtual IOReturn setAttributeForConnection( SInt32 connectIndex, UInt32 attribute, uintptr_t value );
Parameters
attribute

Defines the attribute to be set.

value

The new value for the attribute.

Return Value

an IOReturn code.

Discussion

IOAudioEngine subclasses may implement this method to allow arbitrary attribute/value pairs to be set, specific to one connection.

setClockDomain

Sets a property that CoreAudio uses to determine how devices are synchronized. If an audio device can tell that it is synchronized to another engine, it should set this value to that engine's clock domain. If an audio device can be a clock master, it may publish its own clock domain for other devices to use.

virtual void setClockDomain( UInt32 clockDomain = kIOAudioNewClockDomain);
Parameters
clockDomain

is the unique ID of another engine that this engine realizes it is synchronized to, use the default value kIOAudioNewClockDomain to have IOAudioEngine create a unique clock domain.

setClockIsStable

This function sets a flag that CoreAudio uses to select its sample rate tracking algorithm. Set this to TRUE unless that results in dropped audio. If the driver is experiencing unexplained dropouts setting this FALSE might help.

virtual void setClockIsStable( bool clockIsStable);
Parameters
clockIsStable

TRUE tells CoreAudio to use an agressive PLL to quickly lock to the engine's sample rate while FALSE tells CoreAudio to adjust more slowly to perceived sample rate changes that might just be the result of an unstable clock.

setInputSampleOffset

set the offset CoreAudio will read from off the current read pointer

virtual void setInputSampleOffset( UInt32 numSamples);
Parameters
numSamples

size of offset in sample

setMixClipOverhead

Used to tell IOAudioFamily when the watchdog timer must fire by.

virtual void setMixClipOverhead( UInt32 newMixClipOverhead);
Parameters
newMixClipOverhead

How much time per buffer should be made available for the mix and clip routines to run. Valid values are 1 through 99, inclusive.

Return Value

return no error

Discussion

setMixClipOverhead allows an audio engine to tell IOAudioFamily how much time an engine will take to mix and clip its samples, in percent. The default value is 10, meaning 10%. This will cause IOAudioFamily to make the watchdog timer fire when there is just over 10% of the time to complete a buffer set left (e.g. 51 samples when the HAL is using a buffer size of 512 samples).

setOutputSampleOffset

set the offset CoreAudio will write at off the current write pointer

virtual void setOutputSampleOffset( UInt32 numSamples);
Parameters
numSamples

size of offset in sample

setRunEraseHead

Tells the audio engine whether or not to run the erase head.

virtual void setRunEraseHead( bool runEraseHead);
Parameters
runEraseHead

The audio engine will run the erase head if this value is true.

Discussion

By default, output audio engines run the erase head and input audio engines do not. This method can be called after setDirection() is called in order to change the default behavior.

setSampleLatency

Sets the sample latency for the audio engine.

virtual void setSampleLatency( UInt32 numSamples);
Discussion

The sample latency represents the number of samples ahead of the playback head that it is safe to write into the sample buffer. The audio device API will never write closer to the playback head than the number of samples specified. For input audio engines the number of samples is behind the record head.

setSampleRate

Records the sample rate of the audio engine.

virtual void setSampleRate( const IOAudioSampleRate *newSampleRate);
Parameters
newSampleRate

The sample rate of the audio engine in samples per second.

Discussion

This method must be called during initialization of a new audio engine to record the audio engine's initial sample rate. It also is intended to be used to record changes to the sample rate during use. Currently changing sample rates after the audio engine has been started is not supported. It may require that the sample buffers be re-sized. This will be available in an upcoming release.

setState

Indicates that the audio engine is in the specified state.

virtual IOAudioEngineState setState( IOAudioEngineState newState);
Parameters
newState

The state the audio engine is in.

Return Value

Returns the old state.

Discussion

This method simply sets the internal state of the audio engine to the specified state. It does not affect a change to the state. It does however keep other internal state-related attributes consistent. For example, it enables or disables the timer as needed when the state changes to running or stopped.

start(IOService *)

A simple cover function for start(IOService *, IOAudioDevice *) that assumes the provider is the IOAudioDevice.

virtual bool start( IOService *provider);
Parameters
provider

The service provider for the IOAudioEngine (the IOAudioDevice in this case).

Return Value

Returns true if the IOAudioEngine was successfully started.

Discussion

Subclasses will want to override start(IOService *, IOAudioDevice *) rather than this one.

start(IOService *, IOAudioDevice *)

Standard IOKit start() routine called to start an IOService.

virtual bool start( IOService *provider, IOAudioDevice *device);
Parameters
provider

The service provider for the IOAudioEngine.

device

The IOAudioDevice to which this IOAudioEngine belongs.

Return Value

Returns true if the service was successfully started.

Discussion

This function is called in order to prepare the IOAudioEngine for use. It does NOT mean that the audio I/O engine itself should be started. This implementation gets the IOWorkLoop from the IOAudioDevice and allocates an IOCommandGate. Finally it calls initHardware() in which all of the subclass-specific device initialization should be done. Upon return from initHardware() all IOAudioStreams should be created and added to the audio engine. Also, all IOAudioControls for this IOAudioEngine should be created and attached.

startAudioEngine

Starts the audio I/O engine.

virtual IOReturn startAudioEngine();
Return Value

Must return kIOReturnSuccess on a successful start of the engine.

Discussion

This method is called automatically when the audio engine is placed into use the first time. This must be overridden by the subclass. No call to the superclass's implementation is necessary. The subclass's implementation must start up the audio I/O engine. This includes any audio engine that needs to be started as well as any interrupts that need to be enabled. Upon successfully starting the engine, the subclass's implementation must call setState(kIOAudioEngineRunning). If it has also checked the state using getState() earlier in the implementation, the stateLock must be acquired for the entire initialization process (using IORecursiveLockLock(stateLock) and IORecursiveLockUnlock(stateLock)) to ensure that the state remains consistent. See the general class comments for an example.

stop

Stops the service and prepares for the driver to be terminated.

virtual void stop( IOService *provider);
Parameters
provider

The service provider for the IOAudioEngine.

Discussion

This function is called before the driver is terminated and usually means that the device has been removed from the system.

stopAudioEngine

Stops the audio I/O engine.

virtual IOReturn stopAudioEngine();
Return Value

Must return kIOReturnSuccess on a successful stop of the engine.

Discussion

This method is called automatically when the last client disconnects from this audio engine. It must be overridden by the subclass. No call to the superclass's implementation is necessary. The subclass's implementation must stop the audio I/O engine. The audio engine (if it exists) should be stopped and any interrupts disabled. Upon successfully stopping the engine, the subclass must call setState(kAudioEngineStopped). If it has also checked the state using getState() earlier in the implementation, the stateLock must be acquired for the entire initialization process (using IORecursiveLockLock(stateLock) and IORecursiveLockUnlock(stateLock)) to ensure that the state remains consistent.

timerCallback

A static method used as a callback for the IOAudioDevice timer services.

static void timerCallback( OSObject *arg1, IOAudioDevice *device);
Parameters
arg1

The IOAudioEngine that is the target of the event.

device

The IOAudioDevice that sent the timer event.

Discussion

This method implements the IOAudioDevice::TimerEvent type.

timerFired

Indicates the timer has fired.

virtual void timerFired();
Discussion

This method is called by timerCallback to indicate the timer has fired. This method calls performErase() and performFlush() to do erase head processing and audio engine flushing each time the timer event fires.

Constants

gSampleRateWholeNumberKey
static const OSSymbol *gSampleRateWholeNumberKey;

Available in OS X v10.1 through OS X v10.5.

Declared in IOAudioEngine.h.

gSampleRateFractionKey
static const OSSymbol *gSampleRateFractionKey;

Available in OS X v10.1 through OS X v10.5.

Declared in IOAudioEngine.h.

Instance Variables

audioDevice

IOAudioDevice * audioDevice;

The IOAudioDevice instance to which the IOAudioEngine belongs.

audioEngineStopPosition

IOAudioEnginePosition audioEngineStopPosition;

When all clients have disconnected, this is set to one buffer length past the current audio engine position at the time. Then when the stop position is reached, the audio engine is stopped

commandGate

IOCommandGate *commandGate;

The IOCommandGate for this audio engine - attached to the driver's IOWorkLoop.

configurationChangeInProgress

bool configurationChangeInProgress;

Set to true after beginConfigurationChange() and false upon a subsequent call to completeConfigurationChange() or cancelConfigurationChange().

defaultAudioControls

OSSet *defaultAudioControls;

All of the IOAudioControls that affect this audio engine.

deviceStartedAudioEngine

bool deviceStartedAudioEngine;

Used by the IOAudioDevice to determine responsibility for shutting the audio engine down when it is no longer needed.

inputStreams

OSOrderedSet *inputStreams;

An OSSet of all of the input IOAudioStreams attached to this IOAudioEngine.

isRegistered

bool isRegistered;

Internal state variable to keep track or whether registerService() has been called.

numActiveUserClients

UInt32 numActiveUserClients;

A total of the active user clients - those that are currently playing or recording audio.

numErasesPerBuffer

UInt32 numErasesPerBuffer;

The number of times the erase head get scheduled to run for each cycle of the audio engine.

numSampleFramesPerBuffer

UInt32 numSampleFramesPerBuffer;

outputStreams

OSOrderedSet *outputStreams;

An OSSet of all of the output IOAudioStreams attached to this IOAudioEngine.

runEraseHead

bool runEraseHead;

Set to true if the erase head is to run when the audio engine is running. This is the case if there are any output streams.

sampleRate

IOAudioSampleRate sampleRate;

The current sample rate of the audio engine in samples per second.

state

IOAudioEngineState state;

The current state of the IOAudioEngine - running, stopped, paused.

status

IOAudioEngineStatus * status;

Status struct shared with the CoreAudio.framework.

userClients

OSSet *userClients;

An OSSet of all of the currently connected user clients.

workLoop

IOWorkLoop *workLoop;

The IOWorkLoop for the audio driver - shared with the IOAudioDevice.