chore(macos): vendor system-sdk dependency

This commit is contained in:
2024-09-09 03:44:35 -05:00
parent 7f8d05101e
commit a50d52bae5
2634 changed files with 871615 additions and 1 deletions

View File

@@ -0,0 +1,465 @@
#if (defined(__USE_PUBLIC_HEADERS__) && __USE_PUBLIC_HEADERS__) || (defined(USE_AUDIOTOOLBOX_PUBLIC_HEADERS) && USE_AUDIOTOOLBOX_PUBLIC_HEADERS) || !__has_include(<AudioToolboxCore/AUAudioUnitImplementation.h>)
/*!
@file AUAudioUnitImplementation.h
@framework AudioToolbox.framework
@copyright (c) 2015 Apple, Inc. All rights reserved.
@brief Additional AUAudioUnit interfaces specific to subclass implementations.
*/
/*!
@page AUExtensionPackaging Audio Unit Extension Packaging
@discussion
Audio Unit app extensions are available beginning with macOS 10.11 and iOS 9.0.
For background on app extensions, see "App Extension Programming Guide."
There are two types of audio unit extensions: UI, and non-UI. The principal class of an
extension with UI must be a subclass of AUViewController. This class is declared
in CoreAudioKit/AUViewController.h. The principal class of a non-UI extension can derive from
NSObject.
The principal class of both UI and non-UI extensions must conform to the AUAudioUnitFactory
protocol.
The Info.plist of the .appex bundle describes the type of extension and the principal class.
It also contains an AudioComponents array (see AudioComponent.h), and an optional
AudioComponentBundle entry, for example:
```
<key>NSExtension</key>
<dict>
<key>NSExtensionAttributes</key>
<dict>
<key>NSExtensionActivationRule</key>
<string>TRUEPREDICATE</string>
<key>NSExtensionServiceRoleType</key>
<string>NSExtensionServiceRoleTypeEditor</string>
<key>AudioComponents</key>
<array>
<dict>
<key>factoryFunction</key>
<string>____</string>
<key>manufacturer</key>
<string>____</string>
<key>name</key>
<string>____</string>
<key>sandboxSafe</key>
<true/>
<key>subtype</key>
<string>____</string>
<key>tags</key>
<array>
<string>____</string>
</array>
<key>type</key>
<string>____</string>
<key>version</key>
<integer>____</integer>
</dict>
</array>
<key>AudioComponentBundle</key>
<string>____</string>
</dict>
<key>NSExtensionPointIdentifier</key>
<string>____</string>
<key>NSExtensionPrincipalClass</key>
<string>____</string>
</dict>
```
NSExtensionPointIdentifier
: `com.apple.AudioUnit` or `com.apple.AudioUnit-UI`.
NSExtensionPrincipalClass
: The name of the principal class.
AudioComponentBundle
: Optional. A version 3 audio unit can be loaded into a separate extension process and
this is the default behavior. To be able to load in-process on macOS (see
kAudioComponentInstantiation_LoadInProcess) the audio unit has to be packaged
separately. The AudioComponentBundle entry supports loading in-process by designating
the identifier of a bundle in the .appex or its enclosing app container in which the
factory function and/or principal class are implemented.
AudioComponents
: Registration info for each audio component type/subtype/manufacturer
implemented in the extension. factoryFunction is only necessary
if the AU is implemented using AUAudioUnitV2Bridge.
See AudioComponent.h.
Note that as of macOS version 10.12, the system has special support for installing both version 2
(bundle-based) and version 3 (extension) implementations of the same audio unit. When two components
are registered with the same type/subtype/manufacturer and version, normally the first one found
is used. But if one is an audio unit extension and the other is not, then the audio unit extension's
registration "wins", though if an app attempts to open it synchronously, with
AudioComponentInstanceNew, then the system will fall back to the version 2 implementation.
*/
#ifndef AudioToolbox_AUAudioUnitImplementation_h
#define AudioToolbox_AUAudioUnitImplementation_h
#ifdef __OBJC2__
#import <AudioToolbox/AUAudioUnit.h>
NS_ASSUME_NONNULL_BEGIN
// forward declaration
union AURenderEvent;
// =================================================================================================
// Realtime events - parameters and MIDI
/// Describes the type of a render event.
typedef NS_ENUM(uint8_t, AURenderEventType) {
AURenderEventParameter = 1,
AURenderEventParameterRamp = 2,
AURenderEventMIDI = 8,
AURenderEventMIDISysEx = 9,
AURenderEventMIDIEventList = 10
};
#pragma pack(4)
/// Common header for an AURenderEvent.
typedef struct AURenderEventHeader {
union AURenderEvent *__nullable next; //!< The next event in a linked list of events.
AUEventSampleTime eventSampleTime; //!< The sample time at which the event is scheduled to occur.
AURenderEventType eventType; //!< The type of the event.
uint8_t reserved; //!< Must be 0.
} AURenderEventHeader;
/// Describes a scheduled parameter change.
typedef struct AUParameterEvent {
union AURenderEvent *__nullable next; //!< The next event in a linked list of events.
AUEventSampleTime eventSampleTime; //!< The sample time at which the event is scheduled to occur.
AURenderEventType eventType; //!< AURenderEventParameter or AURenderEventParameterRamp.
uint8_t reserved[3]; //!< Must be 0.
AUAudioFrameCount rampDurationSampleFrames;
//!< If greater than 0, the event is a parameter ramp;
/// should be 0 for a non-ramped event.
AUParameterAddress parameterAddress; //!< The parameter to change.
AUValue value; //!< If ramped, the parameter value at the
/// end of the ramp; for a non-ramped event,
/// the new value.
} AUParameterEvent;
/// Describes a single scheduled MIDI event.
typedef struct AUMIDIEvent {
union AURenderEvent *__nullable next; //!< The next event in a linked list of events.
AUEventSampleTime eventSampleTime; //!< The sample time at which the event is scheduled to occur.
AURenderEventType eventType; //!< AURenderEventMIDI or AURenderEventMIDISysEx.
uint8_t reserved; //!< Must be 0.
uint16_t length; //!< The number of valid MIDI bytes in the data field.
/// 1, 2 or 3 for most MIDI events, but can be longer
/// for system-exclusive (sys-ex) events.
uint8_t cable; //!< The virtual cable number.
uint8_t data[3]; //!< The bytes of the MIDI event. Running status will not be used.
} AUMIDIEvent;
/// Describes a single scheduled MIDIEventList.
typedef struct AUMIDIEventList {
union AURenderEvent *__nullable next; //!< The next event in a linked list of events.
AUEventSampleTime eventSampleTime; //!< The sample time at which the event is scheduled to occur.
AURenderEventType eventType; //!< AURenderEventMIDI or AURenderEventMIDISysEx.
uint8_t reserved; //!< Must be 0.
uint8_t cable; //!< The virtual cable number.
MIDIEventList eventList; //!< A structure containing UMP packets.
} AUMIDIEventList;
/*! @brief A union of the various specific render event types.
@discussion
Determine which variant to use via head.eventType. AURenderEventParameter and
AURenderEventParameterRamp use the parameter variant. AURenderEventMIDI and
AURenderEventMIDISysEx use the MIDI variant.
*/
typedef union AURenderEvent {
AURenderEventHeader head;
AUParameterEvent parameter;
AUMIDIEvent MIDI;
AUMIDIEventList MIDIEventsList;
} AURenderEvent;
#pragma pack()
/*! @brief Block to render the audio unit.
@discussion
Implemented in subclasses; should not be used by clients.
The other parameters are identical to those of AURenderBlock.
@param realtimeEventListHead
A time-ordered linked list of the AURenderEvents to be rendered during this render cycle.
Note that a ramp event will only appear in the render cycle during which it starts; the
audio unit is responsible for maintaining continued ramping state for any further render
cycles.
*/
typedef AUAudioUnitStatus (^AUInternalRenderBlock)(
AudioUnitRenderActionFlags * actionFlags,
const AudioTimeStamp * timestamp,
AUAudioFrameCount frameCount,
NSInteger outputBusNumber,
AudioBufferList * outputData,
const AURenderEvent *__nullable realtimeEventListHead,
AURenderPullInputBlock __nullable __unsafe_unretained pullInputBlock);
// =================================================================================================
/// Aspects of AUAudioUnit of interest only to subclassers.
@interface AUAudioUnit (AUAudioUnitImplementation)
/*! @brief Register an audio unit component implemented as an AUAudioUnit subclass.
@discussion
This method dynamically registers the supplied AUAudioUnit subclass with the Audio Component
system, in the context of the current process (only). After registering the subclass, it can
be instantiated via AudioComponentInstanceNew,
-[AUAudioUnit initWithComponentDescription:options:error:], and via any other API's which
instantiate audio units via their component descriptions (e.g. <AudioToolbox/AUGraph.h>, or
<AVFoundation/AVAudioUnitEffect.h>).
*/
+ (void)registerSubclass:(Class)cls asComponentDescription:(AudioComponentDescription)componentDescription name:(NSString *)name version:(UInt32)version;
/// Block which subclassers must provide (via a getter) to implement rendering.
@property (nonatomic, readonly) AUInternalRenderBlock internalRenderBlock;
/*! @property renderContextObserver
@brief Block called by the OS when the rendering context changes.
Audio Units which create auxiliary realtime rendering threads should implement this property to
return a block which will be called by the OS when the render context changes. Audio Unit hosts
must not attempt to interact with the AudioUnit through this block; it is for the exclusive use
of the OS. See <AudioToolbox/AudioWorkInterval.h> for more information.
*/
@property (nonatomic, readonly) AURenderContextObserver renderContextObserver
API_AVAILABLE(macos(11.0), ios(14.0), watchos(7.0), tvos(14.0))
__SWIFT_UNAVAILABLE_MSG("Swift is not supported for use with audio realtime threads");
/*! @property MIDIOutputBufferSizeHint
@brief Hint to control the size of the allocated buffer for outgoing MIDI events.
@discussion
This property allows the plug-in to provide a hint to the framework regarding the size of
its outgoing MIDI data buffer.
If the plug-in produces more MIDI output data than the default size of the allocated buffer,
then the plug-in can provide this property to increase the size of this buffer.
The value represents the number of 3-byte Legacy MIDI messages that fit into the buffer or
a single MIDIEventList containing 1 MIDIEventPacket of 2 words when using MIDI 2.0 (MIDIEventList based API's).
This property is set to the default value by the framework.
In case of kAudioUnitErr_MIDIOutputBufferFull errors caused by producing too much MIDI
output in one render call, set this property to increase the buffer.
This only provides a recommendation to the framework.
*/
@property (NS_NONATOMIC_IOSONLY) NSInteger MIDIOutputBufferSizeHint API_AVAILABLE(macos(10.13), ios(11.0), watchos(4.0), tvos(11.0));
/*! @method shouldChangeToFormat:forBus:
@param format
An AVAudioFormat which is proposed as the new format.
@param bus
The AUAudioUnitBus on which the format will be changed.
@discussion
This is called when setting the format on an AUAudioUnitBus.
The bus has already checked that the format meets the channel constraints of the bus.
The AU can override this method to check before allowing a new format to be set on the bus.
If this method returns NO, then the new format will not be set on the bus.
The default implementation returns NO if the unit has renderResourcesAllocated, otherwise it results YES.
*/
- (BOOL)shouldChangeToFormat:(AVAudioFormat *)format forBus:(AUAudioUnitBus *)bus;
/*! @method setRenderResourcesAllocated:
@param flag
In the base class implementation of allocateRenderResourcesAndReturnError:, the property renderResourcesAllocated is set to YES.
If allocateRenderResourcesAndReturnError: should fail in a subclass, subclassers must use this method to set renderResourcesAllocated to NO.
*/
- (void)setRenderResourcesAllocated:(BOOL)flag;
@end
// =================================================================================================
/// Aspects of AUAudioUnitBus of interest only to the implementation of v3 AUs.
@interface AUAudioUnitBus (AUAudioUnitImplementation)
/*! @method initWithFormat:error:
@brief initialize with a default format.
@param format The initial format for the bus.
@param outError An error if the format is unsupported for the bus.
*/
- (nullable instancetype)initWithFormat:(AVAudioFormat *)format error:(NSError **)outError;
/*! @property supportedChannelCounts
@brief An array of numbers giving the supported numbers of channels for this bus.
@discussion
If supportedChannelCounts is nil, then any number less than or equal to maximumChannelCount
is supported. If setting supportedChannelCounts makes the current format unsupported, then
format will be set to nil. The default value is nil.
*/
@property (nonatomic, retain, nullable) NSArray<NSNumber *> *supportedChannelCounts;
/*! @property maximumChannelCount
@brief The maximum numbers of channels supported for this bus.
@discussion
If supportedChannelCounts is set, then this value is derived from supportedChannelCounts. If
setting maximumChannelCount makes the current format unsupported, then format will be set to
nil. The default value is UINT_MAX.
*/
@property (nonatomic) AUAudioChannelCount maximumChannelCount;
@end
// =================================================================================================
/// Aspects of AUAudioUnitBusArray of interest only to subclassers.
@interface AUAudioUnitBusArray (AUAudioUnitBusImplementation)
/// Sets the bus array to be a copy of the supplied array. The base class issues KVO notifications.
- (void)replaceBusses:(NSArray <AUAudioUnitBus *> *)busArray;
@end
// =================================================================================================
/*! Factory methods for building parameters, parameter groups, and parameter trees.
@note In non-ARC code, "create" methods return unretained objects (unlike "create"
C functions); the caller should generally retain them.
*/
@interface AUParameterTree (Factory)
/// Create an AUParameter.
/// See AUParameter's properties for descriptions of the arguments.
+ (AUParameter *)createParameterWithIdentifier:(NSString *)identifier name:(NSString *)name address:(AUParameterAddress)address min:(AUValue)min max:(AUValue)max unit:(AudioUnitParameterUnit)unit unitName:(NSString * __nullable)unitName flags:(AudioUnitParameterOptions)flags valueStrings:(NSArray<NSString *> *__nullable)valueStrings dependentParameters:(NSArray<NSNumber *> *__nullable)dependentParameters;
/*! @brief Create an AUParameterGroup.
@param identifier An identifier for the group (non-localized, persistent).
@param name The group's human-readable name (localized).
@param children The group's child nodes.
*/
+ (AUParameterGroup *)createGroupWithIdentifier:(NSString *)identifier name:(NSString *)name children:(NSArray<AUParameterNode *> *)children;
/*! @brief Create a template group which may be used as a prototype for further group instances.
@discussion
Template groups provide a way to construct multiple instances of identical parameter
groups, sharing certain immutable state between the instances.
Template groups may not appear in trees except at the root.
*/
+ (AUParameterGroup *)createGroupTemplate:(NSArray<AUParameterNode *> *)children;
/*! @brief Initialize a group as a copied instance of a template group.
@param templateGroup A group to be used as a template and largely copied.
@param identifier An identifier for the new group (non-localized, persistent).
@param name The new group's human-readable name (localized).
@param addressOffset The new group's parameters' addresses will be offset from those in
the template by this value.
*/
+ (AUParameterGroup *)createGroupFromTemplate:(AUParameterGroup *)templateGroup identifier:(NSString *)identifier name:(NSString *)name addressOffset:(AUParameterAddress)addressOffset;
/*! @brief Create an AUParameterTree.
@param children The tree's top-level child nodes.
*/
+ (AUParameterTree *)createTreeWithChildren:(NSArray<AUParameterNode *> *)children;
@end
// =================================================================================================
/// A block called to notify the AUAudioUnit implementation of changes to AUParameter values.
typedef void (^AUImplementorValueObserver)(AUParameter *param, AUValue value);
/// A block called to fetch an AUParameter's current value from the AUAudioUnit implementation.
typedef AUValue (^AUImplementorValueProvider)(AUParameter *param);
/// A block called to convert an AUParameter's value to a string.
typedef NSString *__nonnull (^AUImplementorStringFromValueCallback)(AUParameter *param, const AUValue *__nullable value);
/// A block called to convert a string to an AUParameter's value.
typedef AUValue (^AUImplementorValueFromStringCallback)(AUParameter *param, NSString *string);
/// A block called to return a group or parameter's localized display name, abbreviated to the requested length.
typedef NSString *__nonnull (^AUImplementorDisplayNameWithLengthCallback)(AUParameterNode *node, NSInteger desiredLength);
/// Aspects of AUParameterNode of interest only to AUAudioUnit subclassers.
@interface AUParameterNode (AUParameterNodeImplementation)
/*! @brief Called when a parameter changes value.
@discussion
This block, used only in an audio unit implementation, receives all externally-generated
changes to parameter values. It should store the new value in its audio signal processing
state (assuming that that state is separate from the AUParameter object).
*/
@property (NS_NONATOMIC_IOSONLY, copy) AUImplementorValueObserver implementorValueObserver;
/*! @brief Called when a value of a parameter in the tree is known to have a stale value
needing to be refreshed.
@discussion
The audio unit should return the current value for this parameter; the AUParameterNode will
store the value.
*/
@property (NS_NONATOMIC_IOSONLY, copy) AUImplementorValueProvider implementorValueProvider;
/// Called to provide string representations of parameter values.
/// If value is nil, the callback uses the current value of the parameter.
@property (NS_NONATOMIC_IOSONLY, copy) AUImplementorStringFromValueCallback implementorStringFromValueCallback;
/// Called to convert string to numeric representations of parameter values.
@property (NS_NONATOMIC_IOSONLY, copy) AUImplementorValueFromStringCallback implementorValueFromStringCallback;
/// Called to obtain an abbreviated version of a parameter or group name.
@property (NS_NONATOMIC_IOSONLY, copy) AUImplementorDisplayNameWithLengthCallback implementorDisplayNameWithLengthCallback;
@end
// =================================================================================================
/*! @brief Wraps a v2 audio unit in an AUAudioUnit subclass.
@discussion
Implementors of version 3 audio units may derive their implementations from
AUAudioUnitV2Bridge. It expects the component description with which it is initialized to
refer to a registered component with a v2 implementation using an
AudioComponentFactoryFunction. The bridge will instantiate the v2 audio unit via the factory
function and communicate it with it using the v2 AudioUnit API's (AudioUnitSetProperty,
etc.)
Hosts should not access this class; it will be instantiated when needed when creating an
AUAudioUnit.
*/
API_AVAILABLE(macos(10.11), ios(9.0), watchos(2.0), tvos(9.0))
@interface AUAudioUnitV2Bridge : AUAudioUnit
@end
// =================================================================================================
/*! @brief Protocol to which principal classes of v3 audio units (extensions) must conform.
@discussion
The principal class of a non-UI v3 audio unit extension will generally derive from NSObject
and implement this protocol.
The principal class of a UI v3 audio unit extension must derive from AUViewController and
implement this protocol.
*/
@protocol AUAudioUnitFactory <NSExtensionRequestHandling>
/*! @brief Create an instance of an extension's AUAudioUnit.
@discussion
This method should create and return an instance of its audio unit.
This method will be called only once per instance of the factory.
Note that in non-ARC code, "create" methods return unretained objects (unlike "create"
C functions); the implementor should return an object with reference count 1 but
autoreleased.
*/
- (nullable AUAudioUnit *)createAudioUnitWithComponentDescription:(AudioComponentDescription)desc error:(NSError **)error;
@end
NS_ASSUME_NONNULL_END
#endif // __OBJC2__
#endif // AudioToolbox_AUAudioUnitImplementation_h
#else
#include <AudioToolboxCore/AUAudioUnitImplementation.h>
#endif

View File

@@ -0,0 +1,66 @@
#if (defined(__USE_PUBLIC_HEADERS__) && __USE_PUBLIC_HEADERS__) || (defined(USE_AUDIOTOOLBOX_PUBLIC_HEADERS) && USE_AUDIOTOOLBOX_PUBLIC_HEADERS) || !__has_include(<AudioToolboxCore/AUCocoaUIView.h>)
/*!
@file AUCocoaUIView.h
@framework AudioToolbox.framework
@copyright (c) 2003-2015 Apple, Inc. All rights reserved.
@abstract Protocol for Cocoa-based audio unit views.
@discussion
Audio unit hosts can call these methods to retrieve views for audio units.
*/
#ifndef AudioToolbox_AUCocoaUIView_h
#define AudioToolbox_AUCocoaUIView_h
#include <TargetConditionals.h>
#if defined(__OBJC__) && TARGET_OS_OSX
#import <Foundation/Foundation.h>
#import <AudioToolbox/AUComponent.h>
NS_ASSUME_NONNULL_BEGIN
@class NSView;
@protocol AUCocoaUIBase
/*!
@method interfaceVersion
@abstract Return the version of the interface you are implementing.
@result An unsigned value.
@discussion For MacOS X 10.3 or later, you should return the current version which is 0.
NOTE: Developers are strongly encouraged to override -(NSString *)description to return the name
of the cocoa view. This name is displayed by host applications and should be returned as a copy
instead of a static string.
For example, you could define the description method like this:
- (NSString *) description {
return [NSString withString: @"Filter View"];
}
*/
- (unsigned)interfaceVersion;
/*!
@method uiViewForAudioUnit:withSize:
@abstract Return the NSView responsible for displaying the interface for the provided AudioUnit.
@param inAudioUnit
The Audio Unit the view is associated with.
@param inPreferredSize
The preferred size of the view to be returned.
@result An NSView.
@discussion
This method is a factory function: each call to it must return a unique view.
Each view must be returned with a retain count of 1 and autoreleased.
It is the client's responsibility to retain the returned view and to release the view when it's no longer needed.
*/
- (NSView * __nullable)uiViewForAudioUnit:(AudioUnit)inAudioUnit withSize:(NSSize)inPreferredSize;
@end
NS_ASSUME_NONNULL_END
#endif // defined(__OBJC__) && TARGET_OS_OSX
#endif // AudioToolbox_AUCocoaUIView_h
#else
#include <AudioToolboxCore/AUCocoaUIView.h>
#endif

View File

@@ -0,0 +1,726 @@
/*!
@file AUGraph.h
@framework AudioToolbox.framework
@copyright (c) 2000-2015 by Apple, Inc., all rights reserved.
@abstract API's to manage graphs of AudioUnits.
An AUGraph is a complete description of an audio signal processing network. The AUGraph
API's maintain a set of AudioUnits, audio connections between their inputs and outputs, and
any callbacks used to provide inputs. It also allows the embedding of sub-graphs within
parent graphs to allow for a logical organization of parts of an overall signal chain. The
graph's AudioUnits do the actual audio processing.
The AUGraph may be introspected, in order to get complete information about all of the
AudioUnits in the graph. The various nodes (AUNode) in the AUGraph representing AudioUnits
or sub graphs may be added or removed, and the interactions between them modified.
An AUGraph's state can be manipulated in both the rendering thread and in other threads.
Consequently, any activities that affect the state of the graph are guarded with locks and a
messaging model between any calling thread and the thread upon which the AUGraph's output
unit is called (the render thread).
An AUGraph will have a single head node - what is referred to below as its output unit. The
output unit is used to both start and stop the rendering operations of a graph, and as the
dispatch point for the safe manipulation of the state of the graph while it is running.
*/
#ifndef AudioToolbox_AUGraph_h
#define AudioToolbox_AUGraph_h
#include <AudioToolbox/AudioUnit.h>
CF_ASSUME_NONNULL_BEGIN
#if defined(__cplusplus)
extern "C"
{
#endif
#define AUGRAPH_DEPRECATED(macos_intro) API_DEPRECATED("AUGraph is deprecated in favor of AVAudioEngine", macos(macos_intro, API_TO_BE_DEPRECATED), ios(2.0, API_TO_BE_DEPRECATED), watchos(2.0, API_TO_BE_DEPRECATED), tvos(9.0, API_TO_BE_DEPRECATED))
/*!
@typedef AUGraph
@abstract A reference to an AUGraph object.
*/
typedef struct OpaqueAUGraph *AUGraph;
/*!
@typedef AUNode
@abstract Used to represent a member of an AUGraph
*/
typedef SInt32 AUNode;
/*!
@enum AUGraph error codes
@abstract These are the error codes returned from the AUGraph API.
@constant kAUGraphErr_NodeNotFound
The specified node cannot be found
@constant kAUGraphErr_InvalidConnection
The attempted connection between two nodes cannot be made
@constant kAUGraphErr_OutputNodeErr
AUGraphs can only contain one OutputUnit.
this error is returned if trying to add a second output unit
or the graph's output unit is removed while the graph is running
@constant kAUGraphErr_CannotDoInCurrentContext
To avoid spinning or waiting in the render thread (a bad idea!), many of the
calls to AUGraph can return: kAUGraphErr_CannotDoInCurrentContext. This
result is only generated when you call an AUGraph API from its render
callback. It means that the lock that it required was held at that time, by
another thread. If you see this result code, you can generally attempt the
action again - typically the NEXT render cycle (so in the mean time the lock
can be cleared), or you can delegate that call to another thread in your
app. You should not spin or put-to-sleep the render thread.
@constant kAUGraphErr_InvalidAudioUnit
*/
CF_ENUM(OSStatus)
{
kAUGraphErr_NodeNotFound = -10860,
kAUGraphErr_InvalidConnection = -10861,
kAUGraphErr_OutputNodeErr = -10862,
kAUGraphErr_CannotDoInCurrentContext = -10863,
kAUGraphErr_InvalidAudioUnit = -10864
};
#pragma mark -
/*!
@function NewAUGraph
@abstract Create a new AUGraph
@param outGraph the new AUGraph object
*/
extern OSStatus
NewAUGraph( AUGraph __nullable * __nonnull outGraph) AUGRAPH_DEPRECATED(10.0);
/*!
@function DisposeAUGraph
@abstract Dispose an AUGraph
Deallocates the AUGraph along with its nodes and their resources.
@param inGraph the AUGraph object to be disposed
*/
extern OSStatus
DisposeAUGraph( AUGraph inGraph) AUGRAPH_DEPRECATED(10.0);
#pragma mark -
#pragma mark Node State
/// @name AU Node management
/// @{
/*!
@function AUGraphAddNode
@abstract Add a node to an AUGraph
Creates a node in the graph that is an AudioUnit, using the supplied
AudioComponentDescription to find and open that unit.
@param inGraph the AUGraph object
@param inDescription the AudioComponentDescription used to find and open the AudioUnit
@param outNode the newly added node
*/
extern OSStatus
AUGraphAddNode( AUGraph inGraph,
const AudioComponentDescription * inDescription,
AUNode * outNode) AUGRAPH_DEPRECATED(10.5);
/*!
@function AUGraphRemoveNode
@abstract Remove a node from an AUGraph
Nodes can be removed from any thread context. The output node of
the AUGraph cannot be removed while the graph is running.
@param inGraph the AUGraph object
@param inNode the node to be removed
*/
extern OSStatus
AUGraphRemoveNode( AUGraph inGraph,
AUNode inNode) AUGRAPH_DEPRECATED(10.0);
/*!
@function AUGraphGetNodeCount
@abstract The number of nodes in an AUGraph
@param inGraph the AUGraph object
@param outNumberOfNodes the number of nodes
*/
extern OSStatus
AUGraphGetNodeCount(AUGraph inGraph,
UInt32 *outNumberOfNodes) AUGRAPH_DEPRECATED(10.0);
/*!
@function AUGraphGetIndNode
@abstract Returns the node at a given index
By using AUGraphGetNodeCount in conjunction with this call, you can
iterate through the nodes of an AUGraph.
@param inGraph the AUGraph object
@param inIndex the index of the node to retrieve
@param outNode the node at that index
*/
extern OSStatus
AUGraphGetIndNode( AUGraph inGraph,
UInt32 inIndex,
AUNode *outNode) AUGRAPH_DEPRECATED(10.0);
/*!
@function AUGraphNodeInfo
@abstract Returns information about a particular AUNode
You can pass in NULL for any of the out parameters if you're not interested
in that value.
@param inGraph the AUGraph object
@param inNode the node to query
@param outDescription the component description that would describe the AudioUnit of this node
@param outAudioUnit the AudioUnit of this node
*/
extern OSStatus
AUGraphNodeInfo( AUGraph inGraph,
AUNode inNode,
AudioComponentDescription * __nullable outDescription,
AudioUnit __nullable * __nullable outAudioUnit) AUGRAPH_DEPRECATED(10.5);
/// @}
#if !TARGET_OS_IPHONE
#pragma mark -
#pragma mark Sub Graphs
/// @name Sub Graph Nodes
/// @{
/*!
@function AUGraphNewNodeSubGraph
@abstract Create a node that will represent a sub graph
This will create a node that represents a contained or member AUGraph.
The AUGraph can be retrieved through the GetNodeInfoSubGraph call.
The member AUGraph is owned by the parent graph and will be disposed when
either:
1. The parent graph is disposed
2. The node is removed from the parent AUGraph
@param inGraph the AUGraph object
@param outNode the node that is used to refer to the sub-graph
*/
extern OSStatus
AUGraphNewNodeSubGraph( AUGraph inGraph,
AUNode *outNode) API_DEPRECATED("no longer supported", macos(10.2, API_TO_BE_DEPRECATED)) API_UNAVAILABLE(ios, watchos, tvos);
/*!
@function AUGraphGetNodeInfoSubGraph
@abstract Return an AUGraph represented by this node
This will return the sub graph represented by this AUNode.
@param inGraph the AUGraph object
@param inNode the node to query
@param outSubGraph the sub-graph
*/
extern OSStatus
AUGraphGetNodeInfoSubGraph( const AUGraph inGraph,
AUNode inNode,
AUGraph __nullable * __nonnull outSubGraph) API_DEPRECATED("no longer supported", macos(10.2, API_TO_BE_DEPRECATED)) API_UNAVAILABLE(ios, watchos, tvos);
/*!
@function AUGraphIsNodeSubGraph
@abstract Determine whether the node represents a sub graph
This will return true if the specified node represents a subgraph, false if not.
@param inGraph the AUGraph object
@param inNode the node to query
@param outFlag true if the node is a subgraph, false if not
*/
extern OSStatus
AUGraphIsNodeSubGraph( const AUGraph inGraph,
AUNode inNode,
Boolean * outFlag) API_DEPRECATED("no longer supported", macos(10.2, API_TO_BE_DEPRECATED)) API_UNAVAILABLE(ios, watchos, tvos);
#endif // !TARGET_OS_IPHONE
/// @}
#pragma mark -
#pragma mark Node Interactions
/// @name Node Interactions
/// @{
/*!
@abstract The different types of node interactions
We use the term interaction as a general term to describe some interaction
of a node. Currently, the interactions of a node that the graph manages are
described below.
@constant kAUNodeInteraction_Connection
connections between 2 audio units,
@constant kAUNodeInteraction_InputCallback
input callbacks being registered to a single audio unit's input bus.
*/
CF_ENUM(UInt32) {
kAUNodeInteraction_Connection = 1,
kAUNodeInteraction_InputCallback = 2
};
/*!
@struct AudioUnitNodeConnection
@abstract A connection between two nodes
@var sourceNode
@var sourceOutputNumber
@var destNode
@var destInputNumber
*/
struct AudioUnitNodeConnection
{
AUNode sourceNode;
UInt32 sourceOutputNumber;
AUNode destNode;
UInt32 destInputNumber;
};
typedef struct AudioUnitNodeConnection AudioUnitNodeConnection;
typedef struct AudioUnitNodeConnection AUNodeConnection;
/*!
@struct AUNodeRenderCallback
@abstract A callback used to provide input to an audio unit
Used to contain information when a callback is used
to provide input to the specific node's specified input
@var destNode
@var destInputNumber
@var cback
*/
struct AUNodeRenderCallback
{
AUNode destNode;
AudioUnitElement destInputNumber;
AURenderCallbackStruct cback;
};
typedef struct AUNodeRenderCallback AUNodeRenderCallback;
/*!
@struct AUNodeInteraction
@abstract Used to describe the interaction between/with a node
This structure contains information about the interaction between
two nodes (in the case of a connection), or the input to a node
(in the case of a callback).
The type of the interaction is used to determine how to interpret the contents
of the following union.
There may be other nodal interactions in the future, so NO ASSUMPTIONS should be made
that these are the only 2 nodal interaction types; you must always check the
nodeInteractionType and only act on those types you understand
Arrays of these structs can be returned, the addition of new members to the
nodeInteraction union will NOT change the size of this structure
@var nodeInteractionType the interaction type
@var nodeInteraction a union providing information about the specified interaction
*/
struct AUNodeInteraction
{
UInt32 nodeInteractionType;
union
{
AUNodeConnection connection;
AUNodeRenderCallback inputCallback;
} nodeInteraction;
};
typedef struct AUNodeInteraction AUNodeInteraction;
/*!
@function AUGraphConnectNodeInput
@abstract connect a node's output to a node's input
*/
extern OSStatus
AUGraphConnectNodeInput( AUGraph inGraph,
AUNode inSourceNode,
UInt32 inSourceOutputNumber,
AUNode inDestNode,
UInt32 inDestInputNumber) AUGRAPH_DEPRECATED(10.0);
/*!
@function AUGraphSetNodeInputCallback
@abstract Set a callback for the specified node's specified input.
@param inInputCallback The callback that will provide input data to the node
*/
extern OSStatus
AUGraphSetNodeInputCallback (AUGraph inGraph,
AUNode inDestNode,
UInt32 inDestInputNumber,
const AURenderCallbackStruct * inInputCallback)
AUGRAPH_DEPRECATED(10.5);
/*!
@function AUGraphDisconnectNodeInput
@abstract disconnect a node's input
This can be used to disconnect either a connection or callback interaction
to the specified node input
*/
extern OSStatus
AUGraphDisconnectNodeInput( AUGraph inGraph,
AUNode inDestNode,
UInt32 inDestInputNumber) AUGRAPH_DEPRECATED(10.0);
/*!
@function AUGraphClearConnections
@abstract clear all of the interactions in a graph
This will clear all connections and callback interactions of the nodes of a graph
*/
extern OSStatus
AUGraphClearConnections( AUGraph inGraph) AUGRAPH_DEPRECATED(10.0);
/*!
@function AUGraphGetNumberOfInteractions
@abstract Retrieve the number of interactions of a graph
The number of node interactions currently being managed by the graph
*/
extern OSStatus
AUGraphGetNumberOfInteractions( AUGraph inGraph,
UInt32 * outNumInteractions) AUGRAPH_DEPRECATED(10.5);
/*!
@function AUGraphGetInteractionInfo
@abstract Retrieve information about a particular interaction in a graph
Returns information about a particular interaction.
inInteractionIndex is based on the outNumInteractions value and is only valid if no
edits to the graph's state have been made.
An app can iterate through the interactions (as with the nodes) of a graph by retrieving
the number of interactions, and then iterating an index from 0 < numInteractions
@param outInteraction the interaction information at the specified index
*/
extern OSStatus
AUGraphGetInteractionInfo( AUGraph inGraph,
UInt32 inInteractionIndex,
AUNodeInteraction * outInteraction) AUGRAPH_DEPRECATED(10.5);
/*!
@function AUGraphCountNodeInteractions
@abstract Retrieve the number of interactions of a graph's node
The number of node interactions currently being managed by the graph for the specified node.
*/
extern OSStatus
AUGraphCountNodeInteractions( AUGraph inGraph,
AUNode inNode,
UInt32 * outNumInteractions) AUGRAPH_DEPRECATED(10.5);
/*!
@function AUGraphGetNodeInteractions
@abstract Retrieve information about the interactions in a graph for a given node
@param ioNumInteractions
on input, specifies the number of interactions that can be returned
on output, specifies the number of interactions returned.
@param outInteractions the interactions the specified node is involved in
*/
extern OSStatus
AUGraphGetNodeInteractions( AUGraph inGraph,
AUNode inNode,
UInt32 * ioNumInteractions,
AUNodeInteraction * outInteractions) AUGRAPH_DEPRECATED(10.5);
/// @}
#pragma mark -
/// @name Updating an AUGraph
/// @{
/*!
@function AUGraphUpdate
@abstract Updates the state of a running AUGraph
Call this after performing a series of "edits" on the AUGraph with calls
such as AUGraphConnectNodeInput() to finalize those edits.
The call will be synchronous if outIsUpdated is NULL,
meaning it will block until the changes are incorporated
into the graph OR an error is returned from the update process
if outIsUpdated is non-NULL, then AUGraphUpdate() will return
immediately and outIsUpdated will equal "true" if the changes
were already made (no more changes to make) or "false" if changes are still
outstanding.
Calling from the AUGraphRenderNotification callback:
Connection and Disconnection events can be completely processed
in the render notification callback of the AUGraph
Nodes can also be removed (except for the output node or a sub-graph of the AUGraph)
as well.
Getting kAUGraphErr_CannotDoInCurrentContext as a result code:
If AUGraphUpdate returns this result, then it means it was
unable to process the update, due to an inability to safely
alter the state of the graph (because another thread was accessing
a call that relies on the graph's state having integrity).
This result code is only a transitory state, which will pass as soon
as your other thread's call to AUGraph (that has the lock) completes.
If an error is encountered in the process of an update (say an invalid connection
is attempted, a disconnection between nodes that are not connected, etc) on a running graph,
then the call will return that error code. It only process events whilst it receives
no error results. Thus, if an error is encountered, other events will not be
processed until AUGraphUpdate is called again. This is done, in cases where
the state of the graph could become inconsistent if further events were processed, so
this decision is left up to you. The same applies to the "cant do" error - you have
to explicitly call AUGraphUpdate again to have the processing of the events occur.
@param outIsUpdated if specified returns true if all of the edits were applied to the graph
*/
extern OSStatus
AUGraphUpdate( AUGraph inGraph,
Boolean * __nullable outIsUpdated) AUGRAPH_DEPRECATED(10.0);
/// @}
#pragma mark -
#pragma mark State Management
/// @name AUGraph state management
/// @{
/*!
@function AUGraphOpen
@abstract Open a graph
AudioUnits are open but not initialized (no resource allocation occurs here)
*/
extern OSStatus
AUGraphOpen( AUGraph inGraph) AUGRAPH_DEPRECATED(10.0);
/*!
@function AUGraphClose
@abstract Close a graph
All AudioUnits are closed - leaving only its nodal representation
*/
extern OSStatus
AUGraphClose( AUGraph inGraph) AUGRAPH_DEPRECATED(10.0);
/*!
@function AUGraphInitialize
@abstract Initialise a graph
AudioUnitInitialize() is called on each opened node/AudioUnit
(get ready to render) and SubGraph that are involved in a
interaction. If the node is not involved, it is initialised
after it becomes involved in an interaction.
A graph must be opened before it can be initialised.
*/
extern OSStatus
AUGraphInitialize( AUGraph inGraph) AUGRAPH_DEPRECATED(10.0);
/*!
@function AUGraphUninitialize
@abstract Uninitialise a graph
The member of the graph are uninitialised
*/
extern OSStatus
AUGraphUninitialize( AUGraph inGraph) AUGRAPH_DEPRECATED(10.0);
/*!
@function AUGraphStart
@abstract Start a graph
Start() is called on the "head" node(s) of the AUGraph (now rendering starts)
The graph must be initialised before it can be started.
*/
extern OSStatus
AUGraphStart( AUGraph inGraph) AUGRAPH_DEPRECATED(10.0);
/*!
@function AUGraphStop
@abstract Stop a graph
Stop() is called on the "head" node(s) of the AUGraph (rendering is stopped)
*/
extern OSStatus
AUGraphStop( AUGraph inGraph) AUGRAPH_DEPRECATED(10.0);
/*!
@function AUGraphIsOpen
@abstract Is the graph open
*/
extern OSStatus
AUGraphIsOpen( AUGraph inGraph,
Boolean *outIsOpen) AUGRAPH_DEPRECATED(10.0);
/*!
@function AUGraphIsInitialized
@abstract Is the graph initialised
*/
extern OSStatus
AUGraphIsInitialized( AUGraph inGraph,
Boolean *outIsInitialized) AUGRAPH_DEPRECATED(10.0);
/*!
@function AUGraphIsRunning
@abstract Is the graph running (has it been started)
*/
extern OSStatus
AUGraphIsRunning( AUGraph inGraph,
Boolean *outIsRunning) AUGRAPH_DEPRECATED(10.0);
/// @}
#pragma mark -
#pragma mark Utilities
/// @name AUGraph utilities
/// @{
/*!
@function AUGraphGetCPULoad
@abstract The CPU load of the graph
Returns a short-term running average of the current CPU load of the graph.
*/
extern OSStatus
AUGraphGetCPULoad( AUGraph inGraph,
Float32 *outAverageCPULoad) AUGRAPH_DEPRECATED(10.1);
/*!
@function AUGraphGetMaxCPULoad
@abstract The Maximum CPU load of the graph
Returns the max CPU load of the graph since this call was last made or the graph was last
started.
*/
extern OSStatus
AUGraphGetMaxCPULoad( AUGraph inGraph,
Float32 *outMaxLoad) AUGRAPH_DEPRECATED(10.3);
/*!
@function AUGraphAddRenderNotify
@abstract Add a notification callback
Add a callback that the graph will call every time the graph renders. The callback will be
called once before the graph's render operation, and once after the render operation is
complete.
*/
extern OSStatus
AUGraphAddRenderNotify( AUGraph inGraph,
AURenderCallback inCallback,
void * __nullable inRefCon) AUGRAPH_DEPRECATED(10.2);
/*!
@function AUGraphRemoveRenderNotify
@abstract Remove a notification callback
Remove a previously added callback. You must provide both the callback and the refCon that was
used previously to add the callback.
*/
extern OSStatus
AUGraphRemoveRenderNotify( AUGraph inGraph,
AURenderCallback inCallback,
void * __nullable inRefCon) AUGRAPH_DEPRECATED(10.2);
/// @}
#pragma mark -
#pragma mark Deprecated
#if !TARGET_OS_IPHONE
struct ComponentDescription;
/*!
@function AUGraphNewNode
ClassInfo data should not be used with new nodes
@param inClassData
must be null
@deprecated in 10.5, see AUGraphAddNode
*/
extern OSStatus
AUGraphNewNode( AUGraph inGraph,
const struct ComponentDescription *inDescription,
UInt32 inClassDataSize,
const void *inClassData,
AUNode *outNode) API_DEPRECATED("no longer supported", macos(10.0, 10.5)) API_UNAVAILABLE(ios, watchos, tvos);
/*!
@function AUGraphGetNodeInfo
ClassInfo data should not be used with new nodes
@deprecated in 10.5, see AUGraphNodeInfo
*/
extern OSStatus
AUGraphGetNodeInfo( AUGraph inGraph,
AUNode inNode,
struct ComponentDescription *outDescription,
UInt32 *outClassDataSize,
void * __nullable * __nullable outClassData,
AudioUnit __nullable * __nullable outAudioUnit) API_DEPRECATED("no longer supported", macos(10.0, 10.5)) API_UNAVAILABLE(ios, watchos, tvos);
/*!
@function AUGraphGetNumberOfConnections
@deprecated in 10.5, see AUGraphGetNumberOfInteractions
*/
extern OSStatus
AUGraphGetNumberOfConnections( AUGraph inGraph,
UInt32 *outNumConnections) API_DEPRECATED("no longer supported", macos(10.1, 10.5)) API_UNAVAILABLE(ios, watchos, tvos);
/*!
@function AUGraphGetConnectionInfo
@deprecated in 10.5, see AUGraphGetInteractionInfo
*/
extern OSStatus
AUGraphGetConnectionInfo( AUGraph inGraph,
UInt32 inConnectionIndex,
AUNode *outSourceNode,
UInt32 *outSourceOutputNumber,
AUNode *outDestNode,
UInt32 *outDestInputNumber) API_DEPRECATED("no longer supported", macos(10.1, 10.5)) API_UNAVAILABLE(ios, watchos, tvos);
/*!
@function AUGraphCountNodeConnections
@deprecated in 10.5, see AUGraphCountNodeInteractions
*/
extern OSStatus
AUGraphCountNodeConnections( AUGraph inGraph,
AUNode inNode,
UInt32 *outNumConnections) API_DEPRECATED("no longer supported", macos(10.3, 10.5)) API_UNAVAILABLE(ios, watchos, tvos);
/*!
@function AUGraphGetNodeConnections
@deprecated in 10.5, see AUGraphGetNodeInteractions
*/
extern OSStatus
AUGraphGetNodeConnections( AUGraph inGraph,
AUNode inNode,
AudioUnitNodeConnection *outConnections,
UInt32 *ioNumConnections)
API_DEPRECATED("no longer supported", macos(10.3, 10.5)) API_UNAVAILABLE(ios, watchos, tvos);
#endif //!TARGET_OS_IPHONE
#if defined(__cplusplus)
}
#endif
CF_ASSUME_NONNULL_END
#endif // AudioToolbox_AUGraph_h

View File

@@ -0,0 +1,108 @@
/*!
@file AUMIDIController.h
@framework AudioToolbox.framework
@copyright (c) 2002-2015 by Apple, Inc., all rights reserved.
@abstract Deprecated.
*/
#ifndef AudioToolbox_AUMIDIController_h
#define AudioToolbox_AUMIDIController_h
#include <TargetConditionals.h>
#if !TARGET_RT_64_BIT
// This API set is not available for 64-bit
#include <AudioToolbox/AudioUnit.h>
#include <CoreMIDI/CoreMIDI.h>
#include <AudioToolbox/AudioUnitUtilities.h>
typedef struct OpaqueAUMIDIController *AUMIDIControllerRef;
#ifdef __cplusplus
extern "C" {
#endif
/*
inVirtualDestinationName is null to create no virtual destination
*/
extern OSStatus
AUMIDIControllerCreate( CFStringRef inVirtualDestinationName,
AUMIDIControllerRef * outController)
API_DEPRECATED("no longer supported", macos(10.2, 10.5)) API_UNAVAILABLE(ios, watchos, tvos);
extern OSStatus
AUMIDIControllerDispose( AUMIDIControllerRef inController)
API_DEPRECATED("no longer supported", macos(10.2, 10.5)) API_UNAVAILABLE(ios, watchos, tvos);
extern OSStatus
AUMIDIControllerMapChannelToAU( AUMIDIControllerRef inController,
SInt32 inSourceMIDIChannel,
AudioUnit inAudioUnit,
SInt32 inDestMIDIChannel,
Boolean inCreateDefaultControlMappings)
API_DEPRECATED("no longer supported", macos(10.2, 10.5)) API_UNAVAILABLE(ios, watchos, tvos);
extern OSStatus
AUMIDIControllerMapEventToParameter( AUMIDIControllerRef inController,
UInt8 inMIDIStatusByte,
UInt16 inMIDIControl,
const AudioUnitParameter *inParameter)
API_DEPRECATED("no longer supported", macos(10.2, 10.5)) API_UNAVAILABLE(ios, watchos, tvos);
// this will remove any mapping held by this controller
// to the specified audio unit - whether those are:
// (1) default mappings (AUMIDIControllerMapChannelToAU)
// (2) custom mappings (AUMIDIControllerMapEventToParameter)
// Typically, this is done when (and should be done) when an AU no longer
// should receive MIDI events for its parameters (or the AU is being disposed)
extern OSStatus
AUMIDIControllerUnmapAudioUnit( AUMIDIControllerRef inController,
AudioUnit inAudioUnit)
API_DEPRECATED("no longer supported", macos(10.2, 10.5)) API_UNAVAILABLE(ios, watchos, tvos);
/*
$$$ need description of timestamps in the packets (if any) are treated -- needs
to factor in the AU's latency $$$
*/
extern OSStatus
AUMIDIControllerHandleMIDI( AUMIDIControllerRef inController,
const MIDIPacketList * inMIDIPacketList)
API_DEPRECATED("no longer supported", macos(10.2, 10.5)) API_UNAVAILABLE(ios, watchos, tvos);
extern OSStatus
AUMIDIControllerConnectSource( AUMIDIControllerRef inController,
MIDIEndpointRef inSource)
API_DEPRECATED("no longer supported", macos(10.2, 10.5)) API_UNAVAILABLE(ios, watchos, tvos);
extern OSStatus
AUMIDIControllerDisconnectSource( AUMIDIControllerRef inController,
MIDIEndpointRef inSource)
API_DEPRECATED("no longer supported", macos(10.2, 10.5)) API_UNAVAILABLE(ios, watchos, tvos);
/*
Tells an AUMIDIController to generate an XML description of the control/NRPN
mapping. Returns a (local file) URL to the file written. $$$ If the AUMIDIController
has a virtual destination associated with it, the AUMIDIController will
call MIDIObjectSetNameConfiguration to publish those names as the current
ones for that destination.
*/
extern OSStatus
AUMIDIControllerExportXMLNames( AUMIDIControllerRef inController,
CFURLRef * outXMLFileURL)
API_DEPRECATED("no longer supported", macos(10.2, 10.5)) API_UNAVAILABLE(ios, watchos, tvos);
#ifdef __cplusplus
}
#endif
#endif // !TARGET_RT_64_BIT
#endif // AudioToolbox_AUMIDIController_h

View File

@@ -0,0 +1,386 @@
#if (defined(__USE_PUBLIC_HEADERS__) && __USE_PUBLIC_HEADERS__) || (defined(USE_AUDIOTOOLBOX_PUBLIC_HEADERS) && USE_AUDIOTOOLBOX_PUBLIC_HEADERS) || !__has_include(<AudioToolboxCore/AUParameters.h>)
/*!
@file AUParameters.h
@framework AudioToolbox.framework
@copyright (c) 2015 Apple, Inc. All rights reserved.
@brief Objects representing an AUAudioUnit's tree of parameters.
*/
#ifndef AudioToolbox_AUParameters_h
#define AudioToolbox_AUParameters_h
#ifdef __OBJC2__
#import <AudioToolbox/AudioUnitProperties.h>
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@class AUParameter;
// =================================================================================================
// typedefs
/*! @typedef AUValue
@brief A value of an audio unit parameter.
*/
typedef float AUValue;
/*! @typedef AUParameterAddress
@brief Numeric identifier for audio unit parameter.
@discussion
Note that parameter addresses are not necessarily persistent, unless the individual audio
unit documents a promise to maintain its addressing scheme. Hosts should bind to parameters'
key paths.
*/
typedef uint64_t AUParameterAddress;
/*! @enum AUParameterAutomationEventType
@brief Identifies the different types of parameter automation events.
@discussion
Audio Units may generate parameter changes from their user interfaces. Hosts may attach
significance to the beginning and end of a UI gesture (typically touching and releasing
a fader). These gestures are conveyed through these types of automation events.
@constant AUParameterAutomationEventTypeValue
The event contains an updated value for the parameter.
@constant AUParameterAutomationEventTypeTouch
The event marks an initial "touch" gesture on a UI element.
@constant AUParameterAutomationEventTypeRelease
The event marks a final "release" gesture on a UI element.
*/
typedef NS_ENUM(uint32_t, AUParameterAutomationEventType) {
AUParameterAutomationEventTypeValue = 0,
AUParameterAutomationEventTypeTouch = 1,
AUParameterAutomationEventTypeRelease = 2
};
/*! @typedef AURecordedParameterEvent
@brief An event recording the changing of a parameter at a particular host time.
*/
typedef struct AURecordedParameterEvent {
uint64_t hostTime; ///< The host time at which the event occurred.
AUParameterAddress address; ///< The address of the parameter whose value changed.
AUValue value; ///< The value of the parameter at that time.
} AURecordedParameterEvent;
/*! @typedef AUParameterAutomationEvent
@brief An event recording the changing of a parameter, possibly including events
such as touch and release gestures, at a particular host time.
*/
typedef struct AUParameterAutomationEvent {
uint64_t hostTime; ///< The host time at which the event occurred.
AUParameterAddress address; ///< The address of the parameter whose value changed.
AUValue value; ///< The value of the parameter at that time.
AUParameterAutomationEventType eventType; ///< The type of the event.
uint64_t reserved;
} AUParameterAutomationEvent;
/*! @typedef AUParameterObserver
@brief A block called to signal that the value of a parameter has changed.
@discussion
See the discussion of -[AUParameterNode tokenByAddingParameterObserver:].
@param address
The address of the parameter whose value changed.
@param value
The current value of the parameter.
*/
typedef void (^AUParameterObserver)(AUParameterAddress address, AUValue value);
/*! @typedef AUParameterRecordingObserver
@brief A block called to record parameter changes as automation events.
@discussion
See the discussion of -[AUParameterNode tokenByAddingParameterRecordingObserver:].
@param numberEvents
The number of events being delivered.
@param events
The events being delivered.
*/
typedef void (^AUParameterRecordingObserver)(NSInteger numberEvents, const AURecordedParameterEvent *events);
/*! @typedef AUParameterAutomationObserver
@brief A block called to record parameter changes as automation events.
@discussion
See the discussion of -[AUParameterNode tokenByAddingParameterAutomationObserver:].
@param numberEvents
The number of events being delivered.
@param events
The events being delivered.
*/
typedef void (^AUParameterAutomationObserver)(NSInteger numberEvents, const AUParameterAutomationEvent *events);
/*! @typedef AUParameterObserverToken
@brief A token representing an installed AUParameterObserver, AUParameterRecordingObserver,
or AUParameterAutomationObserver.
*/
typedef void *AUParameterObserverToken;
// =================================================================================================
/*! @class AUParameterNode
@brief A node in an audio unit's tree of parameters.
@discussion
Nodes are instances of either AUParameterGroup or AUParameter.
*/
API_AVAILABLE(macos(10.11), ios(9.0), watchos(2.0), tvos(9.0))
@interface AUParameterNode : NSObject
/*! @property identifier
@brief A non-localized, permanent name for a parameter or group.
@discussion
The identifier must be unique for all child nodes under any given parent. From release to
release, an audio unit must not change its parameters' identifiers; this will invalidate any
hosts' documents that refer to the parameters.
*/
@property (NS_NONATOMIC_IOSONLY, readonly, copy) NSString *identifier;
/*! @property keyPath
@brief Generated by concatenating the identifiers of a node's parents with its own.
@discussion
Unless an audio unit specifically documents that its parameter addresses are stable and
persistent, hosts, when recording parameter values, should bind to the keyPath.
The individual node identifiers in a key path are separated by periods. (".")
Passing a node's keyPath to -[tree valueForKeyPath:] should return the same node.
*/
@property (NS_NONATOMIC_IOSONLY, readonly, copy) NSString *keyPath;
/*! @property displayName
@brief A localized name to display for the parameter.
*/
@property (NS_NONATOMIC_IOSONLY, readonly, copy) NSString *displayName;
/*! @method displayNameWithLength:
@brief A version of displayName possibly abbreviated to the given desired length, in characters.
@discussion
The default implementation simply returns displayName.
*/
- (NSString *)displayNameWithLength:(NSInteger)maximumLength;
/*! @method tokenByAddingParameterObserver:
@brief Add an observer for a parameter or all parameters in a group/tree.
@discussion
An audio unit view can use an AUParameterObserver to be notified of changes
to a single parameter, or to all parameters in a group/tree.
These callbacks are throttled so as to limit the rate of redundant notifications
in the case of frequent changes to a single parameter.
This block is called in an arbitrary thread context. It is responsible for thread-safety.
It must not make any calls to add or remove other observers, including itself;
this will deadlock.
An audio unit's implementation should interact with the parameter object via
implementorValueObserver and implementorValueProvider.
Parameter observers are bound to a specific parameter instance. If this parameter is
destroyed, e.g. if the parameter tree is re-constructed, the previously set parameter
observers will no longer be valid. Clients can observe changes to the parameter tree
via KVO. See the discussion of -[AUAudioUnit parameterTree].
@param observer
A block to call after the value of a parameter has changed.
@return
A token which can be passed to removeParameterObserver: or to -[AUParameter setValue:originator:]
*/
- (AUParameterObserverToken)tokenByAddingParameterObserver:(AUParameterObserver)observer;
/*! @method tokenByAddingParameterRecordingObserver:
@brief Add a recording observer for a parameter or all parameters in a group/tree.
@discussion
This is a variant of tokenByAddingParameterAutomationObserver where the callback receives
AURecordedParameterEvents instead of AUParameterAutomationEvents.
This will be deprecated in favor of tokenByAddingParameterAutomationObserver in a future
release.
*/
- (AUParameterObserverToken)tokenByAddingParameterRecordingObserver:(AUParameterRecordingObserver)observer;
/*! @method tokenByAddingParameterAutomationObserver:
@brief Add a recording observer for a parameter or all parameters in a group/tree.
@discussion
An audio unit host can use an AUParameterAutomationObserver or AUParameterRecordingObserver
to capture a series of changes to a parameter value, including the timing of the events, as
generated by a UI gesture in a view, for example.
Unlike AUParameterObserver, these callbacks are not throttled.
This block is called in an arbitrary thread context. It is responsible for thread-safety.
It must not make any calls to add or remove other observers, including itself;
this will deadlock.
An audio unit's engine should interact with the parameter object via
implementorValueObserver and implementorValueProvider.
@param observer
A block to call to record the changing of a parameter value.
@return
A token which can be passed to removeParameterObserver: or to -[AUParameter
setValue:originator:]
*/
- (AUParameterObserverToken)tokenByAddingParameterAutomationObserver:(AUParameterAutomationObserver)observer API_AVAILABLE(macos(10.12), ios(10.0), watchos(3.0), tvos(10.0));
/*! @method removeParameterObserver:
@brief Remove an observer created with tokenByAddingParameterObserver,
tokenByAddingParameterRecordingObserver, or tokenByAddingParameterAutomationObserver.
@discussion
This call will remove the callback corresponding to the supplied token. Note that this
will block until any callbacks currently in flight have completed.
*/
- (void)removeParameterObserver:(AUParameterObserverToken)token;
@end
// =================================================================================================
/*! @class AUParameterGroup
@brief A group of related parameters.
@discussion
A parameter group is KVC-compliant for its children; e.g. valueForKey:@"volume" will
return a child parameter whose identifier is "volume".
*/
API_AVAILABLE(macos(10.11), ios(9.0), watchos(2.0), tvos(9.0))
@interface AUParameterGroup : AUParameterNode <NSSecureCoding>
/// The group's child nodes (AUParameterGroupNode).
@property (NS_NONATOMIC_IOSONLY, readonly) NSArray<AUParameterNode *> *children;
/// Returns a flat array of all parameters in the group, including those in child groups.
@property (NS_NONATOMIC_IOSONLY, readonly) NSArray<AUParameter *> *allParameters;
@end
// =================================================================================================
/*! @class AUParameterTree
@brief The top level group node, representing all of an audio unit's parameters.
@discussion
An audio unit's parameters are organized into a tree containing groups and parameters.
Groups may be nested.
The tree is KVO-compliant. For example, if the tree contains a group named "LFO" ,
containing a parameter named rate, then "LFO.rate" refers to that parameter object, and
"LFO.rate.value" refers to that parameter's value.
An audio unit may choose to dynamically rearrange the tree. When doing so, it must
issue a KVO notification on the audio unit's parameterTree property. The tree's elements are
mostly immutable (except for values and implementor hooks); the only way to modify them
is to publish a new tree.
*/
API_AVAILABLE(macos(10.11), ios(9.0), watchos(2.0), tvos(9.0))
@interface AUParameterTree : AUParameterGroup <NSSecureCoding>
/*! @method parameterWithAddress:
@brief Search a tree for a parameter with a specific address.
@return
The parameter corresponding to the supplied address, or nil if no such parameter exists.
*/
- (AUParameter *__nullable)parameterWithAddress:(AUParameterAddress)address;
/*! @method parameterWithID:scope:element:
@brief Search a tree for a specific v2 audio unit parameter.
@discussion
V2 audio units publish parameters identified by a parameter ID, scope, and element.
A host that knows that it is dealing with a v2 unit can locate parameters using this method,
for example, for the Apple-supplied system audio units.
@return
The parameter corresponding to the supplied ID/scope/element, or nil if no such parameter
exists, or if the audio unit is not a v2 unit.
*/
- (AUParameter *__nullable)parameterWithID:(AudioUnitParameterID)paramID scope:(AudioUnitScope)scope element:(AudioUnitElement)element;
@end
// =================================================================================================
// AUParameter
/*! @class AUParameter
@brief A node representing a single parameter.
*/
API_AVAILABLE(macos(10.11), ios(9.0), watchos(2.0), tvos(9.0))
@interface AUParameter : AUParameterNode <NSSecureCoding>
/// The parameter's minimum value.
@property (NS_NONATOMIC_IOSONLY, readonly) AUValue minValue;
/// The parameter's maximum value.
@property (NS_NONATOMIC_IOSONLY, readonly) AUValue maxValue;
/// The parameter's unit of measurement.
@property (NS_NONATOMIC_IOSONLY, readonly) AudioUnitParameterUnit unit;
/// A localized name for the parameter's unit. Supplied by the AU if kAudioUnitParameterUnit_CustomUnit; else by the framework.
@property (NS_NONATOMIC_IOSONLY, readonly, copy, nullable) NSString *unitName;
/// Various details of the parameter.
@property (NS_NONATOMIC_IOSONLY, readonly) AudioUnitParameterOptions flags;
/// The parameter's address.
@property (NS_NONATOMIC_IOSONLY, readonly) AUParameterAddress address;
/// For parameters with kAudioUnitParameterUnit_Indexed, localized strings corresponding
/// to the values.
@property (NS_NONATOMIC_IOSONLY, readonly, copy, nullable) NSArray<NSString *> *valueStrings;
/*! @brief Parameters whose values may change as a side effect of this parameter's value
changing.
@discussion
Each array value is an NSNumber representing AUParameterAddress.
*/
@property (NS_NONATOMIC_IOSONLY, readonly, copy, nullable) NSArray<NSNumber *> *dependentParameters;
/// The parameter's current value.
@property (NS_NONATOMIC_IOSONLY) AUValue value;
///
/*! @brief Set the parameter's value, avoiding redundant notifications to the originator.
@discussion
Bridged to the v2 function AudioUnitSetParameter.
*/
- (void)setValue:(AUValue)value originator:(AUParameterObserverToken __nullable)originator;
/*! @brief Convenience for setValue:originator:atHostTime:eventType:
@discussion
Bridged to the v2 function AudioUnitSetParameter.
*/
- (void)setValue:(AUValue)value originator:(AUParameterObserverToken __nullable)originator atHostTime:(uint64_t)hostTime;
/*! @brief Set the parameter's value, preserving the host time of the gesture that initiated the
change, and associating an event type such as touch/release.
@discussion
In general, this method should only be called from a user interface. It initiates a change
to a parameter in a way that captures the gesture such that it can be recorded later --
any AUParameterAutomationObservers will receive the host time and event type associated
with the parameter change.
From an audio playback engine, a host should schedule automated parameter changes through
AUAudioUnit's scheduleParameterBlock.
Bridged to the v2 function AudioUnitSetParameter.
*/
- (void)setValue:(AUValue)value originator:(AUParameterObserverToken __nullable)originator atHostTime:(uint64_t)hostTime eventType:(AUParameterAutomationEventType)eventType API_AVAILABLE(macos(10.12), ios(10.0), watchos(3.0), tvos(10.0));
/*! @brief Get a textual representation of a value for the parameter. Use value==nil to use the
current value. Bridged to the v2 property kAudioUnitProperty_ParameterStringFromValue.
@discussion
This is currently only supported for parameters whose flags include
kAudioUnitParameterFlag_ValuesHaveStrings.
*/
- (NSString *)stringFromValue:(const AUValue *__nullable)value;
/*! @brief Convert a textual representation of a value to a numeric one.
@discussion
This is currently only supported for parameters whose flags include
kAudioUnitParameterFlag_ValuesHaveStrings.
*/
- (AUValue)valueFromString:(NSString *)string;
@end
NS_ASSUME_NONNULL_END
#endif // __OBJC2__
#endif // AudioToolbox_AUParameters_h
#else
#include <AudioToolboxCore/AUParameters.h>
#endif

View File

@@ -0,0 +1,700 @@
#if (defined(__USE_PUBLIC_HEADERS__) && __USE_PUBLIC_HEADERS__) || (defined(USE_AUDIOTOOLBOX_PUBLIC_HEADERS) && USE_AUDIOTOOLBOX_PUBLIC_HEADERS) || !__has_include(<AudioToolboxCore/AudioComponent.h>)
/*!
@file AudioComponent.h
@framework AudioToolbox.framework
@copyright (c) 2007-2020 Apple Inc. All rights reserved.
@brief API's to locate, get information about, and open audio components.
@discussion
This header file defines a collection of APIs to find, get information about, and open
audio components (such as audio units, audio codecs, and audio file components).
Originally, CoreServices' Component Manager was used for the registration, discovery, and
packaging of these loadable code modules. However, in order to provide an API that will be
supported going forward from macOS 10.6 and iOS 2.0, it is advised that applications use the
Audio Component APIs to find and load (open) audio components such as audio units.
The type "AudioComponent" or "AudioComponentInstance" should be seen and used as a distinct type
from the Component Manager types of "Component" and "ComponentInstance". It is never safe to
assume a direct cast is compatible between this type and the other.
Beginning with macOS 10.7, AudioComponents can be registered and used directly without
involving the Component Manager. The system scans certain directories for bundles with names
ending in ".audiocomp" or ".component" (the latter permits registering plug-ins in a single
bundle with both the Component Manager and the Audio Component system). These directories are
scanned non-recursively:
- ~/Library/Audio/Plug-Ins/Components
- /Library/Audio/Plug-Ins/Components
- /System/Library/Components
Bundles' Info.plist dictionaries should contain an "AudioComponents" item whose value
is an array of dictionaries, e.g.
```
<key>AudioComponents</key>
<array>
<dict>
<key>type</key>
<string>aufx</string>
<key>subtype</key>
<string>XMPL</string>
<key>manufacturer</key>
<string>ACME</string>
<key>name</key>
<string>AUExample</string>
<key>version</key>
<integer>12345</integer>
<key>factoryFunction</key>
<string>AUExampleFactory</string>
<!-- An AudioComponent is sandbox safe -->
<key>sandboxSafe</key>
<true/>
<!-- or it can describe its resource usage -->
<key>resourceUsage</key>
<dict>
<key>iokit.user-client</key>
<array>
<string>CustomUserClient1</string>
<string>CustomUserClient2</string>
</array>
<key>mach-lookup.global-name</key>
<array>
<string>MachServiceName1</string>
<string>MachServiceName2</string>
</array>
<key>network.client</key>
<true/>
<key>temporary-exception.files.all.read-write</key>
</true>
</dict>
<!-- An AudioComponent can define its tags -->
<key>tags</key>
<array>
<string>Effect</string>
<string>Equalizer</string>
</array>
</dict>
</array>
```
The type, subtype and manufacturer keys correspond to the OSType fields of the
AudioComponentDescription structure. They can be strings if they are 4 ASCII characters;
otherwise they must be 32-bit integers.
The "factoryFunction" is the name of a AudioComponentFactoryFunction in the bundle's binary.
Sandbox-Safety
--------------
The "sandboxSafe" key is used to indicate whether or not an AudioComponent can be loaded
directly into a sandboxed process. This key is reflected in the componentFlags field of the the
AudioComponentDescription for the AudioComponent with the constant,
kAudioComponentFlag_SandboxSafe. Note that if this key is not present, it is assumed that the
AudioComponent is not sandbox safe.
The "resourceUsage" key describes the system resources used by an AudioComponent that is not
sandbox safe. The keys for this dictionary are described below. If the "sandboxSafe" key is
true, this dictionary should not be included.
The "iokit.user-client" key is a "resourceUsage" key that describes the IOKit user-client
objects the AudioComponent will open. It is an array of the user-clients' class names.
The "mach-lookup.global-name" key is a "resourceUsage" key that describes the mach services the
AudioComponent needs to connect to. It is an array of the names of the services. Note that these
services can be direct mach services found via bootstrap_look_up() or XPC services found via
xpc_connection_create_mach_service().
The "network.client" key is a "resourceUsage" key that indicates that the AudioComponent will
receive data from the network.
The "temporary-exception.files.all.read-write" key is a "resourceUsage" key that indicates that
the AudioComponent needs arbitrary access to the file system. This is for backward compatibility
for AudioComponents that have not yet adopted the usage of security scope bookmarks and/or the
usage of the standard file dialog for discovering, accessing and storing persistent references
to files on the file system. In a future OS release, this key will not be supported.
Note that a sandbox-safe AudioComponent can function correctly in even the most severely
sandboxed process. This means that the process will have curtailed or no access to common system
resources like the file system, device drivers, the network, and communication with other
processes.
When instantiating a sandbox unsafe AudioComponent in a sandboxed process, the system evaluates
the "resourceUsage" information against the restrictions the process is under. If the
"resourceUsage" will not violate those restrictions, the AudioComponent will be instantiated and
can be used as normal. Note that the system will set kAudioComponentFlag_SandboxSafe in the
AudioComponentDescription in this case.
If the "resourceUsage" information includes things that can't be accessed from the process and
the process has the entitlement, "com.apple.security.temporary-exception.audio-unit-host", the
system will ask the user whether or not it is acceptable for the process to open the unsafe
AudioComponent. If the user says yes, the system will suspend the process's sandbox and allow
the unsafe AudioComponent to be opened and used.
Tags
----
The "tags" key is an array of tags associated with the defined AudioComponent. The following are
the set of predefined standard tags that are localized and can be used in the audio unit
definition. "Equalizer", "Dynamics", "Distortion", "Synthesizer", "Effects", "Filter", "Dynamics
Processor", "Delay", "Reverb", "Pitch", "Panner", "Imaging", "Sampler", "Mixer", "Format
Converter", "Time Effect", "Output", "Offline Effect", "Drums", "Guitar", "Vocal", "Bass",
"MIDI".
These standard tags should not be localized in the audio unit.
Localizing the tags is similar to localizing AudioUnit parameter strings. Create a strings
resource file and name it "AudioUnitTags.strings".
For more information on strings resource file please check
https://developer.apple.com/library/mac/documentation/macosx/conceptual/bpinternational/Articles/StringsFiles.html
*/
#ifndef AudioUnit_AudioComponent_h
#define AudioUnit_AudioComponent_h
//=====================================================================================================================
#pragma mark Overview
#include <TargetConditionals.h>
#include <Availability.h>
#include <CoreAudioTypes/CoreAudioTypes.h>
#include <CoreFoundation/CoreFoundation.h>
CF_ASSUME_NONNULL_BEGIN
//=====================================================================================================================
#pragma mark Constants
/*!
@enum AudioComponentFlags
@brief Flags found in AudioComponentDescription.componentFlags.
@constant kAudioComponentFlag_Unsearchable
When this bit in AudioComponentDescription's componentFlags is set, AudioComponentFindNext
will only return this component when performing a specific, non-wildcard search for the
component, i.e. with non-zero values of componentType, componentSubType, and
componentManufacturer. This can be useful when privately registering a component.
@constant kAudioComponentFlag_SandboxSafe
An AudioComponent sets this bit in its componentFlags to indicate to the system that the
AudioComponent is safe to open in a sandboxed process.
@constant kAudioComponentFlag_IsV3AudioUnit
The system sets this flag automatically when registering components which implement a version 3
Audio Unit.
@constant kAudioComponentFlag_RequiresAsyncInstantiation
The system sets this flag automatically when registering components which require asynchronous
instantiation via AudioComponentInstantiate (v3 audio units with views).
@constant kAudioComponentFlag_CanLoadInProcess
The system sets this flag automatically when registering components which can be loaded into
the current process. This is always true for V2 audio units; it depends on the packaging
in the case of a V3 audio unit.
*/
typedef CF_OPTIONS(UInt32, AudioComponentFlags) {
kAudioComponentFlag_Unsearchable CF_ENUM_AVAILABLE(10_7, 5_0) = 1,
kAudioComponentFlag_SandboxSafe CF_ENUM_AVAILABLE(10_8, 6_0) = 2,
kAudioComponentFlag_IsV3AudioUnit CF_ENUM_AVAILABLE(10_11, 9_0) = 4,
kAudioComponentFlag_RequiresAsyncInstantiation CF_ENUM_AVAILABLE(10_11, 9_0) = 8,
kAudioComponentFlag_CanLoadInProcess CF_ENUM_AVAILABLE(10_11, 9_0) = 0x10
};
/*! @enum AudioComponentInstantiationOptions
@brief Options controlling component instantiation.
@discussion
Most component instances are loaded into the calling process.
A version 3 audio unit, however, can be loaded into a separate extension service process,
and this is the default behavior for these components. To be able to load one in-process
requires that the developer package the audio unit in a bundle separate from the application
extension, since an extension's main binary cannot be dynamically loaded into another
process.
A macOS host may request in-process loading of such audio units using
kAudioComponentInstantiation_LoadInProcess.
kAudioComponentFlag_IsV3AudioUnit specifies whether an audio unit is implemented using API
version 3.
These options are just requests to the implementation. It may fail and fall back to the
default.
@constant kAudioComponentInstantiation_LoadOutOfProcess
Attempt to load the component into a separate extension process.
@constant kAudioComponentInstantiation_LoadInProcess
Attempt to load the component into the current process. Only available on macOS.
*/
typedef CF_OPTIONS(UInt32, AudioComponentInstantiationOptions) {
kAudioComponentInstantiation_LoadOutOfProcess CF_ENUM_AVAILABLE(10_11, 9_0) = 1,
kAudioComponentInstantiation_LoadInProcess CF_ENUM_AVAILABLE(10_11, NA) = 2,
kAudioComponentInstantiation_LoadedRemotely API_UNAVAILABLE(macos) = 1u << 31,
};
//=====================================================================================================================
#pragma mark Data Types
/*!
@struct AudioComponentDescription
@discussion A structure describing the unique and identifying IDs of an audio component
@var componentType
A 4-char code identifying the generic type of an audio component.
@var componentSubType
A 4-char code identifying the a specific individual component. type/
subtype/manufacturer triples must be globally unique.
@var componentManufacturer
Vendor identification.
@var componentFlags
Must be set to zero unless a known specific value is requested.
@var componentFlagsMask
Must be set to zero unless a known specific value is requested.
*/
#pragma pack(push, 4)
typedef struct AudioComponentDescription {
OSType componentType;
OSType componentSubType;
OSType componentManufacturer;
UInt32 componentFlags;
UInt32 componentFlagsMask;
} AudioComponentDescription;
#pragma pack(pop)
/*!
@typedef AudioComponent
@abstract The type used to represent a class of particular audio components
@discussion An audio component is usually found through a search and is then uniquely
identified by the triple of an audio component's type, subtype and
manufacturer.
It can have properties associated with it (such as a name, a version).
It is then used as a factory (like a class in an object-oriented programming
language) from which to create instances. The instances are used to do the
actual work.
For example: the AudioComponentDescription 'aufx'/'dely'/'appl' describes the
delay audio unit effect from Apple, Inc. You can find this component by
searching explicitly for the audio component that matches this pattern (this is
an unique identifier - there is only one match to this triple ID). Then once
found, instances of the Apple delay effect audio unit can be created from its
audio component and used to apply that effect to an audio signal. A single
component can create any number of component instances.
*/
typedef struct OpaqueAudioComponent * AudioComponent;
/*!
@typedef AudioComponentInstance
@abstract The type used to represent an instance of a particular audio component
@discussion An audio component instance is created from its factory/producer audio
component. It is the body of code that does the work.
A special note: While on the desktop this is typedef'd to a
ComponentInstanceRecord *, you should not assume that this will always be
compatible and usable with Component Manager calls.
*/
#if TARGET_OS_IPHONE || (defined(AUDIOCOMPONENT_NOCARBONINSTANCES) && AUDIOCOMPONENT_NOCARBONINSTANCES)
typedef struct OpaqueAudioComponentInstance * AudioComponentInstance;
#else
typedef struct ComponentInstanceRecord * AudioComponentInstance;
#endif
/*!
@typedef AudioComponentMethod
@abstract Generic prototype for an audio plugin method.
@discussion Every audio plugin will implement a collection of methods that match a particular
selector. For example, the AudioUnitInitialize API call is implemented by a
plugin implementing the kAudioUnitInitializeSelect selector. Any function implementing
an audio plugin selector conforms to the basic pattern where the first argument
is a pointer to the plugin instance structure, has 0 or more specific arguments,
and returns an OSStatus.
*/
typedef OSStatus (*AudioComponentMethod)(void *self, ...);
/*!
@struct AudioComponentPlugInInterface
@discussion A structure used to represent an audio plugin's routines
@var Open
the function used to open (or create) an audio plugin instance
@var Close
the function used to close (or dispose) an audio plugin instance
@var Lookup
this is used to return a function pointer for a given selector,
or NULL if that selector is not implemented
@var reserved
must be NULL
*/
struct AudioComponentPlugInInterface {
OSStatus (*Open)(void *self, AudioComponentInstance mInstance);
OSStatus (*Close)(void *self);
AudioComponentMethod __nullable (* __nonnull Lookup)(SInt16 selector);
void * __nullable reserved;
};
typedef struct AudioComponentPlugInInterface AudioComponentPlugInInterface;
/*!
@typedef AudioComponentFactoryFunction
@abstract A function that creates AudioComponentInstances.
@discussion
Authors of AudioComponents may register them from bundles as described
above in the discussion of this header file, or dynamically within a single
process, using AudioComponentRegister.
@param inDesc
The AudioComponentDescription specifying the component to be instantiated.
@result A pointer to a AudioComponentPlugInInterface structure.
*/
typedef AudioComponentPlugInInterface * __nullable (*AudioComponentFactoryFunction)(const AudioComponentDescription *inDesc);
//=====================================================================================================================
#pragma mark Functions
#ifdef __cplusplus
extern "C" {
#endif
/*!
@function AudioComponentFindNext
@abstract Finds an audio component.
@discussion This function is used to find an audio component that is the closest match
to the provided values. Note that the list of available components may change
dynamically in situations involving inter-app audio on iOS, or version 3
audio unit extensions. See kAudioComponentRegistrationsChangedNotification.
@param inComponent
If NULL, then the search starts from the beginning until an audio
component is found that matches the description provided by inDesc.
If non-NULL, then the search starts (continues) from the previously
found audio component specified by inComponent, and will return the next
found audio component.
@param inDesc
The type, subtype and manufacturer fields are used to specify the audio
component to search for. A value of 0 (zero) for any of these fields is
a wildcard, so the first match found is returned.
@result An audio component that matches the search parameters, or NULL if none found.
*/
extern AudioComponent __nullable
AudioComponentFindNext ( AudioComponent __nullable inComponent,
const AudioComponentDescription * inDesc)
API_AVAILABLE(macos(10.6), ios(2.0), watchos(2.0), tvos(9.0));
/*!
@function AudioComponentCount
@abstract Counts audio components.
@discussion Returns the number of AudioComponents that match the specified
AudioComponentDescription.
@param inDesc
The type, subtype and manufacturer fields are used to specify the audio
components to count A value of 0 (zero) for any of these fields is a
wildcard, so will match any value for this field
@result a UInt32. 0 (zero) means no audio components were found that matched the
search parameters.
*/
extern UInt32
AudioComponentCount ( const AudioComponentDescription * inDesc)
API_AVAILABLE(macos(10.6), ios(2.0), watchos(2.0), tvos(9.0));
/*!
@function AudioComponentCopyName
@abstract Retrieves the name of an audio component.
@discussion the name of an audio component
@param inComponent
the audio component (must not be NULL)
@param outName
a CFString that is the name of the audio component. This string should
be released by the caller.
@result an OSStatus result code.
*/
extern OSStatus
AudioComponentCopyName ( AudioComponent inComponent,
CFStringRef __nullable * __nonnull outName)
API_AVAILABLE(macos(10.6), ios(2.0), watchos(2.0), tvos(9.0));
/*!
@function AudioComponentGetDescription
@abstract Retrieve an audio component's description.
@discussion This will return the fully specified audio component description for the
provided audio component.
@param inComponent
the audio component (must not be NULL)
@param outDesc
the audio component description for the specified audio component
@result an OSStatus result code.
*/
extern OSStatus
AudioComponentGetDescription( AudioComponent inComponent,
AudioComponentDescription * outDesc)
API_AVAILABLE(macos(10.6), ios(2.0), watchos(2.0), tvos(9.0));
/*!
@function AudioComponentGetVersion
@abstract Retrieve an audio component's version.
@param inComponent
the audio component (must not be NULL)
@param outVersion
the audio component's version in the form of 0xMMMMmmDD (Major, Minor, Dot)
@result an OSStatus result code.
*/
extern OSStatus
AudioComponentGetVersion( AudioComponent inComponent,
UInt32 * outVersion)
API_AVAILABLE(macos(10.6), ios(2.0), watchos(2.0), tvos(9.0));
#if defined(__OBJC__) && !TARGET_OS_IPHONE
@class NSImage;
/*!
@function AudioComponentGetIcon
@abstract Fetches an icon representing the component.
@param comp
The component whose icon is to be retrieved.
@result
An autoreleased NSImage object.
@discussion
For a component originating in an app extension, the returned icon will be that of the
application containing the extension.
For components loaded from bundles, the icon will be that of the bundle.
*/
extern NSImage * __nullable
AudioComponentGetIcon(AudioComponent comp) API_DEPRECATED_WITH_REPLACEMENT("AudioComponentCopyIcon", macos(10.11, 11.0)) API_UNAVAILABLE(ios, watchos, tvos);
#endif
/*!
@function AudioComponentInstanceNew
@abstract Creates an audio component instance.
@discussion This function creates an instance of a given audio component. The audio
component instance is the object that does all of the work, whereas the
audio component is the way an application finds and then creates this object
to do this work. For example, an audio unit is a type of audio component
instance, so to use an audio unit, one finds its audio component, and then
creates a new instance of that component. This instance is then used to
perform the audio tasks for which it was designed (process, mix, synthesise,
etc.).
@param inComponent
the audio component (must not be NULL)
@param outInstance
the audio component instance
@result an OSStatus result code.
*/
extern OSStatus
AudioComponentInstanceNew( AudioComponent inComponent,
AudioComponentInstance __nullable * __nonnull outInstance)
API_AVAILABLE(macos(10.6), ios(2.0), watchos(2.0), tvos(9.0));
/*!
@function AudioComponentInstantiate
@abstract Creates an audio component instance, asynchronously.
@discussion This is an asynchronous version of AudioComponentInstanceNew(). It must be
used to instantiate any component with kAudioComponentFlag_RequiresAsyncInstantiation
set in its component flags. It may be used for other components as well.
Note: Do not block the main thread while waiting for the completion handler
to be called; this can deadlock.
@param inComponent
the audio component
@param inOptions
see AudioComponentInstantiationOptions
@param inCompletionHandler
called in an arbitrary thread context when instantiation is complete.
*/
extern void
AudioComponentInstantiate( AudioComponent inComponent,
AudioComponentInstantiationOptions inOptions,
void (^inCompletionHandler)(AudioComponentInstance __nullable, OSStatus))
API_AVAILABLE(macos(10.11), ios(9.0), watchos(2.0), tvos(9.0));
/*!
@function AudioComponentInstanceDispose
@abstract Disposes of an audio component instance.
@discussion This function will dispose the audio component instance that was created
with the New call. It will deallocate any resources that the instance was using.
@param inInstance
the audio component instance to dispose (must not be NULL)
@result an OSStatus result code.
*/
extern OSStatus
AudioComponentInstanceDispose( AudioComponentInstance inInstance)
API_AVAILABLE(macos(10.6), ios(2.0), watchos(2.0), tvos(9.0));
/*!
@function AudioComponentInstanceGetComponent
@abstract Retrieve the audio component from its instance
@discussion Allows the application at any time to retrieve the audio component that is
the factory object of a given instance (i.e., the audio component that was
used to create the instance in the first place). This allows the application
to retrieve general information about a particular audio component (its
name, version, etc) when one just has an audio component instance to work
with
@param inInstance
the audio component instance (must not be NULL, and instance must be valid - that is, not disposed)
@result a valid audio component or NULL if no component was found.
*/
extern AudioComponent
AudioComponentInstanceGetComponent ( AudioComponentInstance inInstance)
API_AVAILABLE(macos(10.6), ios(2.0), watchos(2.0), tvos(9.0));
/*!
@function AudioComponentInstanceCanDo
@discussion Determines if an audio component instance implements a particular component
API call as signified by the specified selector identifier token.
@param inInstance
the audio component instance
@param inSelectorID
a number to signify the audio component API (component selector) as appropriate for the instance's component type.
@result a boolean
*/
extern Boolean
AudioComponentInstanceCanDo ( AudioComponentInstance inInstance,
SInt16 inSelectorID)
API_AVAILABLE(macos(10.6), ios(3.0), watchos(2.0), tvos(9.0));
/*!
@function AudioComponentRegister
@abstract Dynamically registers an AudioComponent within the current process
@discussion
AudioComponents are registered either when found in appropriate bundles in the filesystem,
or via this call. AudioComponents registered via this call are available only within
the current process.
@param inDesc
The AudioComponentDescription that describes the AudioComponent. Note that
the registrar needs to be sure to set the flag kAudioComponentFlag_SandboxSafe
in the componentFlags field of the AudioComponentDescription to indicate that
the AudioComponent can be loaded directly into a sandboxed process.
@param inName
the AudioComponent's name
@param inVersion
the AudioComponent's version
@param inFactory
an AudioComponentFactoryFunction which will create instances of your
AudioComponent
@result an AudioComponent object
*/
extern AudioComponent
AudioComponentRegister( const AudioComponentDescription * inDesc,
CFStringRef inName,
UInt32 inVersion,
AudioComponentFactoryFunction inFactory)
API_AVAILABLE(macos(10.7), ios(5.0), watchos(2.0), tvos(9.0));
/*!
@function AudioComponentCopyConfigurationInfo
@abstract Fetches the basic configuration info about a given AudioComponent
@discussion Currently, only AudioUnits can supply this information.
@param inComponent
The AudioComponent whose info is being fetched.
@param outConfigurationInfo
On exit, this is CFDictionaryRef that contains information describing the
capabilities of the AudioComponent. The specific information depends on the
type of AudioComponent. The keys for the dictionary are defined in
AudioUnitProperties.h (or other headers as appropriate for the component type).
@result An OSStatus indicating success or failure.
*/
extern OSStatus
AudioComponentCopyConfigurationInfo( AudioComponent inComponent,
CFDictionaryRef __nullable * __nonnull outConfigurationInfo)
API_AVAILABLE(macos(10.7)) API_UNAVAILABLE(ios, watchos, tvos);
/*!
@enum AudioComponentValidationResult
@abstract Constants for describing the result of validating an AudioComponent
@constant kAudioComponentValidationResult_Passed
The AudioComponent passed validation.
@constant kAudioComponentValidationResult_Failed
The AudioComponent failed validation.
@constant kAudioComponentValidationResult_TimedOut
The validation operation timed out before completing.
@constant kAudioComponentValidationResult_UnauthorizedError_Open
The AudioComponent failed validation during open operation as it is not authorized.
@constant kAudioComponentValidationResult_UnauthorizedError_Init
The AudioComponent failed validation during initialization as it is not authorized.
*/
typedef CF_ENUM(UInt32, AudioComponentValidationResult)
{
kAudioComponentValidationResult_Unknown = 0,
kAudioComponentValidationResult_Passed,
kAudioComponentValidationResult_Failed,
kAudioComponentValidationResult_TimedOut,
kAudioComponentValidationResult_UnauthorizedError_Open,
kAudioComponentValidationResult_UnauthorizedError_Init
};
/*!
@define kAudioComponentConfigurationInfo_ValidationResult
@abstract Dictionary that contains the AudioComponentValidationResult for the component.
@discussion
The keys in this dictionary are the CPU architectures (e.g. "i386") that generated each result.
*/
#define kAudioComponentConfigurationInfo_ValidationResult "ValidationResult"
/*!
@function AudioComponentValidate
@abstract Tests a specified AudioComponent for API and behavioral conformance.
@discussion Currently, only AudioUnits can can be validated.
@param inComponent
The AudioComponent to validate.
@param inValidationParameters
A CFDictionaryRef that contains parameters for the validation operation.
Passing NULL for this argument tells the system to use the default
parameters.
@param outValidationResult
On exit, this is an AudioComponentValidationResult.
@result an OSStatus result code.
*/
extern OSStatus
AudioComponentValidate( AudioComponent inComponent,
CFDictionaryRef __nullable inValidationParameters,
AudioComponentValidationResult *outValidationResult)
API_AVAILABLE(macos(10.7)) API_UNAVAILABLE(ios, watchos, tvos);
/*!
@define kAudioComponentValidationParameter_TimeOut
@discussion This is a number that indicates the time in seconds to wait for a validation
operation to complete. Note that if a validation operation times out, it will return
kAudioComponentValidationResult_TimedOut as its result.
*/
#define kAudioComponentValidationParameter_TimeOut "TimeOut"
/*!
@define kAudioComponentValidationParameter_ForceValidation
@discussion
This is a bool that indicates to ignore the cached value and run validation on the specified
audio unit and update the cache.
*/
#define kAudioComponentValidationParameter_ForceValidation "ForceValidation"
/*!
@define kAudioComponentValidationParameter_LoadOutOfProcess
@discussion
This is a bool that can be used when validating Audio Units and it specifies that the
Audio Unit should be loaded out-of-process during validation.
Under normal circumstances, the validation result should not be influenced by how
the Audio Unit is loaded (in- or out-of-process). This option allows a host
that plans on loading the Audio Unit out-of-process to make sure that it passes the
validation checks in this mode of operation.
*/
#define kAudioComponentValidationParameter_LoadOutOfProcess "LoadOutOfProcess"
#ifdef __cplusplus
}
#endif
CF_ASSUME_NONNULL_END
#endif // AudioUnit_AudioComponent_h
#else
#include <AudioToolboxCore/AudioComponent.h>
#endif

View File

@@ -0,0 +1,895 @@
#if (defined(__USE_PUBLIC_HEADERS__) && __USE_PUBLIC_HEADERS__) || (defined(USE_AUDIOTOOLBOX_PUBLIC_HEADERS) && USE_AUDIOTOOLBOX_PUBLIC_HEADERS) || !__has_include(<AudioToolboxCore/AudioConverter.h>)
/*!
@file AudioConverter.h
@framework AudioToolbox.framework
@copyright (c) 1985-2015 by Apple, Inc., all rights reserved.
@abstract API's to perform audio format conversions.
AudioConverters convert between various linear PCM and compressed
audio formats. Supported transformations include:
- PCM float/integer/bit depth conversions
- PCM sample rate conversion
- PCM interleaving and deinterleaving
- encoding PCM to compressed formats
- decoding compressed formats to PCM
A single AudioConverter may perform more than one
of the above transformations.
*/
#ifndef AudioToolbox_AudioConverter_h
#define AudioToolbox_AudioConverter_h
//=============================================================================
// Includes
//=============================================================================
#include <Availability.h>
#include <CoreAudioTypes/CoreAudioTypes.h>
CF_ASSUME_NONNULL_BEGIN
#if defined(__cplusplus)
extern "C"
{
#endif
//=============================================================================
// Theory of Operation
//=============================================================================
//=============================================================================
// Types specific to the Audio Converter API
//=============================================================================
/*!
@typedef AudioConverterRef
@abstract A reference to an AudioConverter object.
*/
typedef struct OpaqueAudioConverter * AudioConverterRef;
typedef UInt32 AudioConverterPropertyID;
//=============================================================================
// Standard Properties
//=============================================================================
/*!
@enum AudioConverter Property IDs
@abstract The properties of an AudioConverter, accessible via AudioConverterGetProperty()
and AudioConverterSetProperty().
@constant kAudioConverterPropertyMinimumInputBufferSize
a UInt32 that indicates the size in bytes of the smallest buffer of input
data that can be supplied via the AudioConverterInputProc or as the input to
AudioConverterConvertBuffer
@constant kAudioConverterPropertyMinimumOutputBufferSize
a UInt32 that indicates the size in bytes of the smallest buffer of output
data that can be supplied to AudioConverterFillComplexBuffer or as the output to
AudioConverterConvertBuffer
@constant kAudioConverterPropertyMaximumInputPacketSize
a UInt32 that indicates the size in bytes of the largest single packet of
data in the input format. This is mostly useful for variable bit rate
compressed data (decoders).
@constant kAudioConverterPropertyMaximumOutputPacketSize
a UInt32 that indicates the size in bytes of the largest single packet of
data in the output format. This is mostly useful for variable bit rate
compressed data (encoders).
@constant kAudioConverterPropertyCalculateInputBufferSize
a UInt32 that on input holds a size in bytes that is desired for the output
data. On output, it will hold the size in bytes of the input buffer required
to generate that much output data. Note that some converters cannot do this
calculation.
@constant kAudioConverterPropertyCalculateOutputBufferSize
a UInt32 that on input holds a size in bytes that is desired for the input
data. On output, it will hold the size in bytes of the output buffer
required to hold the output data that will be generated. Note that some
converters cannot do this calculation.
@constant kAudioConverterPropertyInputCodecParameters
The value of this property varies from format to format and is considered
private to the format. It is treated as a buffer of untyped data.
@constant kAudioConverterPropertyOutputCodecParameters
The value of this property varies from format to format and is considered
private to the format. It is treated as a buffer of untyped data.
@constant kAudioConverterSampleRateConverterComplexity
An OSType that specifies the sample rate converter algorithm to use (as defined in
AudioToolbox/AudioUnitProperties.h)
@constant kAudioConverterSampleRateConverterQuality
A UInt32 that specifies rendering quality of the sample rate converter (see
enum constants below)
@constant kAudioConverterSampleRateConverterInitialPhase
A Float64 with value 0.0 <= x < 1.0 giving the initial subsample position of the
sample rate converter.
@constant kAudioConverterCodecQuality
A UInt32 that specifies rendering quality of a codec (see enum constants
below)
@constant kAudioConverterPrimeMethod
a UInt32 specifying priming method (usually for sample-rate converter) see
explanation for struct AudioConverterPrimeInfo below along with enum
constants
@constant kAudioConverterPrimeInfo
A pointer to AudioConverterPrimeInfo (see explanation for struct
AudioConverterPrimeInfo below)
@constant kAudioConverterChannelMap
An array of SInt32's. The size of the array is the number of output
channels, and each element specifies which input channel's data is routed to
that output channel (using a 0-based index of the input channels), or -1 if
no input channel is to be routed to that output channel. The default
behavior is as follows. I = number of input channels, O = number of output
channels. When I > O, the first O inputs are routed to the first O outputs,
and the remaining puts discarded. When O > I, the first I inputs are routed
to the first O outputs, and the remaining outputs are zeroed.
A simple example for splitting mono input to stereo output (instead of routing
the input to only the first output channel):
```
// this should be as large as the number of output channels:
SInt32 channelMap[2] = { 0, 0 };
AudioConverterSetProperty(theConverter, kAudioConverterChannelMap,
sizeof(channelMap), channelMap);
```
@constant kAudioConverterDecompressionMagicCookie
A void * pointing to memory set up by the caller. Required by some formats
in order to decompress the input data.
@constant kAudioConverterCompressionMagicCookie
A void * pointing to memory set up by the caller. Returned by the converter
so that it may be stored along with the output data. It can then be passed
back to the converter for decompression at a later time.
@constant kAudioConverterEncodeBitRate
A UInt32 containing the number of bits per second to aim for when encoding
data. Some decoders will also allow you to get this property to discover the bit rate.
@constant kAudioConverterEncodeAdjustableSampleRate
For encoders where the AudioConverter was created with an output sample rate
of zero, and the codec can do rate conversion on its input, this provides a
way to set the output sample rate. The property value is a Float64.
@constant kAudioConverterInputChannelLayout
The property value is an AudioChannelLayout.
@constant kAudioConverterOutputChannelLayout
The property value is an AudioChannelLayout.
@constant kAudioConverterApplicableEncodeBitRates
The property value is an array of AudioValueRange describing applicable bit
rates based on current settings.
@constant kAudioConverterAvailableEncodeBitRates
The property value is an array of AudioValueRange describing available bit
rates based on the input format. You can get all available bit rates from
the AudioFormat API.
@constant kAudioConverterApplicableEncodeSampleRates
The property value is an array of AudioValueRange describing applicable
sample rates based on current settings.
@constant kAudioConverterAvailableEncodeSampleRates
The property value is an array of AudioValueRange describing available
sample rates based on the input format. You can get all available sample
rates from the AudioFormat API.
@constant kAudioConverterAvailableEncodeChannelLayoutTags
The property value is an array of AudioChannelLayoutTags for the format and
number of channels specified in the input format going to the encoder.
@constant kAudioConverterCurrentOutputStreamDescription
Returns the current completely specified output AudioStreamBasicDescription.
For example when encoding to AAC, your original output stream description
will not have been completely filled out.
@constant kAudioConverterCurrentInputStreamDescription
Returns the current completely specified input AudioStreamBasicDescription.
@constant kAudioConverterPropertySettings
Returns the a CFArray of property settings for converters.
@constant kAudioConverterPropertyBitDepthHint
An SInt32 of the source bit depth to preserve. This is a hint to some
encoders like lossless about how many bits to preserve in the input. The
converter usually tries to preserve as many as possible, but a lossless
encoder will do poorly if more bits are supplied than are desired in the
output. The bit depth is expressed as a negative number if the source was floating point,
e.g. -32 for float, -64 for double.
@constant kAudioConverterPropertyFormatList
An array of AudioFormatListItem structs describing all the data formats produced by the
encoder end of the AudioConverter. If the ioPropertyDataSize parameter indicates that
outPropertyData is sizeof(AudioFormatListItem), then only the best format is returned.
This property may be used for example to discover all the data formats produced by the AAC_HE2
(AAC High Efficiency vers. 2) encoder.
*/
CF_ENUM(AudioConverterPropertyID)
{
kAudioConverterPropertyMinimumInputBufferSize = 'mibs',
kAudioConverterPropertyMinimumOutputBufferSize = 'mobs',
kAudioConverterPropertyMaximumInputPacketSize = 'xips',
kAudioConverterPropertyMaximumOutputPacketSize = 'xops',
kAudioConverterPropertyCalculateInputBufferSize = 'cibs',
kAudioConverterPropertyCalculateOutputBufferSize = 'cobs',
kAudioConverterPropertyInputCodecParameters = 'icdp',
kAudioConverterPropertyOutputCodecParameters = 'ocdp',
kAudioConverterSampleRateConverterComplexity = 'srca',
kAudioConverterSampleRateConverterQuality = 'srcq',
kAudioConverterSampleRateConverterInitialPhase = 'srcp',
kAudioConverterCodecQuality = 'cdqu',
kAudioConverterPrimeMethod = 'prmm',
kAudioConverterPrimeInfo = 'prim',
kAudioConverterChannelMap = 'chmp',
kAudioConverterDecompressionMagicCookie = 'dmgc',
kAudioConverterCompressionMagicCookie = 'cmgc',
kAudioConverterEncodeBitRate = 'brat',
kAudioConverterEncodeAdjustableSampleRate = 'ajsr',
kAudioConverterInputChannelLayout = 'icl ',
kAudioConverterOutputChannelLayout = 'ocl ',
kAudioConverterApplicableEncodeBitRates = 'aebr',
kAudioConverterAvailableEncodeBitRates = 'vebr',
kAudioConverterApplicableEncodeSampleRates = 'aesr',
kAudioConverterAvailableEncodeSampleRates = 'vesr',
kAudioConverterAvailableEncodeChannelLayoutTags = 'aecl',
kAudioConverterCurrentOutputStreamDescription = 'acod',
kAudioConverterCurrentInputStreamDescription = 'acid',
kAudioConverterPropertySettings = 'acps',
kAudioConverterPropertyBitDepthHint = 'acbd',
kAudioConverterPropertyFormatList = 'flst'
};
#if !TARGET_OS_IPHONE
//=============================================================================
//
//=============================================================================
/*!
@enum macOS AudioConverter Properties
@constant kAudioConverterPropertyDithering
A UInt32. Set to a value from the enum of dithering algorithms below.
Zero means no dithering and is the default. (macOS only.)
@constant kAudioConverterPropertyDitherBitDepth
A UInt32. Dither is applied at this bit depth. (macOS only.)
*/
CF_ENUM(AudioConverterPropertyID)
{
kAudioConverterPropertyDithering = 'dith',
kAudioConverterPropertyDitherBitDepth = 'dbit'
};
/*!
@enum Dithering algorithms
@abstract Constants to be used as the value for kAudioConverterPropertyDithering.
@constant kDitherAlgorithm_TPDF Dither signal is generated by a white noise source with a triangular probability density function
@constant kDitherAlgorithm_NoiseShaping Use a static, perceptually weighted noise shaped dither
*/
CF_ENUM(UInt32)
{
kDitherAlgorithm_TPDF = 1,
kDitherAlgorithm_NoiseShaping = 2
};
#endif
/*!
@enum Quality constants
@abstract Constants to be used with kAudioConverterSampleRateConverterQuality.
@constant kAudioConverterQuality_Max
maximum quality
@constant kAudioConverterQuality_High
high quality
@constant kAudioConverterQuality_Medium
medium quality
@constant kAudioConverterQuality_Low
low quality
@constant kAudioConverterQuality_Min
minimum quality
*/
CF_ENUM(UInt32)
{
kAudioConverterQuality_Max = 0x7F,
kAudioConverterQuality_High = 0x60,
kAudioConverterQuality_Medium = 0x40,
kAudioConverterQuality_Low = 0x20,
kAudioConverterQuality_Min = 0
};
/*!
@enum Sample Rate Converter Complexity
@constant kAudioConverterSampleRateConverterComplexity_Linear
@discussion Linear interpolation. lowest quality, cheapest.
InitialPhase and PrimeMethod properties are not operative with this mode.
@constant kAudioConverterSampleRateConverterComplexity_Normal
@discussion Normal quality sample rate conversion.
@constant kAudioConverterSampleRateConverterComplexity_Mastering
@discussion Mastering quality sample rate conversion. More expensive.
@constant kAudioConverterSampleRateConverterComplexity_MinimumPhase
@discussion Minimum phase impulse response. Stopband attenuation varies with quality setting.
The InitialPhase and PrimeMethod properties are not operative with this mode.
There are three levels of quality provided.
kAudioConverterQuality_Low (or Min) : noise floor to -96 dB
kAudioConverterQuality_Medium : noise floor to -144 dB
kAudioConverterQuality_High (or Max) : noise floor to -160 dB (this uses double precision internally)
Quality equivalences to the other complexity modes are very roughly as follows:
MinimumPhase Low is somewhat better than Normal Medium.
MinimumPhase Medium is similar to Normal Max.
MinimumPhase High is similar to Mastering Low.
In general, MinimumPhase performs better than Normal and Mastering for the equivalent qualities listed above.
MinimumPhase High is several times faster than Mastering Low.
*/
CF_ENUM(UInt32)
{
kAudioConverterSampleRateConverterComplexity_Linear = 'line', // linear interpolation
kAudioConverterSampleRateConverterComplexity_Normal = 'norm', // normal quality range, the default
kAudioConverterSampleRateConverterComplexity_Mastering = 'bats', // higher quality range, more expensive
kAudioConverterSampleRateConverterComplexity_MinimumPhase = 'minp' // minimum phase impulse response.
};
/*!
@enum Prime method constants
@abstract Constants to be used with kAudioConverterPrimeMethod.
@constant kConverterPrimeMethod_Pre
Primes with leading + trailing input frames.
@constant kConverterPrimeMethod_Normal
Only primes with trailing (zero latency). Leading frames are assumed to be
silence.
@constant kConverterPrimeMethod_None
Acts in "latency" mode. Both leading and trailing frames assumed to be
silence.
*/
CF_ENUM(UInt32)
{
kConverterPrimeMethod_Pre = 0,
kConverterPrimeMethod_Normal = 1,
kConverterPrimeMethod_None = 2
};
/*!
@struct AudioConverterPrimeInfo
@abstract Specifies priming information.
When using AudioConverterFillComplexBuffer() (either a single call or a series of calls), some
conversions, particularly involving sample-rate conversion, ideally require a certain
number of input frames previous to the normal start input frame and beyond the end of
the last expected input frame in order to yield high-quality results.
These are expressed in the leadingFrames and trailingFrames members of the structure.
The very first call to AudioConverterFillComplexBuffer(), or first call after
AudioConverterReset(), will request additional input frames beyond those normally
expected in the input proc callback to fulfill this first AudioConverterFillComplexBuffer()
request. The number of additional frames requested, depending on the prime method, will
be approximately:
Prime method | Additional frames
------------------------------|----------------------
kConverterPrimeMethod_Pre | leadingFrames + trailingFrames
kConverterPrimeMethod_Normal | trailingFrames
kConverterPrimeMethod_None | 0
Thus, in effect, the first input proc callback(s) may provide not only the leading
frames, but also may "read ahead" by an additional number of trailing frames depending
on the prime method.
kConverterPrimeMethod_None is useful in a real-time application processing live input,
in which case trailingFrames (relative to input sample rate) of through latency will be
seen at the beginning of the output of the AudioConverter. In other real-time
applications such as DAW systems, it may be possible to provide these initial extra
audio frames since they are stored on disk or in memory somewhere and
kConverterPrimeMethod_Pre may be preferable. The default method is
kConverterPrimeMethod_Normal, which requires no pre-seeking of the input stream and
generates no latency at the output.
@var leadingFrames
Specifies the number of leading (previous) input frames, relative to the normal/desired
start input frame, required by the converter to perform a high quality conversion. If
using kConverterPrimeMethod_Pre, the client should "pre-seek" the input stream provided
through the input proc by leadingFrames. If no frames are available previous to the
desired input start frame (because, for example, the desired start frame is at the very
beginning of available audio), then provide "leadingFrames" worth of initial zero frames
in the input proc. Do not "pre-seek" in the default case of
kConverterPrimeMethod_Normal or when using kConverterPrimeMethod_None.
@var trailingFrames
Specifies the number of trailing input frames (past the normal/expected end input frame)
required by the converter to perform a high quality conversion. The client should be
prepared to provide this number of additional input frames except when using
kConverterPrimeMethod_None. If no more frames of input are available in the input stream
(because, for example, the desired end frame is at the end of an audio file), then zero
(silent) trailing frames will be synthesized for the client.
*/
struct AudioConverterPrimeInfo {
UInt32 leadingFrames;
UInt32 trailingFrames;
};
typedef struct AudioConverterPrimeInfo AudioConverterPrimeInfo;
//=============================================================================
// Errors
//=============================================================================
/*!
@enum AudioConverter errors
*/
CF_ENUM(OSStatus)
{
kAudioConverterErr_FormatNotSupported = 'fmt?',
kAudioConverterErr_OperationNotSupported = 0x6F703F3F, // 'op??', integer used because of trigraph
kAudioConverterErr_PropertyNotSupported = 'prop',
kAudioConverterErr_InvalidInputSize = 'insz',
kAudioConverterErr_InvalidOutputSize = 'otsz',
// e.g. byte size is not a multiple of the frame size
kAudioConverterErr_UnspecifiedError = 'what',
kAudioConverterErr_BadPropertySizeError = '!siz',
kAudioConverterErr_RequiresPacketDescriptionsError = '!pkd',
kAudioConverterErr_InputSampleRateOutOfRange = '!isr',
kAudioConverterErr_OutputSampleRateOutOfRange = '!osr'
};
#if TARGET_OS_IPHONE
/*!
@enum AudioConverter errors (iPhone only)
@abstract iPhone-specific OSStatus results for AudioConverter
@constant kAudioConverterErr_HardwareInUse
Returned from AudioConverterFillComplexBuffer if the underlying hardware codec has
become unavailable, probably due to an interruption. In this case, your application
must stop calling AudioConverterFillComplexBuffer. If the converter can resume from an
interruption (see kAudioConverterPropertyCanResumeFromInterruption), you must
wait for an EndInterruption notification from AudioSession, and call AudioSessionSetActive(true)
before resuming.
@constant kAudioConverterErr_NoHardwarePermission
Returned from AudioConverterNew if the new converter would use a hardware codec
which the application does not have permission to use.
*/
CF_ENUM(OSStatus)
{
kAudioConverterErr_HardwareInUse = 'hwiu',
kAudioConverterErr_NoHardwarePermission = 'perm'
};
#endif
//=============================================================================
// Routines
//=============================================================================
//-----------------------------------------------------------------------------
/*!
@function AudioConverterNew
@abstract Create a new AudioConverter.
@param inSourceFormat
The format of the source audio to be converted.
@param inDestinationFormat
The destination format to which the audio is to be converted.
@param outAudioConverter
On successful return, points to a new AudioConverter instance.
@result An OSStatus result code.
For a pair of linear PCM formats, the following conversions
are supported:
<ul>
<li>addition and removal of channels, when the stream descriptions'
mChannelsPerFrame does not match. Channels may also be reordered and removed
using the kAudioConverterChannelMap property.</li>
<li>sample rate conversion</li>
<li>interleaving/deinterleaving, when the stream descriptions' (mFormatFlags &
kAudioFormatFlagIsNonInterleaved) does not match.</li>
<li>conversion between any pair of the following formats:</li>
<ul>
<li>8 bit integer, signed or unsigned</li>
<li>16, 24, or 32-bit integer, big- or little-endian. Other integral
bit depths, if high-aligned and non-packed, are also supported</li>
<li>32 and 64-bit float, big- or little-endian.</li>
</ul>
</ul>
Also, encoding and decoding between linear PCM and compressed formats is
supported. Functions in AudioToolbox/AudioFormat.h return information about the
supported formats. When using a codec, you can use any supported PCM format (as
above); the converter will perform any necessary additional conversion between
your PCM format and the one created or consumed by the codec.
*/
extern OSStatus
AudioConverterNew( const AudioStreamBasicDescription * inSourceFormat,
const AudioStreamBasicDescription * inDestinationFormat,
AudioConverterRef __nullable * __nonnull outAudioConverter) API_AVAILABLE(macos(10.1), ios(2.0), watchos(2.0), tvos(9.0));
//-----------------------------------------------------------------------------
/*!
@function AudioConverterNewSpecific
@abstract Create a new AudioConverter using specific codecs.
@param inSourceFormat
The format of the source audio to be converted.
@param inDestinationFormat
The destination format to which the audio is to be converted.
@param inNumberClassDescriptions
The number of class descriptions.
@param inClassDescriptions
AudioClassDescriptions specifiying the codec to instantiate.
@param outAudioConverter
On successful return, points to a new AudioConverter instance.
@result An OSStatus result code.
This function is identical to AudioConverterNew(), except that the client may
explicitly choose which codec to instantiate if there is more than one choice.
*/
extern OSStatus
AudioConverterNewSpecific( const AudioStreamBasicDescription * inSourceFormat,
const AudioStreamBasicDescription * inDestinationFormat,
UInt32 inNumberClassDescriptions,
const AudioClassDescription * inClassDescriptions,
AudioConverterRef __nullable * __nonnull outAudioConverter)
API_AVAILABLE(macos(10.4), ios(2.0), watchos(2.0), tvos(9.0));
//-----------------------------------------------------------------------------
/*!
@function AudioConverterDispose
@abstract Destroy an AudioConverter.
@param inAudioConverter
The AudioConverter to dispose.
@result An OSStatus result code.
*/
extern OSStatus
AudioConverterDispose( AudioConverterRef inAudioConverter) API_AVAILABLE(macos(10.1), ios(2.0), watchos(2.0), tvos(9.0));
//-----------------------------------------------------------------------------
/*!
@function AudioConverterReset
@abstract Reset an AudioConverter
@param inAudioConverter
The AudioConverter to reset.
@result An OSStatus result code.
Should be called whenever there is a discontinuity in the source audio stream
being provided to the converter. This will flush any internal buffers in the
converter.
*/
extern OSStatus
AudioConverterReset( AudioConverterRef inAudioConverter) API_AVAILABLE(macos(10.1), ios(2.0), watchos(2.0), tvos(9.0));
//-----------------------------------------------------------------------------
/*!
@function AudioConverterGetPropertyInfo
@abstract Returns information about an AudioConverter property.
@param inAudioConverter
The AudioConverter to query.
@param inPropertyID
The property to query.
@param outSize
If non-null, on exit, the maximum size of the property value in bytes.
@param outWritable
If non-null, on exit, indicates whether the property value is writable.
@result An OSStatus result code.
*/
extern OSStatus
AudioConverterGetPropertyInfo( AudioConverterRef inAudioConverter,
AudioConverterPropertyID inPropertyID,
UInt32 * __nullable outSize,
Boolean * __nullable outWritable) API_AVAILABLE(macos(10.1), ios(2.0), watchos(2.0), tvos(9.0));
//-----------------------------------------------------------------------------
/*!
@function AudioConverterGetProperty
@abstract Returns an AudioConverter property value.
@param inAudioConverter
The AudioConverter to query.
@param inPropertyID
The property to fetch.
@param ioPropertyDataSize
On entry, the size of the memory pointed to by outPropertyData. On
successful exit, the size of the property value.
@param outPropertyData
On exit, the property value.
@result An OSStatus result code.
*/
extern OSStatus
AudioConverterGetProperty( AudioConverterRef inAudioConverter,
AudioConverterPropertyID inPropertyID,
UInt32 * ioPropertyDataSize,
void * outPropertyData) API_AVAILABLE(macos(10.1), ios(2.0), watchos(2.0), tvos(9.0));
//-----------------------------------------------------------------------------
/*!
@function AudioConverterSetProperty
@abstract Sets an AudioConverter property value.
@param inAudioConverter
The AudioConverter to modify.
@param inPropertyID
The property to set.
@param inPropertyDataSize
The size in bytes of the property value.
@param inPropertyData
Points to the new property value.
@result An OSStatus result code.
*/
extern OSStatus
AudioConverterSetProperty( AudioConverterRef inAudioConverter,
AudioConverterPropertyID inPropertyID,
UInt32 inPropertyDataSize,
const void * inPropertyData) API_AVAILABLE(macos(10.1), ios(2.0), watchos(2.0), tvos(9.0));
//-----------------------------------------------------------------------------
/*!
@function AudioConverterConvertBuffer
@abstract Converts data from an input buffer to an output buffer.
@param inAudioConverter
The AudioConverter to use.
@param inInputDataSize
The size of the buffer inInputData.
@param inInputData
The input audio data buffer.
@param ioOutputDataSize
On entry, the size of the buffer outOutputData. On exit, the number of bytes
written to outOutputData.
@param outOutputData
The output data buffer.
@result
Produces a buffer of output data from an AudioConverter, using the supplied
input buffer.
WARNING: this function will fail for any conversion where there is a
variable relationship between the input and output data buffer sizes. This
includes sample rate conversions and most compressed formats. In these cases,
use AudioConverterFillComplexBuffer. Generally this function is only appropriate for
PCM-to-PCM conversions where there is no sample rate conversion.
*/
extern OSStatus
AudioConverterConvertBuffer( AudioConverterRef inAudioConverter,
UInt32 inInputDataSize,
const void * inInputData,
UInt32 * ioOutputDataSize,
void * outOutputData) API_AVAILABLE(macos(10.1), ios(2.0), watchos(2.0), tvos(9.0));
//-----------------------------------------------------------------------------
/*!
@typedef AudioConverterComplexInputDataProc
@abstract Callback function for supplying input data to AudioConverterFillComplexBuffer.
@param inAudioConverter
The AudioConverter requesting input.
@param ioNumberDataPackets
On entry, the minimum number of packets of input audio data the converter
would like in order to fulfill its current FillBuffer request. On exit, the
number of packets of audio data actually being provided for input, or 0 if
there is no more input.
@param ioData
On exit, the members of ioData should be set to point to the audio data
being provided for input.
@param outDataPacketDescription
If non-null, on exit, the callback is expected to fill this in with
an AudioStreamPacketDescription for each packet of input data being provided.
@param inUserData
The inInputDataProcUserData parameter passed to AudioConverterFillComplexBuffer().
@result An OSStatus result code.
This callback function supplies input to AudioConverterFillComplexBuffer.
The AudioConverter requests a minimum number of packets (*ioNumberDataPackets).
The callback may return one or more packets. If this is less than the minimum,
the callback will simply be called again in the near future.
The callback manipulates the members of ioData to point to one or more buffers
of audio data (multiple buffers are used with non-interleaved PCM data). The
callback is responsible for not freeing or altering this buffer until it is
called again.
If the callback returns an error, it must return zero packets of data.
AudioConverterFillComplexBuffer will stop producing output and return whatever
output has already been produced to its caller, along with the error code. This
mechanism can be used when an input proc has temporarily run out of data, but
has not yet reached end of stream.
*/
typedef OSStatus
(*AudioConverterComplexInputDataProc)( AudioConverterRef inAudioConverter,
UInt32 * ioNumberDataPackets,
AudioBufferList * ioData,
AudioStreamPacketDescription * __nullable * __nullable outDataPacketDescription,
void * __nullable inUserData);
//-----------------------------------------------------------------------------
/*!
@function AudioConverterFillComplexBuffer
@abstract Converts data supplied by an input callback function, supporting non-interleaved
and packetized formats.
@param inAudioConverter
The AudioConverter to use.
@param inInputDataProc
A callback function which supplies the input data.
@param inInputDataProcUserData
A value for the use of the callback function.
@param ioOutputDataPacketSize
On entry, the capacity of outOutputData expressed in packets in the
converter's output format. On exit, the number of packets of converted
data that were written to outOutputData.
@param outOutputData
The converted output data is written to this buffer. On entry, the buffers'
mDataByteSize fields (which must all be the same) reflect buffer capacity.
On exit, mDataByteSize is set to the number of bytes written.
@param outPacketDescription
If non-null, and the converter's output uses packet descriptions, then
packet descriptions are written to this array. It must point to a memory
block capable of holding *ioOutputDataPacketSize packet descriptions.
(See AudioFormat.h for ways to determine whether an audio format
uses packet descriptions).
@result An OSStatus result code.
Produces a buffer list of output data from an AudioConverter. The supplied input
callback function is called whenever necessary.
*/
extern OSStatus
AudioConverterFillComplexBuffer( AudioConverterRef inAudioConverter,
AudioConverterComplexInputDataProc inInputDataProc,
void * __nullable inInputDataProcUserData,
UInt32 * ioOutputDataPacketSize,
AudioBufferList * outOutputData,
AudioStreamPacketDescription * __nullable outPacketDescription)
API_AVAILABLE(macos(10.2), ios(2.0), watchos(2.0), tvos(9.0));
//-----------------------------------------------------------------------------
/*!
@function AudioConverterConvertComplexBuffer
@abstract Converts PCM data from an input buffer list to an output buffer list.
@param inAudioConverter
The AudioConverter to use.
@param inNumberPCMFrames
The number of PCM frames to convert.
@param inInputData
The source audio buffer list.
@param outOutputData
The converted output data is written to this buffer list.
@result An OSStatus result code.
@warning This function will fail for any conversion where there is a
variable relationship between the input and output data buffer sizes. This
includes sample rate conversions and most compressed formats. In these cases,
use AudioConverterFillComplexBuffer. Generally this function is only appropriate for
PCM-to-PCM conversions where there is no sample rate conversion.
*/
extern OSStatus
AudioConverterConvertComplexBuffer( AudioConverterRef inAudioConverter,
UInt32 inNumberPCMFrames,
const AudioBufferList * inInputData,
AudioBufferList * outOutputData)
API_AVAILABLE(macos(10.7), ios(5.0), watchos(2.0), tvos(9.0));
// =================================================================================================
// DEPRECATED
// =================================================================================================
/*
Deprecated properties:
@constant kAudioConverterPropertyMaximumInputBufferSize
DEPRECATED. The AudioConverter input proc may be passed any number of packets of data.
If fewer are packets are returned than required, then the input proc will be called again.
If more packets are passed than required, they will remain in the client's buffer and be
consumed as needed.
@constant kAudioConverterSampleRateConverterAlgorithm
DEPRECATED: please use kAudioConverterSampleRateConverterComplexity instead
*/
CF_ENUM(AudioConverterPropertyID)
{
kAudioConverterPropertyMaximumInputBufferSize = 'xibs',
kAudioConverterSampleRateConverterAlgorithm = 'srci',
};
#if TARGET_OS_IPHONE
/*!
@enum AudioConverterPropertyID (iOS only)
@abstract iOS-specific properties of an AudioConverter, accessible via AudioConverterGetProperty()
and AudioConverterSetProperty().
@constant kAudioConverterPropertyCanResumeFromInterruption
A read-only UInt32 signifying whether the underlying codec supports resumption following
an interruption. If the property is unimplemented (i.e. AudioConverterGetProperty
returns an error), then the codec is not a hardware codec. If the property's value
is 1, then the codec can resume work following an interruption. If the property's
value is 0, then interruptions destroy the codec's state.
DEPRECATED: Hardware codecs are no longer supported.
*/
CF_ENUM(AudioConverterPropertyID)
{
kAudioConverterPropertyCanResumeFromInterruption = 'crfi'
};
#endif
//-----------------------------------------------------------------------------
/*!
@typedef AudioConverterInputDataProc
@abstract Callback function for supplying input data to AudioConverterFillBuffer.
@param inAudioConverter
The AudioConverter requesting input.
@param ioDataSize
On entry, the minimum number of bytes of audio data the converter
would like in order to fulfill its current FillBuffer request.
On exit, the number of bytes of audio data actually being provided
for input, or 0 if there is no more input.
@param outData
On exit, *outData should point to the audio data being provided
for input.
@param inUserData
The inInputDataProcUserData parameter passed to AudioConverterFillBuffer().
@result An OSStatus result code.
This callback function supplies input to AudioConverterFillBuffer.
The AudioConverter requests a minimum amount of data (*ioDataSize). The callback
may return any amount of data. If it is less than than the minimum, the callback
will simply be called again in the near future.
The callback supplies a pointer to a buffer of audio data. The callback is
responsible for not freeing or altering this buffer until it is called again.
If the callback returns an error, it must return zero bytes of data.
AudioConverterFillBuffer will stop producing output and return whatever output
has already been produced to its caller, along with the error code. This
mechanism can be used when an input proc has temporarily run out of data, but
has not yet reached end of stream.
@deprecated This API is now deprecated, use AudioConverterFillComplexBuffer instead.
*/
typedef OSStatus
(*AudioConverterInputDataProc)( AudioConverterRef inAudioConverter,
UInt32 * ioDataSize,
void * __nonnull * __nonnull outData,
void * __nullable inUserData);
//-----------------------------------------------------------------------------
/*!
@function AudioConverterFillBuffer
@abstract Converts data supplied by an input callback function.
@param inAudioConverter
The AudioConverter to use.
@param inInputDataProc
A callback function which supplies the input data.
@param inInputDataProcUserData
A value for the use of the callback function.
@param ioOutputDataSize
On entry, the size of the buffer pointed to by outOutputData.
On exit, the number of bytes written to outOutputData
@param outOutputData
The buffer into which the converted data is written.
@result An OSStatus result code.
Produces a buffer of output data from an AudioConverter. The supplied input
callback function is called whenever necessary.
@deprecated This API is now deprecated, use AudioConverterFillComplexBuffer instead.
*/
#if !TARGET_OS_IPHONE
extern OSStatus
AudioConverterFillBuffer( AudioConverterRef inAudioConverter,
AudioConverterInputDataProc inInputDataProc,
void * __nullable inInputDataProcUserData,
UInt32 * ioOutputDataSize,
void * outOutputData)
API_DEPRECATED("no longer supported", macos(10.1, 10.5)) API_UNAVAILABLE(ios, watchos, tvos);
#endif // !TARGET_OS_IPHONE
#if defined(__cplusplus)
}
#endif
CF_ASSUME_NONNULL_END
#endif // AudioToolbox_AudioConverter_h
#else
#include <AudioToolboxCore/AudioConverter.h>
#endif

View File

@@ -0,0 +1,994 @@
#if (defined(__USE_PUBLIC_HEADERS__) && __USE_PUBLIC_HEADERS__) || (defined(USE_AUDIOTOOLBOX_PUBLIC_HEADERS) && USE_AUDIOTOOLBOX_PUBLIC_HEADERS) || !__has_include(<AudioToolboxCore/AudioFileComponent.h>)
/*!
@file AudioFileComponent.h
@framework AudioToolbox.framework
@copyright (c) 2004-2015 by Apple, Inc., all rights reserved.
@abstract Interfaces for components which implement knowledge of audio file formats.
@discussion
Audio file components are not for the use of clients. Rather, they are called by the
implementation of the AudioFile API to implement the various semantics of that API.
Most of these calls match a call in the AudioFile API which calls through to the component.
A component may be used in two ways, either associated with a file or not. If a component is
not associated with a file, it may be used to answer questions about the file type in
general and whether some data is recognized by that file type. A component is associated
with a file by calling one of the AudioFile Create, Open or Initialize calls. If a component
is associated with a file, then it can also be asked to perform any of the calls that
implement the AudioFile API.
*/
#ifndef AudioToolbox_AudioFileComponent_h
#define AudioToolbox_AudioFileComponent_h
//==================================================================================================
// Includes
//==================================================================================================
#include <AudioToolbox/AudioComponent.h>
#include <AudioToolbox/AudioFile.h>
CF_ASSUME_NONNULL_BEGIN
#if defined(__cplusplus)
extern "C"
{
#endif
/*!
@typedef AudioFileComponent
@abstract represents an instance of an AudioFileComponent.
*/
typedef AudioComponentInstance AudioFileComponent;
/*!
@typedef AudioFileComponentPropertyID
@abstract a four char code for a property ID.
*/
typedef UInt32 AudioFileComponentPropertyID;
/*!
@function AudioFileComponentCreateURL
@abstract creates a new (or initialises an existing) audio file specified by the URL.
@discussion creates a new (or initialises an existing) audio file specified by the URL.
@param inComponent an AudioFileComponent
@param inFileRef an CFURLRef fully specifying the path of the file to create/initialise
@param inFormat an AudioStreamBasicDescription describing the data format that will be
added to the audio file.
@param inFlags relevant flags for creating/opening the file.
if kAudioFileFlags_EraseFile is set, it will erase an existing file
if not set, then the Create call will fail if the URL is an existing file
@result returns noErr if successful.
*/
extern OSStatus
AudioFileComponentCreateURL (
AudioFileComponent inComponent,
CFURLRef inFileRef,
const AudioStreamBasicDescription *inFormat,
UInt32 inFlags) API_AVAILABLE(macos(10.5)) API_UNAVAILABLE(ios, watchos, tvos);
/*!
@function AudioFileComponentOpenURL
@abstract Open an existing audio file.
@discussion Open an existing audio file for reading or reading and writing.
@param inComponent an AudioFileComponent.
@param inFileRef the CFURLRef of an existing audio file.
@param inPermissions use the permission constants.
@param inFileDescriptor an open file descriptor.
@result returns noErr if successful.
*/
extern OSStatus
AudioFileComponentOpenURL (
AudioFileComponent inComponent,
CFURLRef inFileRef,
SInt8 inPermissions,
int inFileDescriptor) API_AVAILABLE(macos(10.5)) API_UNAVAILABLE(ios, watchos, tvos);
/*!
@function AudioFileComponentOpenWithCallbacks
@abstract implements AudioFileOpenWithCallbacks
@param inComponent an AudioFileComponent
@param inClientData a constant that will be passed to your callbacks.
@param inReadFunc a function that will be called when AudioFile needs to read data.
@param inWriteFunc a function that will be called when AudioFile needs to write data.
@param inGetSizeFunc a function that will be called when AudioFile needs to know the file size.
@param inSetSizeFunc a function that will be called when AudioFile needs to set the file size.
@result returns noErr if successful.
*/
extern OSStatus
AudioFileComponentOpenWithCallbacks(
AudioFileComponent inComponent,
void *inClientData,
AudioFile_ReadProc inReadFunc,
AudioFile_WriteProc inWriteFunc,
AudioFile_GetSizeProc inGetSizeFunc,
AudioFile_SetSizeProc inSetSizeFunc) API_AVAILABLE(macos(10.4)) API_UNAVAILABLE(ios, watchos, tvos);
/*!
@function AudioFileComponentInitializeWithCallbacks
@abstract implements AudioFileInitializeWithCallbacks
@param inComponent an AudioFileComponent
@param inClientData a constant that will be passed to your callbacks.
@param inReadFunc a function that will be called when AudioFile needs to read data.
@param inWriteFunc a function that will be called when AudioFile needs to write data.
@param inGetSizeFunc a function that will be called when AudioFile needs to know the file size.
@param inSetSizeFunc a function that will be called when AudioFile needs to set the file size.
@param inFileType an AudioFileTypeID indicating the type of audio file to which to initialize the file.
@param inFormat an AudioStreamBasicDescription describing the data format that will be
added to the audio file.
@param inFlags relevant flags for creating/opening the file. Currently zero.
@result returns noErr if successful.
*/
extern OSStatus
AudioFileComponentInitializeWithCallbacks(
AudioFileComponent inComponent,
void *inClientData,
AudioFile_ReadProc inReadFunc,
AudioFile_WriteProc inWriteFunc,
AudioFile_GetSizeProc inGetSizeFunc,
AudioFile_SetSizeProc inSetSizeFunc,
UInt32 inFileType,
const AudioStreamBasicDescription *inFormat,
UInt32 inFlags) API_AVAILABLE(macos(10.4)) API_UNAVAILABLE(ios, watchos, tvos);
/*!
@function AudioFileComponentCloseFile
@abstract implements AudioFileClose.
@param inComponent an AudioFileComponent
@result returns noErr if successful.
*/
extern OSStatus
AudioFileComponentCloseFile(
AudioFileComponent inComponent) API_AVAILABLE(macos(10.4)) API_UNAVAILABLE(ios, watchos, tvos);
/*!
@function AudioFileComponentOptimize
@abstract implements AudioFileOptimize.
@param inComponent an AudioFileComponent
@result returns noErr if successful.
*/
extern OSStatus
AudioFileComponentOptimize(
AudioFileComponent inComponent) API_AVAILABLE(macos(10.4)) API_UNAVAILABLE(ios, watchos, tvos);
/*!
@function AudioFileComponentReadBytes
@abstract implements AudioFileReadBytes.
@discussion Returns kAudioFileEndOfFileError when read encounters end of file.
@param inComponent an AudioFileComponent
@param inUseCache true if it is desired to cache the data upon read, else false
@param inStartingByte the byte offset of the audio data desired to be returned
@param ioNumBytes on input, the number of bytes to read, on output, the number of
bytes actually read.
@param outBuffer outBuffer should be a void * to user allocated memory large enough for the requested bytes.
@result returns noErr if successful.
*/
extern OSStatus
AudioFileComponentReadBytes(
AudioFileComponent inComponent,
Boolean inUseCache,
SInt64 inStartingByte,
UInt32 *ioNumBytes,
void *outBuffer) API_AVAILABLE(macos(10.4)) API_UNAVAILABLE(ios, watchos, tvos);
/*!
@function AudioFileComponentWriteBytes
@abstract implements AudioFileWriteBytes.
@param inComponent an AudioFileComponent
@param inUseCache true if it is desired to cache the data upon write, else false
@param inStartingByte the byte offset where the audio data should be written
@param ioNumBytes on input, the number of bytes to write, on output, the number of
bytes actually written.
@param inBuffer inBuffer should be a void * containing the bytes to be written
@result returns noErr if successful.
*/
extern OSStatus
AudioFileComponentWriteBytes(
AudioFileComponent inComponent,
Boolean inUseCache,
SInt64 inStartingByte,
UInt32 *ioNumBytes,
const void *inBuffer) API_AVAILABLE(macos(10.4)) API_UNAVAILABLE(ios, watchos, tvos);
/*!
@function AudioFileComponentReadPackets
@abstract implements AudioFileReadPackets.
@discussion For all uncompressed formats, packets == frames.
ioNumPackets less than requested indicates end of file.
@param inComponent an AudioFileComponent
@param inUseCache true if it is desired to cache the data upon read, else false
@param outNumBytes on output, the number of bytes actually returned
@param outPacketDescriptions on output, an array of packet descriptions describing
the packets being returned. NULL may be passed for this
parameter. Nothing will be returned for linear pcm data.
@param inStartingPacket the packet index of the first packet desired to be returned
@param ioNumPackets on input, the number of packets to read, on output, the number of
packets actually read.
@param outBuffer outBuffer should be a pointer to user allocated memory of size:
number of packets requested times file's maximum (or upper bound on)
packet size.
@result returns noErr if successful.
*/
extern OSStatus
AudioFileComponentReadPackets(
AudioFileComponent inComponent,
Boolean inUseCache,
UInt32 *outNumBytes,
AudioStreamPacketDescription * __nullable outPacketDescriptions,
SInt64 inStartingPacket,
UInt32 *ioNumPackets,
void *outBuffer) API_AVAILABLE(macos(10.4)) API_UNAVAILABLE(ios, watchos, tvos);
/*!
@function AudioFileComponentReadPacketData
@abstract implements AudioFileReadPacketData.
@discussion For all uncompressed formats, packets == frames.
If the byte size of the number packets requested is
less than the buffer size, ioNumBytes will be reduced.
If the buffer is too small for the number of packets
requested, ioNumPackets and ioNumBytes will be reduced
to the number of packets that can be accommodated and their byte size.
Returns kAudioFileEndOfFileError when read encounters end of file.
@param inComponent an AudioFileComponent
@param inUseCache true if it is desired to cache the data upon read, else false
@param ioNumBytes on input the size of outBuffer in bytes.
on output, the number of bytes actually returned.
@param outPacketDescriptions on output, an array of packet descriptions describing
the packets being returned. NULL may be passed for this
parameter. Nothing will be returned for linear pcm data.
@param inStartingPacket the packet index of the first packet desired to be returned
@param ioNumPackets on input, the number of packets to read, on output, the number of
packets actually read.
@param outBuffer outBuffer should be a pointer to user allocated memory.
@result returns noErr if successful.
*/
extern OSStatus
AudioFileComponentReadPacketData(
AudioFileComponent inComponent,
Boolean inUseCache,
UInt32 *ioNumBytes,
AudioStreamPacketDescription * __nullable outPacketDescriptions,
SInt64 inStartingPacket,
UInt32 *ioNumPackets,
void *outBuffer) API_AVAILABLE(macos(10.4)) API_UNAVAILABLE(ios, watchos, tvos);
/*!
@function AudioFileComponentWritePackets
@abstract implements AudioFileWritePackets.
@discussion For all uncompressed formats, packets == frames.
@param inComponent an AudioFileComponent
@param inUseCache true if it is desired to cache the data upon write, else false
@param inNumBytes the number of bytes being provided for write
@param inPacketDescriptions an array of packet descriptions describing the packets being
provided. Not all formats require packet descriptions to be
provided. NULL may be passed if no descriptions are required.
@param inStartingPacket the packet index of where the first packet provided should be placed.
@param ioNumPackets on input, the number of packets to write, on output, the number of
packets actually written.
@param inBuffer a void * to user allocated memory containing the packets to write.
@result returns noErr if successful.
*/
extern OSStatus
AudioFileComponentWritePackets(
AudioFileComponent inComponent,
Boolean inUseCache,
UInt32 inNumBytes,
const AudioStreamPacketDescription * __nullable inPacketDescriptions,
SInt64 inStartingPacket,
UInt32 *ioNumPackets,
const void *inBuffer) API_AVAILABLE(macos(10.4)) API_UNAVAILABLE(ios, watchos, tvos);
/*!
@function AudioFileComponentGetPropertyInfo
@abstract implements AudioFileGetPropertyInfo.
@param inComponent an AudioFileComponent
@param inPropertyID an AudioFileProperty constant.
@param outPropertySize the size in bytes of the current value of the property. In order to get the property value,
you will need a buffer of this size.
@param outWritable will be set to 1 if writable, or 0 if read only.
@result returns noErr if successful.
*/
extern OSStatus
AudioFileComponentGetPropertyInfo(
AudioFileComponent inComponent,
AudioFileComponentPropertyID inPropertyID,
UInt32 * __nullable outPropertySize,
UInt32 * __nullable outWritable) API_AVAILABLE(macos(10.4)) API_UNAVAILABLE(ios, watchos, tvos);
/*!
@function AudioFileComponentGetProperty
@abstract implements AudioFileGetProperty.
@param inComponent an AudioFileComponent
@param inPropertyID an AudioFileProperty constant.
@param ioPropertyDataSize on input the size of the outPropertyData buffer. On output the number of bytes written to the buffer.
@param outPropertyData the buffer in which to write the property data.
@result returns noErr if successful.
*/
extern OSStatus
AudioFileComponentGetProperty(
AudioFileComponent inComponent,
AudioFileComponentPropertyID inPropertyID,
UInt32 *ioPropertyDataSize,
void *outPropertyData) API_AVAILABLE(macos(10.4)) API_UNAVAILABLE(ios, watchos, tvos);
/*!
@function AudioFileComponentSetProperty
@abstract implements AudioFileSetProperty.
@param inComponent an AudioFileComponent
@param inPropertyID an AudioFileProperty constant.
@param inPropertyDataSize the size of the property data.
@param inPropertyData the buffer containing the property data.
@result returns noErr if successful.
*/
extern OSStatus
AudioFileComponentSetProperty(
AudioFileComponent inComponent,
AudioFileComponentPropertyID inPropertyID,
UInt32 inPropertyDataSize,
const void *inPropertyData) API_AVAILABLE(macos(10.4)) API_UNAVAILABLE(ios, watchos, tvos);
/*!
@function AudioFileComponentCountUserData
@abstract implements AudioFileCountUserData
@discussion "User Data" refers to chunks in AIFF, CAF and WAVE files, or resources
in Sound Designer II files, and possibly other things in other files.
For simplicity, referred to below as "chunks".
@param inComponent an AudioFileComponent
@param inUserDataID the four char code of the chunk.
@param outNumberItems on output, if successful, number of chunks of this type in the file.
@result returns noErr if successful.
*/
extern OSStatus
AudioFileComponentCountUserData(
AudioFileComponent inComponent,
UInt32 inUserDataID,
UInt32 *outNumberItems) API_AVAILABLE(macos(10.4)) API_UNAVAILABLE(ios, watchos, tvos);
/*!
@function AudioFileComponentGetUserDataSize
@abstract implements AudioFileGetUserDataSize
@param inComponent an AudioFileComponent
@param inUserDataID the four char code of the chunk.
@param inIndex an index specifying which chunk if there are more than one.
@param outUserDataSize on output, if successful, the size of the user data chunk.
@result returns noErr if successful.
*/
extern OSStatus
AudioFileComponentGetUserDataSize(
AudioFileComponent inComponent,
UInt32 inUserDataID,
UInt32 inIndex,
UInt32 *outUserDataSize) API_AVAILABLE(macos(10.4)) API_UNAVAILABLE(ios, watchos, tvos);
/*!
@function AudioFileGetUserData
@abstract implements AudioFileGetUserData.
@param inComponent an AudioFileComponent
@param inUserDataID the four char code of the chunk.
@param inIndex an index specifying which chunk if there are more than one.
@param ioUserDataSize the size of the buffer on input, size of bytes copied to buffer on output
@param outUserData a pointer to a buffer in which to copy the chunk data.
@result returns noErr if successful.
*/
extern OSStatus
AudioFileComponentGetUserData(
AudioFileComponent inComponent,
UInt32 inUserDataID,
UInt32 inIndex,
UInt32 *ioUserDataSize,
void *outUserData) API_AVAILABLE(macos(10.4)) API_UNAVAILABLE(ios, watchos, tvos);
/*!
@function AudioFileComponentSetUserData
@abstract implements AudioFileSetUserData.
@param inComponent an AudioFileComponent
@param inUserDataID the four char code of the chunk.
@param inIndex an index specifying which chunk if there are more than one.
@param inUserDataSize on input the size of the data to copy, on output, size of bytes copied from the buffer
@param inUserData a pointer to a buffer from which to copy the chunk data
(only the contents of the chunk, not including the chunk header).
@result returns noErr if successful.
*/
extern OSStatus
AudioFileComponentSetUserData(
AudioFileComponent inComponent,
UInt32 inUserDataID,
UInt32 inIndex,
UInt32 inUserDataSize,
const void *inUserData) API_AVAILABLE(macos(10.4)) API_UNAVAILABLE(ios, watchos, tvos);
/*!
@function AudioFileComponentRemoveUserData
@abstract implements AudioFileRemoveUserData.
@param inComponent an AudioFileComponent
@param inUserDataID the four char code of the chunk.
@param inIndex an index specifying which chunk if there are more than one.
@result returns noErr if successful.
*/
extern OSStatus
AudioFileComponentRemoveUserData(
AudioFileComponent inComponent,
UInt32 inUserDataID,
UInt32 inIndex) API_AVAILABLE(macos(10.5)) API_UNAVAILABLE(ios, watchos, tvos);
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
// The following calls are not made on AudioFile instances.
// These calls are used to determine the audio file type of some data.
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
/*!
@function AudioFileComponentExtensionIsThisFormat
@abstract used by the AudioFile API to determine if this component is appropriate for handling a file.
@param inComponent an AudioFileComponent
@param inExtension a CFString containing a file name extension.
@param outResult on output, is set to 1 if the extension is recognized by this component, 0 if not.
@result returns noErr if successful.
*/
extern OSStatus
AudioFileComponentExtensionIsThisFormat(
AudioFileComponent inComponent,
CFStringRef inExtension,
UInt32 *outResult) API_AVAILABLE(macos(10.4)) API_UNAVAILABLE(ios, watchos, tvos);
/*!
@function AudioFileComponentFileDataIsThisFormat
@abstract used by the AudioFile API to determine if this component is appropriate for handling a file.
@param inComponent an AudioFileComponent
@param inDataByteSize the size of inData in bytes.
@param inData a pointer to a buffer of audio file data.
@param outResult on output, is set to 1 if the file is recognized by this component, 0 if not.
@result returns noErr if successful.
*/
extern OSStatus
AudioFileComponentFileDataIsThisFormat(
AudioFileComponent inComponent,
UInt32 inDataByteSize,
const void* inData,
UInt32 *outResult) API_AVAILABLE(macos(10.4)) API_UNAVAILABLE(ios, watchos, tvos);
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
// The following two calls are deprecated.
// Please implement AudioFileComponentFileDataIsThisFormat instead.
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
/*!
@function AudioFileComponentFileIsThisFormat
@abstract deprecated. use AudioFileComponentFileDataIsThisFormat instead.
@param inComponent an AudioFileComponent
@param inFileRefNum a refNum of a file.
@param outResult on output, is set to 1 if the file is recognized by this component, 0 if not.
@result returns noErr if successful.
*/
extern OSStatus
AudioFileComponentFileIsThisFormat(
AudioFileComponent inComponent,
SInt16 inFileRefNum,
UInt32 *outResult) API_DEPRECATED("no longer supported", macos(10.4, 10.5)) API_UNAVAILABLE(ios, watchos, tvos);
/*!
@function AudioFileComponentDataIsThisFormat
@abstract deprecated. use AudioFileComponentFileDataIsThisFormat instead.
@param inComponent an AudioFileComponent
@param inClientData a constant that will be passed to your callbacks.
@param inReadFunc a function that will be called when AudioFile needs to read data.
@param inWriteFunc a function that will be called when AudioFile needs to write data.
@param inGetSizeFunc a function that will be called when AudioFile needs to know the file size.
@param inSetSizeFunc a function that will be called when AudioFile needs to set the file size.
@param outResult on output, is set to 1 if the file data is recognized by this component, 0 if not.
@result returns noErr if successful.
*/
extern OSStatus
AudioFileComponentDataIsThisFormat(
AudioFileComponent inComponent,
void * __nullable inClientData,
AudioFile_ReadProc __nullable inReadFunc,
AudioFile_WriteProc __nullable inWriteFunc,
AudioFile_GetSizeProc __nullable inGetSizeFunc,
AudioFile_SetSizeProc __nullable inSetSizeFunc,
UInt32 *outResult) API_DEPRECATED("no longer supported", macos(10.4, 10.5)) API_UNAVAILABLE(ios, watchos, tvos);
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
// The following calls are not made on AudioFile instances.
// They implement the AudioFileGetGlobalInfo calls.
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
/*!
@function AudioFileComponentGetGlobalInfoSize
@abstract implements AudioFileGetGlobalInfoSize.
@param inComponent an AudioFileComponent
@param inPropertyID an AudioFileGlobalInfo property constant.
@param inSpecifierSize The size of the specifier data.
@param inSpecifier A specifier is a buffer of data used as an input argument to some of the global info properties.
@param outPropertySize the size in bytes of the current value of the property. In order to get the property value,
you will need a buffer of this size.
@result returns noErr if successful.
*/
extern OSStatus
AudioFileComponentGetGlobalInfoSize(
AudioFileComponent inComponent,
AudioFileComponentPropertyID inPropertyID,
UInt32 inSpecifierSize,
const void * __nullable inSpecifier,
UInt32 *outPropertySize) API_AVAILABLE(macos(10.4)) API_UNAVAILABLE(ios, watchos, tvos);
/*!
@function AudioFileComponentGetGlobalInfo
@abstract implements AudioFileGetGlobalInfo.
@param inComponent an AudioFileComponent
@param inPropertyID an AudioFileGlobalInfo property constant.
@param inSpecifierSize The size of the specifier data.
@param inSpecifier A specifier is a buffer of data used as an input argument to some of the global info properties.
@param ioPropertyDataSize on input the size of the outPropertyData buffer. On output the number of bytes written to the buffer.
@param outPropertyData the buffer in which to write the property data.
@result returns noErr if successful.
*/
extern OSStatus
AudioFileComponentGetGlobalInfo(
AudioFileComponent inComponent,
AudioFileComponentPropertyID inPropertyID,
UInt32 inSpecifierSize,
const void * __nullable inSpecifier,
UInt32 *ioPropertyDataSize,
void *outPropertyData) API_AVAILABLE(macos(10.4)) API_UNAVAILABLE(ios, watchos, tvos);
//==================================================================================================
// Properties for AudioFileComponentGetGlobalInfo.
//==================================================================================================
/*!
@enum AudioFileComponent specific properties
@constant kAudioFileComponent_CanRead
Is file type readable? Returns a UInt32 1 or 0.
@constant kAudioFileComponent_CanWrite
Is file type writeable? Returns a UInt32 1 or 0.
@constant kAudioFileComponent_FileTypeName
Returns a CFString containing the name for the file type.
@constant kAudioFileComponent_ExtensionsForType
Returns a CFArray of CFStrings containing the file extensions
that are recognized for this file type.
@constant kAudioFileComponent_UTIsForType
Returns a CFArray of CFStrings containing the universal type identifiers
for this file type.
@constant kAudioFileComponent_MIMETypesForType
Returns a CFArray of CFStrings containing the MIME types
for this file type.
@constant kAudioFileComponent_AvailableFormatIDs
Returns a array of format IDs for formats that can be read.
@constant kAudioFileComponent_AvailableStreamDescriptionsForFormat
The specifier is the format ID for the requested format.
Returns an array of AudioStreamBasicDescriptions which have all of the
formats for a particular file type and format ID. The AudioStreamBasicDescriptions
have the following fields filled in: mFormatID, mFormatFlags, mBitsPerChannel
@constant kAudioFileComponent_FastDispatchTable
Deprecated. This selector is no longer called by the implementation.
@constant kAudioFileComponent_HFSTypeCodesForType
Returns an array of HFSTypeCodes corresponding to this file type.
The first type in the array is the preferred one for use when
writing new files.
*/
CF_ENUM(AudioFilePropertyID)
{
kAudioFileComponent_CanRead = 'cnrd',
kAudioFileComponent_CanWrite = 'cnwr',
kAudioFileComponent_FileTypeName = 'ftnm',
kAudioFileComponent_UTIsForType = 'futi',
kAudioFileComponent_MIMETypesForType = 'fmim',
kAudioFileComponent_ExtensionsForType = 'fext',
kAudioFileComponent_AvailableFormatIDs = 'fmid',
kAudioFileComponent_AvailableStreamDescriptionsForFormat = 'sdid',
kAudioFileComponent_FastDispatchTable = 'fdft',
kAudioFileComponent_HFSTypeCodesForType = 'fhfs'
};
//==================================================================================================
// Selectors for the component routines
//==================================================================================================
enum
{
kAudioFileCreateSelect = 0x0001,
kAudioFileOpenSelect = 0x0002,
kAudioFileInitializeSelect = 0x0003,
kAudioFileOpenWithCallbacksSelect = 0x0004,
kAudioFileInitializeWithCallbacksSelect = 0x0005,
kAudioFileCloseSelect = 0x0006,
kAudioFileOptimizeSelect = 0x0007,
kAudioFileReadBytesSelect = 0x0008,
kAudioFileWriteBytesSelect = 0x0009,
kAudioFileReadPacketsSelect = 0x000A,
kAudioFileWritePacketsSelect = 0x000B,
kAudioFileGetPropertyInfoSelect = 0x000C,
kAudioFileGetPropertySelect = 0x000D,
kAudioFileSetPropertySelect = 0x000E,
kAudioFileExtensionIsThisFormatSelect = 0x000F,
kAudioFileFileIsThisFormatSelect = 0x0010,
kAudioFileDataIsThisFormatSelect = 0x0011,
kAudioFileGetGlobalInfoSizeSelect = 0x0012,
kAudioFileGetGlobalInfoSelect = 0x0013,
kAudioFileCountUserDataSelect = 0x0014,
kAudioFileGetUserDataSizeSelect = 0x0015,
kAudioFileGetUserDataSelect = 0x0016,
kAudioFileSetUserDataSelect = 0x0017,
kAudioFileRemoveUserDataSelect = 0x0018,
kAudioFileCreateURLSelect = 0x0019,
kAudioFileOpenURLSelect = 0x001A,
kAudioFileFileDataIsThisFormatSelect = 0x001B,
kAudioFileReadPacketDataSelect = 0x001C,
};
#pragma mark -
#pragma mark Deprecated
//==================================================================================================
// Fast Dispatch Function typedefs. Deprecated. These are no longer used by the implementation.
//==================================================================================================
typedef OSStatus (*ReadBytesFDF)( void *inComponentStorage,
Boolean inUseCache,
SInt64 inStartingByte,
UInt32 *ioNumBytes,
void *outBuffer);
typedef OSStatus (*WriteBytesFDF)( void *inComponentStorage,
Boolean inUseCache,
SInt64 inStartingByte,
UInt32 *ioNumBytes,
const void *inBuffer);
typedef OSStatus (*ReadPacketsFDF)( void *inComponentStorage,
Boolean inUseCache,
UInt32 *outNumBytes,
AudioStreamPacketDescription * __nullable outPacketDescriptions,
SInt64 inStartingPacket,
UInt32 *ioNumPackets,
void *outBuffer);
typedef OSStatus (*ReadPacketDataFDF)( void *inComponentStorage,
Boolean inUseCache,
UInt32 *ioNumBytes,
AudioStreamPacketDescription * __nullable outPacketDescriptions,
SInt64 inStartingPacket,
UInt32 *ioNumPackets,
void *outBuffer);
typedef OSStatus (*WritePacketsFDF)( void *inComponentStorage,
Boolean inUseCache,
UInt32 inNumBytes,
const AudioStreamPacketDescription * __nullable inPacketDescriptions,
SInt64 inStartingPacket,
UInt32 *ioNumPackets,
const void *inBuffer);
typedef OSStatus (*GetPropertyInfoFDF)( void *inComponentStorage,
AudioFilePropertyID inPropertyID,
UInt32 * __nullable outDataSize,
UInt32 * __nullable isWritable);
typedef OSStatus (*GetPropertyFDF)( void *inComponentStorage,
AudioFilePropertyID inPropertyID,
UInt32 *ioDataSize,
void *ioPropertyData);
typedef OSStatus (*SetPropertyFDF)( void *inComponentStorage,
AudioFilePropertyID inPropertyID,
UInt32 inDataSize,
const void *inPropertyData);
typedef OSStatus (*CountUserDataFDF)( void *inComponentStorage,
UInt32 inUserDataID,
UInt32 *outNumberItems);
typedef OSStatus (*GetUserDataSizeFDF)( void *inComponentStorage,
UInt32 inUserDataID,
UInt32 inIndex,
UInt32 *outDataSize);
typedef OSStatus (*GetUserDataFDF)( void *inComponentStorage,
UInt32 inUserDataID,
UInt32 inIndex,
UInt32 *ioUserDataSize,
void *outUserData);
typedef OSStatus (*SetUserDataFDF)( void *inComponentStorage,
UInt32 inUserDataID,
UInt32 inIndex,
UInt32 inUserDataSize,
const void *inUserData);
/* no fast dispatch for kAudioFileRemoveUserDataSelect */
#pragma mark -
#pragma mark Deprecated
//==================================================================================================
// Fast Dispatch Function tables. Deprecated. These are no longer used by the implementation.
//==================================================================================================
typedef struct AudioFileFDFTable
{
void *mComponentStorage;
ReadBytesFDF mReadBytesFDF;
WriteBytesFDF mWriteBytesFDF;
ReadPacketsFDF mReadPacketsFDF;
WritePacketsFDF mWritePacketsFDF;
GetPropertyInfoFDF mGetPropertyInfoFDF;
GetPropertyFDF mGetPropertyFDF;
SetPropertyFDF mSetPropertyFDF;
CountUserDataFDF mCountUserDataFDF;
GetUserDataSizeFDF mGetUserDataSizeFDF;
GetUserDataFDF mGetUserDataFDF;
SetUserDataFDF mSetUserDataFDF;
} AudioFileFDFTable API_DEPRECATED("no longer supported", macos(10.4, 10.7)) API_UNAVAILABLE(ios, watchos, tvos);
typedef struct AudioFileFDFTableExtended
{
void *mComponentStorage;
ReadBytesFDF mReadBytesFDF;
WriteBytesFDF mWriteBytesFDF;
ReadPacketsFDF mReadPacketsFDF;
WritePacketsFDF mWritePacketsFDF;
GetPropertyInfoFDF mGetPropertyInfoFDF;
GetPropertyFDF mGetPropertyFDF;
SetPropertyFDF mSetPropertyFDF;
CountUserDataFDF mCountUserDataFDF;
GetUserDataSizeFDF mGetUserDataSizeFDF;
GetUserDataFDF mGetUserDataFDF;
SetUserDataFDF mSetUserDataFDF;
ReadPacketDataFDF mReadPacketDataFDF;
} AudioFileFDFTableExtended API_DEPRECATED("no longer supported", macos(10.4, 10.7)) API_UNAVAILABLE(ios, watchos, tvos);
struct FSRef;
/*!
@functiongroup Deprecated AFComponent
@discussion These API calls are no longer called on Snow Leopard, instead the URL versions are used.
They can be provided by the file component for compatibility with Leopard and Tiger systems
*/
/*!
@function AudioFileComponentCreate
@abstract implements AudioFileCreate
@param inComponent an AudioFileComponent
@param inParentRef an FSRef to the directory where the new file should be created.
@param inFileName a CFStringRef containing the name of the file to be created.
@param inFormat an AudioStreamBasicDescription describing the data format that will be
added to the audio file.
@param inFlags relevant flags for creating/opening the file. Currently zero.
@param outNewFileRef if successful, the FSRef of the newly created file.
@result returns noErr if successful.
*/
extern OSStatus
AudioFileComponentCreate(
AudioFileComponent inComponent,
const struct FSRef *inParentRef,
CFStringRef inFileName,
const AudioStreamBasicDescription *inFormat,
UInt32 inFlags,
struct FSRef *outNewFileRef) API_DEPRECATED("no longer supported", macos(10.4, 10.6)) API_UNAVAILABLE(ios, watchos, tvos);
/*!
@function AudioFileComponentInitialize
@abstract implements AudioFileInitialize
@param inComponent an AudioFileComponent
@param inFileRef the FSRef of an existing audio file.
@param inFormat an AudioStreamBasicDescription describing the data format that will be
added to the audio file.
@param inFlags flags for creating/opening the file. Currently zero.
@result returns noErr if successful.
*/
extern OSStatus
AudioFileComponentInitialize(
AudioFileComponent inComponent,
const struct FSRef *inFileRef,
const AudioStreamBasicDescription *inFormat,
UInt32 inFlags) API_DEPRECATED("no longer supported", macos(10.4, 10.6)) API_UNAVAILABLE(ios, watchos, tvos);
/*!
@function AudioFileComponentOpenFile
@abstract implements AudioFileOpen
@param inComponent an AudioFileComponent
@param inFileRef the FSRef of an existing audio file.
@param inPermissions use the permission constants
@param inRefNum the file refNum for the opened file. This avoids opening the file twice
- once to determine which file type to which to delegate and once to parse it.
@result returns noErr if successful.
*/
extern OSStatus
AudioFileComponentOpenFile(
AudioFileComponent inComponent,
const struct FSRef *inFileRef,
SInt8 inPermissions,
SInt16 inRefNum) API_DEPRECATED("no longer supported", macos(10.4, 10.6)) API_UNAVAILABLE(ios, watchos, tvos);
#if defined(__cplusplus)
}
#endif
#if !TARGET_OS_IPHONE
//=====================================================================================================================
typedef OSStatus (*AudioFileComponentCreateURLProc)(
void *self,
CFURLRef inFileRef,
const AudioStreamBasicDescription* inFormat,
UInt32 inFlags);
typedef OSStatus (*AudioFileComponentOpenURLProc)(
void *self,
CFURLRef inFileRef,
SInt8 inPermissions,
int inFileDescriptor);
typedef OSStatus (*AudioFileComponentOpenWithCallbacksProc)(
void *self,
void *inClientData,
AudioFile_ReadProc inReadFunc,
AudioFile_WriteProc inWriteFunc,
AudioFile_GetSizeProc inGetSizeFunc,
AudioFile_SetSizeProc inSetSizeFunc);
typedef OSStatus (*AudioFileComponentInitializeWithCallbacksProc)(
void *self,
void *inClientData,
AudioFile_ReadProc inReadFunc,
AudioFile_WriteProc inWriteFunc,
AudioFile_GetSizeProc inGetSizeFunc,
AudioFile_SetSizeProc inSetSizeFunc,
UInt32 inFileType,
const AudioStreamBasicDescription *inFormat,
UInt32 inFlags);
typedef OSStatus (*AudioFileComponentCloseProc)(
void *self);
typedef OSStatus (*AudioFileComponentOptimizeProc)(
void *self);
typedef OSStatus (*AudioFileComponentReadBytesProc)(
void *self,
Boolean inUseCache,
SInt64 inStartingByte,
UInt32 *ioNumBytes,
void *outBuffer);
typedef OSStatus (*AudioFileComponentWriteBytesProc)(
void *self,
Boolean inUseCache,
SInt64 inStartingByte,
UInt32 *ioNumBytes,
const void *inBuffer);
typedef OSStatus (*AudioFileComponentReadPacketsProc)(
void *self,
Boolean inUseCache,
UInt32 *outNumBytes,
AudioStreamPacketDescription * __nullable outPacketDescriptions,
SInt64 inStartingPacket,
UInt32 *ioNumPackets,
void *outBuffer);
typedef OSStatus (*AudioFileComponentReadPacketDataProc)(
void *self,
Boolean inUseCache,
UInt32 *ioNumBytes,
AudioStreamPacketDescription * __nullable outPacketDescriptions,
SInt64 inStartingPacket,
UInt32 *ioNumPackets,
void *outBuffer);
typedef OSStatus (*AudioFileComponentWritePacketsProc)(
void *self,
Boolean inUseCache,
UInt32 inNumBytes,
const AudioStreamPacketDescription * __nullable inPacketDescriptions,
SInt64 inStartingPacket,
UInt32 *ioNumPackets,
const void *inBuffer);
typedef OSStatus (*AudioFileComponentGetPropertyInfoProc)(
void *self,
AudioFileComponentPropertyID inPropertyID,
UInt32 * __nullable outPropertySize,
UInt32 * __nullable outWritable);
typedef OSStatus (*AudioFileComponentGetPropertyProc)(
void *self,
AudioFileComponentPropertyID inPropertyID,
UInt32 *ioPropertyDataSize,
void *outPropertyData);
typedef OSStatus (*AudioFileComponentSetPropertyProc)(
void *self,
AudioFileComponentPropertyID inPropertyID,
UInt32 inPropertyDataSize,
const void *inPropertyData);
typedef OSStatus (*AudioFileComponentCountUserDataProc)(
void *self,
UInt32 inUserDataID,
UInt32 *outNumberItems);
typedef OSStatus (*AudioFileComponentGetUserDataSizeProc)(
void *self,
UInt32 inUserDataID,
UInt32 inIndex,
UInt32 *outUserDataSize);
typedef OSStatus (*AudioFileComponentGetUserDataProc)(
void *self,
UInt32 inUserDataID,
UInt32 inIndex,
UInt32 *ioUserDataSize,
void *outUserData);
typedef OSStatus (*AudioFileComponentSetUserDataProc)(
void *self,
UInt32 inUserDataID,
UInt32 inIndex,
UInt32 inUserDataSize,
const void *inUserData);
typedef OSStatus (*AudioFileComponentRemoveUserDataProc)(
void *self,
UInt32 inUserDataID,
UInt32 inIndex);
typedef OSStatus (*AudioFileComponentExtensionIsThisFormatProc)(
void *self,
CFStringRef inExtension,
UInt32 *outResult);
typedef OSStatus (*AudioFileComponentFileDataIsThisFormatProc)(
void *self,
UInt32 inDataByteSize,
const void* inData,
UInt32 *outResult);
typedef OSStatus (*AudioFileComponentGetGlobalInfoSizeProc)(
void *self,
AudioFileComponentPropertyID inPropertyID,
UInt32 inSpecifierSize,
const void * __nullable inSpecifier,
UInt32 *outPropertySize);
typedef OSStatus (*AudioFileComponentGetGlobalInfoProc)(
void *self,
AudioFileComponentPropertyID inPropertyID,
UInt32 inSpecifierSize,
const void * __nullable inSpecifier,
UInt32 *ioPropertyDataSize,
void *outPropertyData);
#endif
CF_ASSUME_NONNULL_END
#endif // AudioToolbox_AudioFileComponent_h
#else
#include <AudioToolboxCore/AudioFileComponent.h>
#endif

View File

@@ -0,0 +1,499 @@
#if (defined(__USE_PUBLIC_HEADERS__) && __USE_PUBLIC_HEADERS__) || (defined(USE_AUDIOTOOLBOX_PUBLIC_HEADERS) && USE_AUDIOTOOLBOX_PUBLIC_HEADERS) || !__has_include(<AudioToolboxCore/AudioFileStream.h>)
/*!
@file AudioFileStream.h
@framework AudioToolbox.framework
@copyright (c) 1985-2015 by Apple, Inc., all rights reserved.
@brief API's to parse streamed audio files into packets of audio data.
@discussion
AudioFileStream addresses situations where, in a stream of audio data, only a limited window
of data may be available at any time.
This case differs significantly enough from the random access file case to warrant a separate
API rather than overload the AudioFile API with additional semantics. With a random access file,
one can always assume that a read request for contiguous data that doesn't include EOF will
always supply all of the data. This makes parsing straightforward and inexpensive. In the
streaming case such an assumption cannot be made. A request by the parser for data from the
stream may only be partially satisfied. Any partially satisfied requests must be remembered and
retried before any other requests are satisfied, otherwise the streamed data might be lost
forever in the past. So the parser must be able to suspend work at any point and resume parsing
where it left off.
The client provides data to the parser using AudioFileStreamParseBytes and the parser calls back
to the client with properties or packets using the AudioFileStream_PropertyListenerProc and
AudioFileStream_PacketsProc function pointers.
*/
#ifndef AudioToolbox_AudioFileStream_h
#define AudioToolbox_AudioFileStream_h
//=============================================================================
// Includes
//=============================================================================
#include <AudioToolbox/AudioFile.h>
CF_ASSUME_NONNULL_BEGIN
#if defined(__cplusplus)
extern "C"
{
#endif
//=============================================================================
// AudioFileStream flags
//=============================================================================
#pragma mark flags
/*!
@enum AudioFileStreamPropertyFlags
@constant kAudioFileStreamPropertyFlag_PropertyIsCached
This flag is set in a call to AudioFileStream_PropertyListenerProc when the value of the property
can be obtained at any later time. If this flag is not set, then you should either get the value of
the property from within this callback or set the flag kAudioFileStreamPropertyFlag_CacheProperty in order to signal
to the parser to begin caching the property data. Otherwise the value may not be available in the future.
@constant kAudioFileStreamPropertyFlag_CacheProperty
This flag can be set by a property listener in order to signal to the parser that the client is
interested in the value of the property and that it should be cached until the full value of the property is available.
*/
typedef CF_OPTIONS(UInt32, AudioFileStreamPropertyFlags) {
kAudioFileStreamPropertyFlag_PropertyIsCached = 1,
kAudioFileStreamPropertyFlag_CacheProperty = 2
};
/*! @enum AudioFileStreamParseFlags
@constant kAudioFileStreamParseFlag_Discontinuity
This flag is passed in to AudioFileStreamParseBytes to signal a discontinuity. Any partial packet straddling a buffer
boundary will be discarded. This is necessary to avoid being called with a corrupt packet. After a discontinuity occurs
seeking may be approximate in some data formats.
*/
typedef CF_OPTIONS(UInt32, AudioFileStreamParseFlags) {
kAudioFileStreamParseFlag_Discontinuity = 1
};
/*! @enum AudioFileStreamParseFlags
@constant kAudioFileStreamSeekFlag_OffsetIsEstimated
This flag may be returned from AudioFileStreamSeek if the byte offset is only an estimate, not exact.
*/
typedef CF_OPTIONS(UInt32, AudioFileStreamSeekFlags) {
kAudioFileStreamSeekFlag_OffsetIsEstimated = 1
};
//=============================================================================
// AudioFileStream Types
//=============================================================================
#pragma mark types
typedef UInt32 AudioFileStreamPropertyID;
typedef struct OpaqueAudioFileStreamID *AudioFileStreamID;
typedef void (*AudioFileStream_PropertyListenerProc)(
void * inClientData,
AudioFileStreamID inAudioFileStream,
AudioFileStreamPropertyID inPropertyID,
AudioFileStreamPropertyFlags * ioFlags);
typedef void (*AudioFileStream_PacketsProc)(
void * inClientData,
UInt32 inNumberBytes,
UInt32 inNumberPackets,
const void * inInputData,
AudioStreamPacketDescription * __nullable inPacketDescriptions);
//=============================================================================
// AudioFileStream error codes
//=============================================================================
#pragma mark Error codes
/*!
@enum AudioFileStream error codes
@abstract These are the error codes returned from the AudioFile API.
@constant kAudioFileStreamError_UnsupportedFileType
The file type is not supported.
@constant kAudioFileStreamError_UnsupportedDataFormat
The data format is not supported by this file type.
@constant kAudioFileStreamError_UnsupportedProperty
The property is not supported.
@constant kAudioFileStreamError_BadPropertySize
The size of the property data was not correct.
@constant kAudioFileStreamError_NotOptimized
It is not possible to produce output packets because the file's packet table or other defining
info is either not present or is after the audio data.
@constant kAudioFileStreamError_InvalidPacketOffset
A packet offset was less than zero, or past the end of the file,
or a corrupt packet size was read when building the packet table.
@constant kAudioFileStreamError_InvalidFile
The file is malformed, or otherwise not a valid instance of an audio file of its type, or
is not recognized as an audio file.
@constant kAudioFileStreamError_ValueUnknown
The property value is not present in this file before the audio data.
@constant kAudioFileStreamError_DataUnavailable
The amount of data provided to the parser was insufficient to produce any result.
@constant kAudioFileStreamError_IllegalOperation
An illegal operation was attempted.
@constant kAudioFileStreamError_UnspecifiedError
An unspecified error has occurred.
*/
CF_ENUM(OSStatus)
{
kAudioFileStreamError_UnsupportedFileType = 'typ?',
kAudioFileStreamError_UnsupportedDataFormat = 'fmt?',
kAudioFileStreamError_UnsupportedProperty = 'pty?',
kAudioFileStreamError_BadPropertySize = '!siz',
kAudioFileStreamError_NotOptimized = 'optm',
kAudioFileStreamError_InvalidPacketOffset = 'pck?',
kAudioFileStreamError_InvalidFile = 'dta?',
kAudioFileStreamError_ValueUnknown = 'unk?',
kAudioFileStreamError_DataUnavailable = 'more',
kAudioFileStreamError_IllegalOperation = 'nope',
kAudioFileStreamError_UnspecifiedError = 'wht?',
kAudioFileStreamError_DiscontinuityCantRecover = 'dsc!'
};
//=============================================================================
// AudioFileStream Properties
//=============================================================================
#pragma mark Properties
/*!
@enum AudioFileStream Properties
@abstract constants for AudioFileStream get property calls
@discussion There are currently no settable properties.
@constant kAudioFileStreamProperty_ReadyToProducePackets
An UInt32 which is zero until the parser has parsed up to the beginning of the audio data.
Once it has reached the audio data, the value of this property becomes one.
When this value has become one, all properties that can be known about the stream are known.
@constant kAudioFileStreamProperty_FileFormat
An UInt32 four char code that identifies the format of the file
@constant kAudioFileStreamProperty_DataFormat
An AudioStreamBasicDescription describing the format of the audio data
@constant kAudioFileStreamProperty_FormatList
In order to support formats such as AAC SBR where an encoded data stream can be decoded to
multiple destination formats, this property returns an array of AudioFormatListItems
(see AudioFormat.h) of those formats.
The default behavior is to return the an AudioFormatListItem that has the same
AudioStreamBasicDescription that kAudioFileStreamProperty_DataFormat returns.
@constant kAudioFileStreamProperty_MagicCookieData
A void * pointing to memory set up by the caller.
Some file types require that a magic cookie be provided before packets can be written
to the file, so this property should be set before calling
AudioFileWriteBytes()/AudioFileWritePackets() if a magic cookie exists.
@constant kAudioFileStreamProperty_AudioDataByteCount
a UInt64 that indicates the number of bytes of audio data contained in the file
@constant kAudioFileStreamProperty_AudioDataPacketCount
a UInt64 that indicates the number of packets of audio data contained in the file
@constant kAudioFileStreamProperty_MaximumPacketSize
a UInt32 that indicates the maximum size of a packet for the data contained in the file
@constant kAudioFileStreamProperty_DataOffset
a SInt64 that indicates the byte offset in the file of the audio data.
@constant kAudioFileStreamProperty_ChannelLayout
An AudioChannelLayout struct.
@constant kAudioFileStreamProperty_PacketToFrame
pass a AudioFramePacketTranslation with mPacket filled out and get mFrame back.
mFrameOffsetInPacket is ignored.
@constant kAudioFileStreamProperty_FrameToPacket
pass a AudioFramePacketTranslation with mFrame filled out and get mPacket and
mFrameOffsetInPacket back.
@constant kAudioFileStreamProperty_RestrictsRandomAccess
A UInt32 indicating whether an Audio File contains packets that cannot be used as random
access points.
A value of 0 indicates that any packet can be used as a random access point, i.e. that a
decoder can start decoding with any packet.
A value of 1 indicates that some packets cannot be used as random access points, i.e.
that either kAudioFileStreamProperty_PacketToRollDistance or
kAudioFileStreamProperty_PacketToDependencyInfo must be employed in order to identify an
appropriate initial packet for decoding.
@constant kAudioFileStreamProperty_PacketToRollDistance
Pass an AudioPacketRollDistanceTranslation with mPacket filled out and get mRollDistance
back.
See AudioFile.h for the declaration of AudioPacketRollDistanceTranslation.
The roll distance indicates the count of packets that must be decoded prior to the
packet with the specified number in order to achieve full refresh of the decoder at that
packet.
For file formats that do not carry comprehensive information regarding independently
decodable packets, accurate roll distances may be available only for the range of
packets either currently or most recently provided to your packets proc.
@constant kAudioFileStreamProperty_PreviousIndependentPacket
@constant kAudioFileStreamProperty_NextIndependentPacket
Pass an AudioIndependentPacketTranslation with mPacket filled out and get
mIndependentlyDecodablePacket back. A value of -1 means that no independent packet is
present in the stream in the direction of interest. Otherwise, for
kAudioFileStreamProperty_PreviousIndependentPacket, mIndependentlyDecodablePacket will be
less than mPacket, and for kAudioFileStreamProperty_NextIndependentPacket,
mIndependentlyDecodablePacket will be greater than mPacket.
For file formats that do not carry comprehensive information regarding independently
decodable packets, independent packets may be identifiable only within the range of
packets either currently or most recently provided to your packets proc.
@constant kAudioFileStreamProperty_PacketToDependencyInfo
Pass an AudioPacketDependencyInfoTranslation with mPacket filled out and get
mIsIndependentlyDecodable and mPrerollPacketCount back.
A value of 0 for mIsIndependentlyDecodable indicates that the specified packet is not
independently decodable.
A value of 1 for mIsIndependentlyDecodable indicates that the specified packet is
independently decodable.
For independently decodable packets, mPrerollPacketCount indicates the count of packets
that must be decoded after the packet with the specified number in order to refresh the
decoder.
For file formats that do not carry comprehensive information regarding packet
dependencies, accurate dependency info may be available only for the range of
packets either currently or most recently provided to your packets proc.
@constant kAudioFileStreamProperty_PacketToByte
pass an AudioBytePacketTranslation struct with mPacket filled out and get mByte back.
mByteOffsetInPacket is ignored. If the mByte value is an estimate then
kBytePacketTranslationFlag_IsEstimate will be set in the mFlags field.
@constant kAudioFileStreamProperty_ByteToPacket
pass an AudioBytePacketTranslation struct with mByte filled out and get mPacket and
mByteOffsetInPacket back. If the mPacket value is an estimate then
kBytePacketTranslationFlag_IsEstimate will be set in the mFlags field.
@constant kAudioFileStreamProperty_PacketTableInfo
Gets the AudioFilePacketTableInfo struct for the file types that support it.
@constant kAudioFileStreamProperty_PacketSizeUpperBound
a UInt32 for the theoretical maximum packet size in the file.
@constant kAudioFileStreamProperty_AverageBytesPerPacket
a Float64 of giving the average bytes per packet seen.
For CBR and files with packet tables, this number will be exact. Otherwise, it is a
running average of packets parsed.
@constant kAudioFileStreamProperty_BitRate
a UInt32 of the bit rate in bits per second.
@constant kAudioFileStreamProperty_InfoDictionary
a CFDictionary filled with information about the data contained in the stream.
See AudioFile.h for InfoDictionary key strings. Caller is responsible for releasing the CFObject.
*/
CF_ENUM(AudioFileStreamPropertyID)
{
kAudioFileStreamProperty_ReadyToProducePackets = 'redy',
kAudioFileStreamProperty_FileFormat = 'ffmt',
kAudioFileStreamProperty_DataFormat = 'dfmt',
kAudioFileStreamProperty_FormatList = 'flst',
kAudioFileStreamProperty_MagicCookieData = 'mgic',
kAudioFileStreamProperty_AudioDataByteCount = 'bcnt',
kAudioFileStreamProperty_AudioDataPacketCount = 'pcnt',
kAudioFileStreamProperty_MaximumPacketSize = 'psze',
kAudioFileStreamProperty_DataOffset = 'doff',
kAudioFileStreamProperty_ChannelLayout = 'cmap',
kAudioFileStreamProperty_PacketToFrame = 'pkfr',
kAudioFileStreamProperty_FrameToPacket = 'frpk',
kAudioFileStreamProperty_RestrictsRandomAccess = 'rrap',
kAudioFileStreamProperty_PacketToRollDistance = 'pkrl',
kAudioFileStreamProperty_PreviousIndependentPacket = 'pind',
kAudioFileStreamProperty_NextIndependentPacket = 'nind',
kAudioFileStreamProperty_PacketToDependencyInfo = 'pkdp',
kAudioFileStreamProperty_PacketToByte = 'pkby',
kAudioFileStreamProperty_ByteToPacket = 'bypk',
kAudioFileStreamProperty_PacketTableInfo = 'pnfo',
kAudioFileStreamProperty_PacketSizeUpperBound = 'pkub',
kAudioFileStreamProperty_AverageBytesPerPacket = 'abpp',
kAudioFileStreamProperty_BitRate = 'brat',
kAudioFileStreamProperty_InfoDictionary = 'info'
};
//=============================================================================
// AudioFileStream Functions
//=============================================================================
#pragma mark Functions
/*!
@function AudioFileStreamOpen
@discussion Create a new audio file stream parser.
The client provides the parser with data and the parser calls
callbacks when interesting things are found in the data, such as properties and
audio packets.
@param inClientData
a constant that will be passed to your callbacks.
@param inPropertyListenerProc
Whenever the value of a property is parsed in the data, this function will be called.
You can then get the value of the property from in the callback. In some cases, due to
boundaries in the input data, the property may return kAudioFileStreamError_DataUnavailable.
When unavailable data is requested from within the property listener, the parser will begin
caching the property value and will call the property listener again when the property is
available. For property values for which kAudioFileStreamPropertyFlag_PropertyIsCached is unset, this
will be the only opportunity to get the value of the property, since the data will be
disposed upon return of the property listener callback.
@param inPacketsProc
Whenever packets are parsed in the data, a pointer to the packets is passed to the client
using this callback. At times only a single packet may be passed due to boundaries in the
input data.
@param inFileTypeHint
For files whose type cannot be easily or uniquely determined from the data (ADTS,AC3),
this hint can be used to indicate the file type.
Otherwise if you do not know the file type, you can pass zero.
@param outAudioFileStream
A new file stream ID for use in other AudioFileStream API calls.
*/
extern OSStatus
AudioFileStreamOpen (
void * __nullable inClientData,
AudioFileStream_PropertyListenerProc inPropertyListenerProc,
AudioFileStream_PacketsProc inPacketsProc,
AudioFileTypeID inFileTypeHint,
AudioFileStreamID __nullable * __nonnull outAudioFileStream)
API_AVAILABLE(macos(10.5), ios(2.0), watchos(2.0), tvos(9.0));
/*!
@function AudioFileStreamParseBytes
@discussion This call is the means for streams to supply data to the parser.
Data is expected to be passed in sequentially from the beginning of the file, without gaps.
In the course of parsing, the client's property and/or packets callbacks may be called.
At the end of the stream, this function must be called once with null data pointer and zero
data byte size to flush any remaining packets out of the parser.
@param inAudioFileStream
The file stream ID
@param inDataByteSize
The number of bytes passed in for parsing. Must be zero when flushing the parser.
@param inData
The data passed in to be parsed. Must be null when flushing the parser.
@param inFlags
If there is a data discontinuity, then kAudioFileStreamParseFlag_Discontinuity should be set true.
*/
extern OSStatus
AudioFileStreamParseBytes(
AudioFileStreamID inAudioFileStream,
UInt32 inDataByteSize,
const void * __nullable inData,
AudioFileStreamParseFlags inFlags)
API_AVAILABLE(macos(10.5), ios(2.0), watchos(2.0), tvos(9.0));
/*!
@function AudioFileStreamSeek
@discussion This call is used to seek in the data stream. The client passes in a packet
offset to seek to and the parser passes back a byte offset from which to
get the data to satisfy that request. The data passed to the next call to
AudioFileParseBytes will be assumed to be from that byte offset.
For file formats which do not contain packet tables the byte offset may
be an estimate. If so, the flag kAudioFileStreamSeekFlag_OffsetIsEstimated will be true.
@param inAudioFileStream
The file stream ID
@param inPacketOffset
The offset from the beginning of the file of the packet to which to seek.
@param outDataByteOffset
The byte offset of the data from the file's data offset returned.
You need to add the value of kAudioFileStreamProperty_DataOffset to get an absolute byte offset in the file.
@param ioFlags
If outDataByteOffset is an estimate, then kAudioFileStreamSeekFlag_OffsetIsEstimated will be set on output.
There are currently no flags defined for passing into this call.
*/
extern OSStatus
AudioFileStreamSeek(
AudioFileStreamID inAudioFileStream,
SInt64 inPacketOffset,
SInt64 * outDataByteOffset,
AudioFileStreamSeekFlags * ioFlags)
API_AVAILABLE(macos(10.5), ios(2.0), watchos(2.0), tvos(9.0));
/*!
@function AudioFileStreamGetPropertyInfo
@discussion Retrieve the info about the given property. The outSize argument
will return the size in bytes of the current value of the property.
@param inAudioFileStream
The file stream ID
@param inPropertyID
Property ID whose value should be read
@param outPropertyDataSize
Size in bytes of the property
@param outWritable
whether the property is writable
@result an OSStatus return code
*/
extern OSStatus
AudioFileStreamGetPropertyInfo(
AudioFileStreamID inAudioFileStream,
AudioFileStreamPropertyID inPropertyID,
UInt32 * __nullable outPropertyDataSize,
Boolean * __nullable outWritable)
API_AVAILABLE(macos(10.5), ios(2.0), watchos(2.0), tvos(9.0));
/*!
@function AudioFileStreamGetProperty
@discussion Retrieve the indicated property data.
@param inAudioFileStream
The file stream ID
@param inPropertyID
Property ID whose value should be read
@param ioPropertyDataSize
On input, the size of the buffer pointed to by outPropertyData. On output,
the number of bytes written.
@param outPropertyData
Pointer to the property data buffer
@result an OSStatus return code
*/
extern OSStatus
AudioFileStreamGetProperty(
AudioFileStreamID inAudioFileStream,
AudioFileStreamPropertyID inPropertyID,
UInt32 * ioPropertyDataSize,
void * outPropertyData)
API_AVAILABLE(macos(10.5), ios(2.0), watchos(2.0), tvos(9.0));
/*!
@function AudioFileStreamSetProperty
@discussion Set the value of the property. There are currently no settable properties.
@param inAudioFileStream
The file stream ID
@param inPropertyID
Property ID whose value should be set
@param inPropertyDataSize
Size in bytes of the property data
@param inPropertyData
Pointer to the property data buffer
@result an OSStatus return code
*/
extern OSStatus
AudioFileStreamSetProperty(
AudioFileStreamID inAudioFileStream,
AudioFileStreamPropertyID inPropertyID,
UInt32 inPropertyDataSize,
const void * inPropertyData)
API_AVAILABLE(macos(10.5), ios(2.0), watchos(2.0), tvos(9.0));
/*!
@function AudioFileStreamClose
@discussion Close and deallocate the file stream object.
@param inAudioFileStream
The file stream ID
*/
extern OSStatus
AudioFileStreamClose( AudioFileStreamID inAudioFileStream)
API_AVAILABLE(macos(10.5), ios(2.0), watchos(2.0), tvos(9.0));
#if defined(__cplusplus)
}
#endif
CF_ASSUME_NONNULL_END
#endif // AudioToolbox_AudioFileStream_h
#else
#include <AudioToolboxCore/AudioFileStream.h>
#endif

View File

@@ -0,0 +1,537 @@
#if (defined(__USE_PUBLIC_HEADERS__) && __USE_PUBLIC_HEADERS__) || (defined(USE_AUDIOTOOLBOX_PUBLIC_HEADERS) && USE_AUDIOTOOLBOX_PUBLIC_HEADERS) || !__has_include(<AudioToolboxCore/AudioFormat.h>)
/*!
@file AudioFormat.h
@framework AudioToolbox.framework
@copyright (c) 1985-2015 by Apple, Inc., all rights reserved.
@abstract API for finding things out about audio formats.
*/
#ifndef AudioToolbox_AudioFormat_h
#define AudioToolbox_AudioFormat_h
//=============================================================================
// Includes
//=============================================================================
// System Includes
#include <Availability.h>
#include <CoreAudioTypes/CoreAudioTypes.h>
CF_ASSUME_NONNULL_BEGIN
#if defined(__cplusplus)
extern "C"
{
#endif
//=============================================================================
// Types
//=============================================================================
/*!
@typedef AudioFormatPropertyID
@abstract A type for four char codes for property IDs
*/
typedef UInt32 AudioFormatPropertyID;
/*!
@enum AudioPanningMode
@abstract Different panning algorithms.
@constant kPanningMode_SoundField
Sound field panning algorithm
@constant kPanningMode_VectorBasedPanning
Vector based panning algorithm
*/
typedef CF_ENUM(UInt32, AudioPanningMode) {
kPanningMode_SoundField = 3,
kPanningMode_VectorBasedPanning = 4
};
/*!
@struct AudioPanningInfo
@abstract This struct is for use with kAudioFormatProperty_PanningMatrix.
@var mPanningMode the PanningMode to be used for the pan
@var mCoordinateFlags the coordinates are specified as in the AudioChannelDescription struct in CoreAudioTypes.h
@var mCoordinates the coordinates are specified as in the AudioChannelDescription struct in CoreAudioTypes.h
@var mGainScale
mGainScale is used to multiply the panning values.
In typical usage you are applying an existing volume.
value in 0 -> 1 (where 1 is unity gain) to the panned values.
1 would give you panning at unity.
0 would give you back a matrix of zeroes.
@var mOutputChannelMap
This is the channel map that is going to be used to determine channel volumes for this pan.
*/
struct AudioPanningInfo {
AudioPanningMode mPanningMode;
UInt32 mCoordinateFlags;
Float32 mCoordinates[3];
Float32 mGainScale;
const AudioChannelLayout * mOutputChannelMap;
};
typedef struct AudioPanningInfo AudioPanningInfo;
/*!
@enum AudioBalanceFadeType
@abstract used for mType field of AudioBalanceFade struct
@constant kAudioBalanceFadeType_MaxUnityGain
the gain value never exceeds 1.0, the opposite channel fades out.
This can reduce overall loudness when the balance or fade is not in the center.
@constant kAudioBalanceFadeType_EqualPower
The overall loudness remains constant, but gain can exceed 1.0.
the gain value is 1.0 when the balance and fade are in the center.
From there they can increase to +3dB (1.414) and decrease to -inf dB (0.0).
*/
typedef CF_ENUM(UInt32, AudioBalanceFadeType) {
kAudioBalanceFadeType_MaxUnityGain = 0,
kAudioBalanceFadeType_EqualPower = 1
};
/*!
@struct AudioBalanceFade
@abstract this struct is used with kAudioFormatProperty_BalanceFade
@var mLeftRightBalance
-1 is full left, 0 is center, +1 is full right
@var mBackFrontFade
-1 is full rear, 0 is center, +1 is full front
@var mType
an AudioBalanceFadeType constant
@var mChannelLayout
a pointer to an AudioChannelLayout
*/
struct AudioBalanceFade
{
Float32 mLeftRightBalance; // -1 is full left, 0 is center, +1 is full right
Float32 mBackFrontFade; // -1 is full rear, 0 is center, +1 is full front
AudioBalanceFadeType mType; // max unity gain, or equal power.
const AudioChannelLayout* mChannelLayout;
};
typedef struct AudioBalanceFade AudioBalanceFade;
/*!
@struct AudioFormatInfo
@abstract this struct is used as a specifier for the kAudioFormatProperty_FormatList property
@var mASBD
an AudioStreamBasicDescription
@var mMagicCookie
a pointer to the decompression info for the data described in mASBD
@var mMagicCookieSize
the size in bytes of mMagicCookie
*/
struct AudioFormatInfo
{
AudioStreamBasicDescription mASBD;
const void* mMagicCookie;
UInt32 mMagicCookieSize;
};
typedef struct AudioFormatInfo AudioFormatInfo;
/*!
@struct ExtendedAudioFormatInfo
@abstract this struct is used as a specifier for the kAudioFormatProperty_FormatList property
@var mASBD
an AudioStreamBasicDescription
@var mMagicCookie
a pointer to the decompression info for the data described in mASBD
@var mMagicCookieSize
the size in bytes of mMagicCookie
@var mClassDescription
an AudioClassDescription specifying the codec to be used in answering the question.
*/
struct ExtendedAudioFormatInfo
{
AudioStreamBasicDescription mASBD;
const void* __nullable mMagicCookie;
UInt32 mMagicCookieSize;
AudioClassDescription mClassDescription;
};
typedef struct ExtendedAudioFormatInfo ExtendedAudioFormatInfo;
//=============================================================================
// Properties - for various format structures.
//=============================================================================
/*!
@enum AudioFormatProperty constants
@abstract constants for use with AudioFormatGetPropertyInfo and AudioFormatGetProperty.
@constant kAudioFormatProperty_FormatInfo
Retrieves general information about a format. The specifier is a
magic cookie, or NULL.
On input, the property value is an AudioStreamBasicDescription which
should have at least the mFormatID filled out. On output it will be filled out
as much as possible given the information known about the format
and the contents of the magic cookie (if any is given).
If multiple formats can be described by the AudioStreamBasicDescription and the associated magic cookie,
this property will return the base level format.
@constant kAudioFormatProperty_FormatIsVBR
Returns whether or not a format has a variable number of bytes per
packet. The specifier is an AudioStreamBasicDescription describing
the format to ask about. The value is a UInt32 where non-zero means
the format is variable bytes per packet.
@constant kAudioFormatProperty_FormatIsExternallyFramed
Returns whether or not a format requires external framing information,
i.e. AudioStreamPacketDescriptions.
The specifier is an AudioStreamBasicDescription describing
the format to ask about. The value is a UInt32 where non-zero means
the format is externally framed. Any format which has variable byte sized packets
requires AudioStreamPacketDescriptions.
@constant kAudioFormatProperty_FormatEmploysDependentPackets
Returns whether or not a format is capable of combining independently
decodable packets with dependent packets. The specifier is an
AudioStreamBasicDescription describing the format to ask about.
The value is a UInt32 where zero means that all packets in streams
of the specified format are independently decodable and non-zero means
that streams of the specified format may include dependent packets.
@constant kAudioFormatProperty_FormatIsEncrypted
Returns whether or not a format is encrypted. The specifier is a UInt32 format ID.
The value is a UInt32 where non-zero means the format is encrypted.
@constant kAudioFormatProperty_EncodeFormatIDs
No specifier needed. Must be set to NULL.
Returns an array of UInt32 format IDs for formats that are valid output formats
for a converter.
@constant kAudioFormatProperty_DecodeFormatIDs
No specifier needed. Must be set to NULL.
Returns an array of UInt32 format IDs for formats that are valid input formats
for a converter.
@constant kAudioFormatProperty_Encoders
The specifier is the format that you are interested in, e.g. 'aac '
Returns an array of AudioClassDescriptions for all installed encoders for the given format
@constant kAudioFormatProperty_Decoders
The specifier is the format that you are interested in, e.g. 'aac '
Returns an array of AudioClassDescriptions for all installed decoders for the given format
@constant kAudioFormatProperty_AvailableEncodeBitRates
The specifier is a UInt32 format ID.
The property value is an array of AudioValueRange describing all available bit rates.
@constant kAudioFormatProperty_AvailableEncodeSampleRates
The specifier is a UInt32 format ID.
The property value is an array of AudioValueRange describing all available sample rates.
@constant kAudioFormatProperty_AvailableEncodeChannelLayoutTags
The specifier is an AudioStreamBasicDescription with at least the mFormatID
and mChannelsPerFrame fields set.
The property value is an array of AudioChannelLayoutTags for the format and number of
channels specified. If mChannelsPerFrame is zero, then all layouts supported by
the format are returned.
@constant kAudioFormatProperty_AvailableEncodeNumberChannels
The specifier is an AudioStreamBasicDescription with at least the mFormatID field set.
The property value is an array of UInt32 indicating the number of channels that can be encoded.
A value of 0xFFFFFFFF indicates that any number of channels may be encoded.
@constant kAudioFormatProperty_AvailableDecodeNumberChannels
The specifier is an AudioStreamBasicDescription with at least the mFormatID field set.
The property value is an array of UInt32 indicating the number of channels that can be decoded.
@constant kAudioFormatProperty_FormatName
Returns a name for a given format. The specifier is an
AudioStreamBasicDescription describing the format to ask about.
The value is a CFStringRef. The caller is responsible for releasing the
returned string. For some formats (eg, Linear PCM) you will get back a
descriptive string (e.g. 16-bit, interleaved, etc...)
@constant kAudioFormatProperty_ASBDFromESDS
Returns an audio stream description for a given ESDS. The specifier is an ESDS.
The value is a AudioStreamBasicDescription. If multiple formats can be described
by the ESDS this property will return the base level format.
@constant kAudioFormatProperty_ChannelLayoutFromESDS
Returns an audio channel layout for a given ESDS. The specifier is an
ESDS. The value is a AudioChannelLayout.
@constant kAudioFormatProperty_ASBDFromMPEGPacket
Returns an audio stream description for a given MPEG Packet. The specifier is an MPEG Packet.
The value is a AudioStreamBasicDescription.
@constant kAudioFormatProperty_FormatList
Returns a list of AudioFormatListItem structs describing the audio formats contained within the compressed bit stream
as described by the magic cookie. The specifier is an AudioFormatInfo struct. The mFormatID member of the
ASBD struct must filled in. Formats are returned in order from the most to least 'rich', with
channel count taking the highest precedence followed by sample rate. The kAudioFormatProperty_FormatList property
is the preferred method for discovering format information of the audio data. If the audio data can only be described
by a single AudioFormatListItem, this property would be equivalent to using the kAudioFormatProperty_FormatInfo property,
which should be used by the application as a fallback case, to ensure backward compatibility with existing systems
when kAudioFormatProperty_FormatList is not present on the running system.
@constant kAudioFormatProperty_OutputFormatList
Returns a list of AudioFormatListItem structs describing the audio formats which may be obtained by decoding the format
described by the specifier.
The specifier is an AudioFormatInfo struct. At a minimum formatID member of the ASBD struct must filled in. Other fields
may be filled in. If there is no magic cookie, then the number of channels and sample rate should be filled in.
@constant kAudioFormatProperty_FirstPlayableFormatFromList
The specifier is a list of 1 or more AudioFormatListItem. Generally it is the list of these items returned from kAudioFormatProperty_FormatList. The property value retrieved is an UInt32 that specifies an index into that list. The list that the caller provides is generally sorted with the first item as the best format (most number of channels, highest sample rate), and the returned index represents the first item in that list that can be played by the system.
Thus, the property is typically used to determine the best playable format for a given (layered) audio stream
@constant kAudioFormatProperty_ValidateChannelLayout
The specifier is an AudioChannelLayout. The property value and size are not used and must be set to NULL.
This property validates an AudioChannelLayout. This is useful if the layout has come from an untrusted source such as a file.
It returns noErr if the AudioChannelLayout is OK, kAudio_ParamError if there is a structural problem with the layout,
or kAudioFormatUnknownFormatError for unrecognized layout tags or channel labels.
@constant kAudioFormatProperty_ChannelLayoutForTag
Returns the channel descriptions for a standard channel layout.
The specifier is a AudioChannelLayoutTag (the mChannelLayoutTag field
of the AudioChannelLayout struct) containing the layout constant.
The value is an AudioChannelLayout structure. In typical use a AudioChannelLayout
can be valid with just a defined AudioChannelLayoutTag (ie, those layouts
have predefined speaker locations and orderings).
Returns an error if the tag is kAudioChannelLayoutTag_UseChannelBitmap
@constant kAudioFormatProperty_TagForChannelLayout
Returns an AudioChannelLayoutTag for a layout, if there is one.
The specifier is an AudioChannelLayout containing the layout description.
The value is an AudioChannelLayoutTag.
This can be used to reduce a layout specified by kAudioChannelLayoutTag_UseChannelDescriptions
or kAudioChannelLayoutTag_UseChannelBitmap to a known AudioChannelLayoutTag.
@constant kAudioFormatProperty_ChannelLayoutForBitmap
Returns the channel descriptions for a standard channel layout.
The specifier is a UInt32 (the mChannelBitmap field
of the AudioChannelLayout struct) containing the layout bitmap. The value
is an AudioChannelLayout structure. In some uses, an AudioChannelLayout can be
valid with the layoutTag set to "use bitmap" and the bitmap set appropriately.
@constant kAudioFormatProperty_BitmapForLayoutTag
Returns a bitmap for an AudioChannelLayoutTag, if there is one.
The specifier is a AudioChannelLayoutTag containing the layout tag.
The value is an UInt32 bitmap. The bits are as defined in CoreAudioTypes.h.
To go in the other direction, i.e. get a layout tag for a bitmap,
use kAudioFormatProperty_TagForChannelLayout where your layout tag
is kAudioChannelLayoutTag_UseChannelBitmap and the bitmap is filled in.
@constant kAudioFormatProperty_ChannelLayoutName
Returns the a name for a particular channel layout. The specifier is
an AudioChannelLayout containing the layout description. The value
is a CFStringRef. The caller is responsible for releasing the
returned string.
@constant kAudioFormatProperty_ChannelLayoutSimpleName
Returns the a simpler name for a channel layout than does kAudioFormatProperty_ChannelLayoutName.
It omits the channel labels from the name. The specifier is
an AudioChannelLayout containing the layout description. The value
is a CFStringRef. The caller is responsible for releasing the
returned string.
@constant kAudioFormatProperty_ChannelName
Returns the name for a particular channel. The specifier is an
AudioChannelDescription which has the mChannelLabel field set. The value
is a CFStringRef. The caller is responsible for releasing the
returned string.
@constant kAudioFormatProperty_ChannelShortName
Returns an abbreviated name for a particular channel. The specifier is an
AudioChannelDescription which has the mChannelLabel field set. The value
is a CFStringRef. The caller is responsible for releasing the
returned string.
@constant kAudioFormatProperty_MatrixMixMap
Returns a matrix of scaling coefficients for converting audio from one channel map
to another in a standard way, if one is known. Otherwise an error is returned.
The specifier is an array of two pointers to AudioChannelLayout structures.
The first points to the input layout, the second to the output layout.
The value is a two dimensional array of Float32 where the first dimension (rows)
is the input channel and the second dimension (columns) is the output channel.
@constant kAudioFormatProperty_ChannelMap
Returns an array of SInt32 for reordering input channels.
The specifier is an array of two pointers to AudioChannelLayout structures.
The first points to the input layout, the second to the output layout.
The length of the output array is equal to the number of output channels.
@constant kAudioFormatProperty_NumberOfChannelsForLayout
This is a general call for parsing a AudioChannelLayout provided as the specifier,
to determine the number of valid channels that are represented. So, if the
LayoutTag is specified, it returns the number of channels for that layout. If
the bitmap is specified, it returns the number of channels represented by that bitmap.
If the layout tag is 'kAudioChannelLayoutTag_UseChannelDescriptions' it returns
the number of channel descriptions.
@constant kAudioFormatProperty_AreChannelLayoutsEquivalent
Returns a UInt32 which is 1 if two layouts are equivalent and 0 if they are not equivalent.
In order to be equivalent, the layouts must describe the same channels in the same order.
Whether the layout is represented by a bitmap, channel descriptions or a channel layout tag is not significant.
The channel coordinates are only significant if the channel label is kAudioChannelLabel_UseCoordinates.
The specifier is an array of two pointers to AudioChannelLayout structures.
The value is a pointer to the UInt32 result.
@constant kAudioFormatProperty_ChannelLayoutHash
Returns a UInt32 which represents the hash of the provided channel layout.
The specifier is a pointer to an AudioChannelLayout structure.
The value is a pointer to the UInt32 result.
@constant kAudioFormatProperty_TagsForNumberOfChannels
returns an array of AudioChannelLayoutTags for the number of channels specified.
The specifier is a UInt32 number of channels.
@constant kAudioFormatProperty_PanningMatrix
This call will pass in an AudioPanningInfo struct that specifies one of the
kPanningMode_ constants for the panning algorithm and an AudioChannelLayout
to describe the destination channel layout. As in kAudioFormatProperty_MatrixMixMap
the return value is an array of Float32 values of the number of channels
represented by this specified channel layout. It is presumed that the source
being panned is mono (thus for a quad channel layout, 4 Float32 values are returned).
The intention of this API is to provide support for panning operations that are
strictly manipulating the respective volumes of the channels. Thus, more
complex panners (like HRTF, distance filtering etc,) will not be represented
by this API. The resultant volume scalars can then be applied to a mixer
or some other processing code to adapt the individual volumes of the mixed
output.
The volume values will typically be presented within a 0->1 range (where 1 is unity gain)
For stereo formats, vector based panning is equivalent to the equal-power pan mode.
@constant kAudioFormatProperty_BalanceFade
get an array of coefficients for applying left/right balance and front/back fade.
The specifier is an AudioBalanceFade struct.
the return value is an array of Float32 values of the number of channels
represented by this specified channel layout.
The volume values will typically be presented within a 0->1 range (where 1 is unity gain)
@constant kAudioFormatProperty_ID3TagSize
Returns a UInt32 indicating the ID3 tag size.
The specifier must begin with the ID3 tag header and be at least 10 bytes in length
@constant kAudioFormatProperty_ID3TagToDictionary
Returns a CFDictionary containing key/value pairs for the frames in the ID3 tag
The specifier is the entire ID3 tag
Caller must call CFRelease for the returned dictionary
*/
CF_ENUM(AudioFormatPropertyID)
{
//=============================================================================
// The following properties are concerned with the AudioStreamBasicDescription
//=============================================================================
kAudioFormatProperty_FormatInfo = 'fmti',
kAudioFormatProperty_FormatName = 'fnam',
kAudioFormatProperty_EncodeFormatIDs = 'acof',
kAudioFormatProperty_DecodeFormatIDs = 'acif',
kAudioFormatProperty_FormatList = 'flst',
kAudioFormatProperty_ASBDFromESDS = 'essd',
kAudioFormatProperty_ChannelLayoutFromESDS = 'escl',
kAudioFormatProperty_OutputFormatList = 'ofls',
kAudioFormatProperty_FirstPlayableFormatFromList = 'fpfl',
kAudioFormatProperty_FormatIsVBR = 'fvbr',
kAudioFormatProperty_FormatIsExternallyFramed = 'fexf',
kAudioFormatProperty_FormatEmploysDependentPackets = 'fdep',
kAudioFormatProperty_FormatIsEncrypted = 'cryp',
kAudioFormatProperty_Encoders = 'aven',
kAudioFormatProperty_Decoders = 'avde',
kAudioFormatProperty_AvailableEncodeBitRates = 'aebr',
kAudioFormatProperty_AvailableEncodeSampleRates = 'aesr',
kAudioFormatProperty_AvailableEncodeChannelLayoutTags = 'aecl',
kAudioFormatProperty_AvailableEncodeNumberChannels = 'avnc',
kAudioFormatProperty_AvailableDecodeNumberChannels = 'adnc',
kAudioFormatProperty_ASBDFromMPEGPacket = 'admp',
//=============================================================================
// The following properties concern the AudioChannelLayout struct (speaker layouts)
//=============================================================================
kAudioFormatProperty_BitmapForLayoutTag = 'bmtg',
kAudioFormatProperty_MatrixMixMap = 'mmap',
kAudioFormatProperty_ChannelMap = 'chmp',
kAudioFormatProperty_NumberOfChannelsForLayout = 'nchm',
kAudioFormatProperty_AreChannelLayoutsEquivalent = 'cheq',
kAudioFormatProperty_ChannelLayoutHash = 'chha',
kAudioFormatProperty_ValidateChannelLayout = 'vacl',
kAudioFormatProperty_ChannelLayoutForTag = 'cmpl',
kAudioFormatProperty_TagForChannelLayout = 'cmpt',
kAudioFormatProperty_ChannelLayoutName = 'lonm',
kAudioFormatProperty_ChannelLayoutSimpleName = 'lsnm',
kAudioFormatProperty_ChannelLayoutForBitmap = 'cmpb',
kAudioFormatProperty_ChannelName = 'cnam',
kAudioFormatProperty_ChannelShortName = 'csnm',
kAudioFormatProperty_TagsForNumberOfChannels = 'tagc',
kAudioFormatProperty_PanningMatrix = 'panm',
kAudioFormatProperty_BalanceFade = 'balf',
//=============================================================================
// The following properties concern the ID3 Tags
//=============================================================================
kAudioFormatProperty_ID3TagSize = 'id3s',
kAudioFormatProperty_ID3TagToDictionary = 'id3d'
};
#if TARGET_OS_IPHONE
CF_ENUM(AudioFormatPropertyID) {
kAudioFormatProperty_HardwareCodecCapabilities = 'hwcc',
} __attribute__((deprecated));
/*!
@enum AudioCodecComponentType
@discussion Collection of audio codec component types.
(On macOS these declarations are in AudioToolbox/AudioCodec.h).
@constant kAudioDecoderComponentType
A codec that translates data in some other format into linear PCM.
The component subtype specifies the format ID of the other format.
@constant kAudioEncoderComponentType
A codec that translates linear PCM data into some other format
The component subtype specifies the format ID of the other format
*/
CF_ENUM(UInt32)
{
kAudioDecoderComponentType = 'adec',
kAudioEncoderComponentType = 'aenc',
};
/*!
@enum AudioCodecComponentManufacturer
@discussion Audio codec component manufacturer codes. On iPhoneOS, a codec's
manufacturer can be used to distinguish between hardware and
software codecs.
@constant kAppleSoftwareAudioCodecManufacturer
Apple software audio codecs.
@constant kAppleHardwareAudioCodecManufacturer
Apple hardware audio codecs.
*/
CF_ENUM(UInt32)
{
kAppleSoftwareAudioCodecManufacturer = 'appl',
kAppleHardwareAudioCodecManufacturer = 'aphw'
};
#endif
//=============================================================================
// Routines
//=============================================================================
/*!
@function AudioFormatGetPropertyInfo
@abstract Retrieve information about the given property
@param inPropertyID an AudioFormatPropertyID constant.
@param inSpecifierSize The size of the specifier data.
@param inSpecifier A specifier is a buffer of data used as an input argument to some of the properties.
@param outPropertyDataSize The size in bytes of the current value of the property. In order to get the property value,
you will need a buffer of this size.
@result returns noErr if successful.
*/
extern OSStatus
AudioFormatGetPropertyInfo( AudioFormatPropertyID inPropertyID,
UInt32 inSpecifierSize,
const void * __nullable inSpecifier,
UInt32 * outPropertyDataSize) API_AVAILABLE(macos(10.3), ios(2.0), watchos(2.0), tvos(9.0));
/*!
@function AudioFormatGetProperty
@abstract Retrieve the indicated property data
@param inPropertyID an AudioFormatPropertyID constant.
@param inSpecifierSize The size of the specifier data.
@param inSpecifier A specifier is a buffer of data used as an input argument to some of the properties.
@param ioPropertyDataSize on input the size of the outPropertyData buffer. On output the number of bytes written to the buffer.
@param outPropertyData the buffer in which to write the property data. If outPropertyData is NULL and ioPropertyDataSize is
not, the amount that would have been written will be reported.
@result returns noErr if successful.
*/
extern OSStatus
AudioFormatGetProperty( AudioFormatPropertyID inPropertyID,
UInt32 inSpecifierSize,
const void * __nullable inSpecifier,
UInt32 * __nullable ioPropertyDataSize,
void * __nullable outPropertyData) API_AVAILABLE(macos(10.3), ios(2.0), watchos(2.0), tvos(9.0));
//-----------------------------------------------------------------------------
// AudioFormat Error Codes
//-----------------------------------------------------------------------------
CF_ENUM(OSStatus)
{
kAudioFormatUnspecifiedError = 'what', // 0x77686174, 2003329396
kAudioFormatUnsupportedPropertyError = 'prop', // 0x70726F70, 1886547824
kAudioFormatBadPropertySizeError = '!siz', // 0x2173697A, 561211770
kAudioFormatBadSpecifierSizeError = '!spc', // 0x21737063, 561213539
kAudioFormatUnsupportedDataFormatError = 'fmt?', // 0x666D743F, 1718449215
kAudioFormatUnknownFormatError = '!fmt' // 0x21666D74, 560360820
};
#if defined(__cplusplus)
}
#endif
CF_ASSUME_NONNULL_END
#endif // AudioToolbox_AudioFormat_h
#else
#include <AudioToolboxCore/AudioFormat.h>
#endif

View File

@@ -0,0 +1,259 @@
/*!
@file AudioHardwareService.h
@framework AudioToolbox.framework
@copyright (c) 2006-2015 by Apple, Inc., all rights reserved.
@abstract API's for general high level audio services.
@discussion
The Audio Hardware Service (AHS) provides a way for applications to query and manipulate the
aspects of an audio hardware device without incurring the overhead of loading the full audio
HAL. AHS provides access to all the AudioObjects and their properties on the system. However,
access is limited to only those properties that do not directly impact IO. For example, you can
query the device's format but you can't query its IO buffer size. As such, the AHS API directly
incorporates the various structures and constants in HAL's API, with the caveat that the
AudioObjectIDs used in AHS cannot be used with the HAL.
*/
#ifndef AudioHardwareService_h
#define AudioHardwareService_h
#if !TARGET_OS_IPHONE
#if !defined(__COREAUDIO_USE_FLAT_INCLUDES__)
#include <Availability.h>
#include <CoreAudio/AudioHardware.h>
#else
#include <AudioHardware.h>
#endif
#endif
#if !TARGET_OS_IPHONE
#if defined(__cplusplus)
extern "C"
{
#endif
//==================================================================================================
#pragma mark Audio Hardware Service Properties
/*!
@enum Audio Hardware Service Properties
@abstract AudioObjectPropertySelector values that apply to various kinds of AudioObjects
only when accessed via the Audio Hardware Service API.
@constant kAudioHardwareServiceProperty_ServiceRestarted
A Float32 whose value has no meaning. Rather, this property exists so that
clients can be informed when the service has been reset for some reason.
When a reset happens, any state the client has with AHS, such as cached data
or added listeners, must be re-established by the client.
@constant kAudioHardwareServiceDeviceProperty_VirtualMainVolume
A Float32 that represents the value of the volume control. The range is
between 0.0 and 1.0 (inclusive). This actual volume controls this property
manipulates depends on what the device provides. If the device has a true
main volume control, this property directly controls that. If the device
has individual channel volume controls, this property will apply to those
identified by the device's preferred multi-channel layout (or preferred
stereo pair if the device is stereo only). Note that this control maintains
the relative balance between all the channels it affects.
@constant kAudioHardwareServiceDeviceProperty_VirtualMainBalance
A Float32 that represents the value of the stereo balance control. The range
is from 0.0 (all power to the left) to 1.0 (all power to the right) with
the value of 0.5 signifying that the channels have equal power. This control
is only present for devices that have individual channel volume controls. It
manipulates the relative balance between the volume controls on the channels
identified as the device's default stereo pair.
*/
CF_ENUM(AudioObjectPropertySelector)
{
kAudioHardwareServiceProperty_ServiceRestarted = 'srst',
kAudioHardwareServiceDeviceProperty_VirtualMainVolume = 'vmvc',
kAudioHardwareServiceDeviceProperty_VirtualMasterVolume API_DEPRECATED_WITH_REPLACEMENT("kAudioHardwareServiceDeviceProperty_VirtualMainVolume", macos(10.5, 10.5)) API_UNAVAILABLE(ios, watchos, tvos) = kAudioHardwareServiceDeviceProperty_VirtualMainVolume,
kAudioHardwareServiceDeviceProperty_VirtualMainBalance = 'vmbc',
kAudioHardwareServiceDeviceProperty_VirtualMasterBalance API_DEPRECATED_WITH_REPLACEMENT("kAudioHardwareServiceDeviceProperty_VirtualMainBalance", macos(10.5, 10.5)) API_UNAVAILABLE(ios, watchos, tvos) = kAudioHardwareServiceDeviceProperty_VirtualMainBalance,
};
//==================================================================================================
#pragma mark Audio Hardware Service Functions
/*!
@functiongroup Audio Hardware Service
*/
/*!
@function AudioHardwareServiceHasProperty
@abstract Queries an AudioObject about whether or not it has the given property.
@param inObjectID
The AudioObject to query.
@param inAddress
An AudioObjectPropertyAddress indicating which property is being queried.
@result A Boolean indicating whether or not the AudioObject has the given property.
*/
extern Boolean
AudioHardwareServiceHasProperty( AudioObjectID inObjectID,
const AudioObjectPropertyAddress* inAddress)
API_DEPRECATED("no longer supported", macos(10.5, 10.11)) API_UNAVAILABLE(ios, watchos, tvos);
/*!
@function AudioHardwareServiceIsPropertySettable
@abstract Queries an AudioObject about whether or not the given property can be set using
AudioHardwareServiceSetPropertyData.
@param inObjectID
The AudioObject to query.
@param inAddress
An AudioObjectPropertyAddress indicating which property is being queried.
@param outIsSettable
A Boolean indicating whether or not the property can be set.
@result An OSStatus indicating success or failure.
*/
extern OSStatus
AudioHardwareServiceIsPropertySettable( AudioObjectID inObjectID,
const AudioObjectPropertyAddress* inAddress,
Boolean* outIsSettable)
API_DEPRECATED("no longer supported", macos(10.5, 10.11)) API_UNAVAILABLE(ios, watchos, tvos);
/*!
@function AudioHardwareServiceGetPropertyDataSize
@abstract Queries an AudioObject to find the size of the data for the given property.
@param inObjectID
The AudioObject to query.
@param inAddress
An AudioObjectPropertyAddress indicating which property is being queried.
@param inQualifierDataSize
A UInt32 indicating the size of the buffer pointed to by inQualifierData.
Note that not all properties require qualification, in which case this
value will be 0.
@param inQualifierData
A buffer of data to be used in determining the data of the property being
queried. Note that not all properties require qualification, in which case
this value will be NULL.
@param outDataSize
A UInt32 indicating how many bytes the data for the given property occupies.
@result An OSStatus indicating success or failure.
*/
extern OSStatus
AudioHardwareServiceGetPropertyDataSize( AudioObjectID inObjectID,
const AudioObjectPropertyAddress* inAddress,
UInt32 inQualifierDataSize,
const void* inQualifierData,
UInt32* outDataSize)
API_DEPRECATED("no longer supported", macos(10.5, 10.11)) API_UNAVAILABLE(ios, watchos, tvos);
/*!
@function AudioHardwareServiceGetPropertyData
@abstract Queries an AudioObject to get the data of the given property and places it in
the provided buffer.
@param inObjectID
The AudioObject to query.
@param inAddress
An AudioObjectPropertyAddress indicating which property is being queried.
@param inQualifierDataSize
A UInt32 indicating the size of the buffer pointed to by inQualifierData.
Note that not all properties require qualification, in which case this
value will be 0.
@param inQualifierData
A buffer of data to be used in determining the data of the property being
queried. Note that not all properties require qualification, in which case
this value will be NULL.
@param ioDataSize
A UInt32 which on entry indicates the size of the buffer pointed to by
outData and on exit indicates how much of the buffer was used.
@param outData
The buffer into which the AudioObject will put the data for the given
property.
@result An OSStatus indicating success or failure.
*/
extern OSStatus
AudioHardwareServiceGetPropertyData( AudioObjectID inObjectID,
const AudioObjectPropertyAddress* inAddress,
UInt32 inQualifierDataSize,
const void* inQualifierData,
UInt32* ioDataSize,
void* outData)
API_DEPRECATED("no longer supported", macos(10.5, 10.11)) API_UNAVAILABLE(ios, watchos, tvos);
/*!
@function AudioHardwareServiceSetPropertyData
@abstract Tells an AudioObject to change the value of the given property using the
provided data.
@discussion Note that the value of the property should not be considered changed until the
HAL has called the listeners as many properties values are changed
asynchronously.
@param inObjectID
The AudioObject to change.
@param inAddress
An AudioObjectPropertyAddress indicating which property is being changed.
@param inQualifierDataSize
A UInt32 indicating the size of the buffer pointed to by inQualifierData.
Note that not all properties require qualification, in which case this
value will be 0.
@param inQualifierData
A buffer of data to be used in determining the data of the property being
queried. Note that not all properties require qualification, in which case
this value will be NULL.
@param inDataSize
A UInt32 indicating the size of the buffer pointed to by inData.
@param inData
The buffer containing the data to be used to change the property's value.
@result An OSStatus indicating success or failure.
*/
extern OSStatus
AudioHardwareServiceSetPropertyData( AudioObjectID inObjectID,
const AudioObjectPropertyAddress* inAddress,
UInt32 inQualifierDataSize,
const void* inQualifierData,
UInt32 inDataSize,
const void* inData)
API_DEPRECATED("no longer supported", macos(10.5, 10.11)) API_UNAVAILABLE(ios, watchos, tvos);
/*!
@function AudioHardwareServiceAddPropertyListener
@abstract Registers the given AudioObjectPropertyListenerProc to receive notifications
when the given properties change.
@param inObjectID
The AudioObject to register the listener with.
@param inAddress
The AudioObjectPropertyAddresses indicating which property the listener
should be notified about.
@param inListener
The AudioObjectPropertyListenerProc to call.
@param inClientData
A pointer to client data that is passed to the listener when it is called.
@result An OSStatus indicating success or failure.
*/
extern OSStatus
AudioHardwareServiceAddPropertyListener( AudioObjectID inObjectID,
const AudioObjectPropertyAddress* inAddress,
AudioObjectPropertyListenerProc inListener,
void* inClientData)
API_DEPRECATED("no longer supported", macos(10.5, 10.11)) API_UNAVAILABLE(ios, watchos, tvos);
/*!
@function AudioHardwareServiceRemovePropertyListener
@abstract Unregisters the given AudioObjectPropertyListenerProc from receiving
notifications when the given properties change.
@param inObjectID
The AudioObject to unregister the listener from.
@param inAddress
The AudioObjectPropertyAddresses indicating which property the listener
will stop being notified about.
@param inListener
The AudioObjectPropertyListenerProc being removed.
@param inClientData
A pointer to client data that is passed to the listener when it is called.
@result An OSStatus indicating success or failure.
*/
extern OSStatus
AudioHardwareServiceRemovePropertyListener( AudioObjectID inObjectID,
const AudioObjectPropertyAddress* inAddress,
AudioObjectPropertyListenerProc inListener,
void* inClientData)
API_DEPRECATED("no longer supported", macos(10.5, 10.11)) API_UNAVAILABLE(ios, watchos, tvos);
#if defined(__cplusplus)
}
#endif
#endif //!TARGET_OS_IPHONE
#endif /* AudioHardwareService_h */

View File

@@ -0,0 +1,56 @@
#if (defined(__USE_PUBLIC_HEADERS__) && __USE_PUBLIC_HEADERS__) || (defined(USE_AUDIOTOOLBOX_PUBLIC_HEADERS) && USE_AUDIOTOOLBOX_PUBLIC_HEADERS) || !__has_include(<AudioToolboxCore/AudioOutputUnit.h>)
/*!
@file AudioOutputUnit.h
@framework AudioToolbox.framework
@copyright (c) 2000-2015 Apple, Inc. All rights reserved.
@brief Additional Audio Unit API for audio input/output units.
*/
#ifndef AudioUnit_AudioOutputUnit_h
#define AudioUnit_AudioOutputUnit_h
#include <AudioToolbox/AUComponent.h>
CF_ASSUME_NONNULL_BEGIN
#ifdef __cplusplus
extern "C" {
#endif
//-----------------------------------------------------------------------------
// Start/stop methods for output units
//-----------------------------------------------------------------------------
extern OSStatus
AudioOutputUnitStart( AudioUnit ci) API_AVAILABLE(macos(10.0), ios(2.0), watchos(2.0), tvos(9.0));
extern OSStatus
AudioOutputUnitStop( AudioUnit ci) API_AVAILABLE(macos(10.0), ios(2.0), watchos(2.0), tvos(9.0));
//-----------------------------------------------------------------------------
// Selectors for component and audio plugin calls
//-----------------------------------------------------------------------------
enum {
kAudioOutputUnitRange = 0x0200, // selector range
kAudioOutputUnitStartSelect = 0x0201,
kAudioOutputUnitStopSelect = 0x0202
};
/*!
*/
typedef OSStatus (*AudioOutputUnitStartProc) (void *self);
/*!
*/
typedef OSStatus (*AudioOutputUnitStopProc) (void *self);
#ifdef __cplusplus
}
#endif
CF_ASSUME_NONNULL_END
#endif /* AudioUnit_AudioOutputUnit_h */
#else
#include <AudioToolboxCore/AudioOutputUnit.h>
#endif

View File

@@ -0,0 +1,399 @@
/*!
@file AudioServices.h
@framework AudioToolbox.framework
@copyright (c) 2006-2015 by Apple, Inc., all rights reserved.
@abstract API's for general high level audio services.
@discussion
AudioServices provides a means to play audio for things such as UI sound effects.
*/
#ifndef AudioToolbox_AudioServices_h
#define AudioToolbox_AudioServices_h
//==================================================================================================
#pragma mark Includes
#include <TargetConditionals.h>
#include <Availability.h>
#if TARGET_OS_OSX
#include <CoreAudio/AudioHardware.h>
#include <AudioToolbox/AudioHardwareService.h>
#elif TARGET_OS_IOS && !TARGET_OS_MACCATALYST
#include <AudioToolbox/AudioSession.h>
#endif
#include <CoreFoundation/CoreFoundation.h>
//==================================================================================================
CF_ASSUME_NONNULL_BEGIN
#if defined(__cplusplus)
extern "C"
{
#endif
//==================================================================================================
#pragma mark AudioServices Error Constants
/*!
@enum AudioServices error codes
@abstract Error codes returned from the AudioServices portion of the API.
@constant kAudioServicesNoError
No error has occurred
@constant kAudioServicesUnsupportedPropertyError
The property is not supported.
@constant kAudioServicesBadPropertySizeError
The size of the property data was not correct.
@constant kAudioServicesBadSpecifierSizeError
The size of the specifier data was not correct.
@constant kAudioServicesSystemSoundUnspecifiedError
A SystemSound unspecified error has occurred.
@constant kAudioServicesSystemSoundClientTimedOutError
The SystemSound client message timed out
@constant kAudioServicesSystemSoundExceededMaximumDurationError
The SystemSound's duration exceeded the allowable threshold
*/
CF_ENUM(OSStatus)
{
kAudioServicesNoError = 0,
kAudioServicesUnsupportedPropertyError = 'pty?',
kAudioServicesBadPropertySizeError = '!siz',
kAudioServicesBadSpecifierSizeError = '!spc',
kAudioServicesSystemSoundUnspecifiedError = -1500,
kAudioServicesSystemSoundClientTimedOutError = -1501,
kAudioServicesSystemSoundExceededMaximumDurationError = -1502
};
//==================================================================================================
#pragma mark AudioServices Types
/*!
@typedef SystemSoundID
@abstract SystemSoundIDs are created by the System Sound client application
for playback of a provided AudioFile.
*/
typedef UInt32 SystemSoundID;
/*!
@typedef AudioServicesPropertyID
@abstract Type used for specifying an AudioServices property.
*/
typedef UInt32 AudioServicesPropertyID;
/*!
@typedef AudioServicesSystemSoundCompletionProc
@abstract A function to be executed when a SystemSoundID finishes playing.
@discussion AudioServicesSystemSoundCompletionProc may be provided by client application to be
called when a SystemSoundID has completed playback.
@param ssID
The SystemSoundID that completed playback
@param clientData
Client application user data
*/
typedef void
(*AudioServicesSystemSoundCompletionProc)( SystemSoundID ssID,
void* __nullable clientData);
//==================================================================================================
#pragma mark AudioServices Constants
#if !TARGET_OS_IPHONE
/*!
@enum AudioServices constants
@abstract Constants for use with System Sound portion of the AudioServices APIs.
@constant kSystemSoundID_UserPreferredAlert
Use this constant with the play sound APIs to
playback the alert sound selected by the User in System Preferences.
@constant kSystemSoundID_FlashScreen
Use this constant with the play sound APIs to flash the screen
- Desktop systems only
*/
CF_ENUM(SystemSoundID)
{
kSystemSoundID_UserPreferredAlert = 0x00001000,
kSystemSoundID_FlashScreen = 0x00000FFE,
// this has been renamed to be consistent
kUserPreferredAlert = kSystemSoundID_UserPreferredAlert
};
#endif
/*!
@enum AudioServices constants
@constant kSystemSoundID_Vibrate
Use this constant with the play sound APIs to vibrate the device
- iOS only
- on a device with no vibration capability (like iPod Touch) this will
do nothing
*/
CF_ENUM(SystemSoundID)
{
kSystemSoundID_Vibrate = 0x00000FFF
};
//==================================================================================================
#pragma mark AudioServices Properties
/*!
@enum AudioServices property codes
@abstract These are the property codes used with the AudioServices API.
@constant kAudioServicesPropertyIsUISound
a UInt32 where 1 means that the SystemSoundID passed in the
inSpecifier parameter will respect the 'Play user interface sounds effects'
check box in System Preferences and be silent when the user turns off UI
sounds. This property is set to 1 by default. Set to 0 if it is desired for
an SystemSoundID to always be heard when passed to AudioServicesPlaySystemSound(),
regardless of user's setting in the Sound Preferences.
@constant kAudioServicesPropertyCompletePlaybackIfAppDies
a UInt32 where 1 means that the SystemSoundID passed in the
inSpecifier parameter will finish playing even if the client application goes away.
*/
CF_ENUM(AudioServicesPropertyID)
{
kAudioServicesPropertyIsUISound = 'isui',
kAudioServicesPropertyCompletePlaybackIfAppDies = 'ifdi'
};
//==================================================================================================
#pragma mark AudioServices Functions
/*!
@functiongroup AudioServices
*/
/*!
@function AudioServicesCreateSystemSoundID
@abstract Allows the application to designate an audio file for playback by the System Sound server.
@discussion Returned SystemSoundIDs are passed to AudioServicesPlayAlertSoundWithCompletion()
and AudioServicesPlaySystemSoundWithCompletion() to be played.
The maximum supported duration for a system sound is 30 secs.
@param inFileURL
A CFURLRef for an AudioFile.
@param outSystemSoundID
Returns a SystemSoundID.
*/
extern OSStatus
AudioServicesCreateSystemSoundID( CFURLRef inFileURL,
SystemSoundID* outSystemSoundID)
API_AVAILABLE(macos(10.5), ios(2.0), watchos(2.0), tvos(9.0))
;
/*!
@function AudioServicesDisposeSystemSoundID
@abstract Allows the System Sound server to dispose any resources needed for the provided
SystemSoundID.
@discussion Allows the application to tell the System Sound server that the resources for the
associated audio file are no longer required.
@param inSystemSoundID
A SystemSoundID that the application no longer needs to use.
*/
extern OSStatus
AudioServicesDisposeSystemSoundID(SystemSoundID inSystemSoundID)
API_AVAILABLE(macos(10.5), ios(2.0), watchos(2.0), tvos(9.0))
;
/*!
@function AudioServicesPlayAlertSoundWithCompletion
@abstract Play an alert sound
@discussion Play the sound designated by the provided SystemSoundID with alert sound behavior.
@param inSystemSoundID
The SystemSoundID to be played. On the desktop the kSystemSoundID_UserPreferredAlert
constant can be passed in to play back the alert sound selected by the user
in System Preferences. On iOS there is no preferred user alert sound.
@param inCompletionBlock
The completion block gets executed for every attempt to play a system sound irrespective
of success or failure. The callbacks are issued on a serial queue and the client is
responsible for handling thread safety.
*/
extern void
AudioServicesPlayAlertSoundWithCompletion( SystemSoundID inSystemSoundID,
void (^__nullable inCompletionBlock)(void))
API_AVAILABLE(macos(10.11), ios(9.0), watchos(2.0), tvos(9.0))
;
/*!
@function AudioServicesPlaySystemSoundWithCompletion
@abstract Play a system sound
@discussion Play the sound designated by the provided SystemSoundID.
@param inSystemSoundID
The SystemSoundID to be played.
@param inCompletionBlock
The completion block gets executed for every attempt to play a system sound irrespective
of success or failure. The callbacks are issued on a serial queue and the client is
responsible for handling thread safety.
*/
extern void
AudioServicesPlaySystemSoundWithCompletion( SystemSoundID inSystemSoundID,
void (^__nullable inCompletionBlock)(void))
API_AVAILABLE(macos(10.11), ios(9.0), watchos(2.0), tvos(9.0))
;
/*!
@function AudioServicesGetPropertyInfo
@abstract Get information about the size of an AudioServices property and whether it can
be set.
@param inPropertyID
a AudioServicesPropertyID constant.
@param inSpecifierSize
The size of the specifier data.
@param inSpecifier
A specifier is a buffer of data used as an input argument to some of the
properties.
@param outPropertyDataSize
The size in bytes of the current value of the property. In order to get the
property value, you will need a buffer of this size.
@param outWritable
Will be set to 1 if writable, or 0 if read only.
@result returns kAudioServicesNoError if successful.
*/
extern OSStatus
AudioServicesGetPropertyInfo( AudioServicesPropertyID inPropertyID,
UInt32 inSpecifierSize,
const void * __nullable inSpecifier,
UInt32 * __nullable outPropertyDataSize,
Boolean * __nullable outWritable)
API_AVAILABLE(macos(10.5), ios(2.0), watchos(2.0), tvos(9.0))
;
/*!
@function AudioServicesGetProperty
@abstract Retrieve the indicated property data
@param inPropertyID
a AudioServicesPropertyID constant.
@param inSpecifierSize
The size of the specifier data.
@param inSpecifier
A specifier is a buffer of data used as an input argument to some of the
properties.
@param ioPropertyDataSize
On input, the size of the outPropertyData buffer. On output the number of
bytes written to the buffer.
@param outPropertyData
The buffer in which to write the property data. May be NULL if caller only
wants ioPropertyDataSize to be filled with the amount that would have been
written.
@result returns kAudioServicesNoError if successful.
*/
extern OSStatus
AudioServicesGetProperty( AudioServicesPropertyID inPropertyID,
UInt32 inSpecifierSize,
const void * __nullable inSpecifier,
UInt32 * ioPropertyDataSize,
void * __nullable outPropertyData)
API_AVAILABLE(macos(10.5), ios(2.0), watchos(2.0), tvos(9.0))
;
/*!
@function AudioServicesSetProperty
@abstract Set the indicated property data
@param inPropertyID
a AudioServicesPropertyID constant.
@param inSpecifierSize
The size of the specifier data.
@param inSpecifier
A specifier is a buffer of data used as an input argument to some of the
properties.
@param inPropertyDataSize
The size of the inPropertyData buffer.
@param inPropertyData
The buffer containing the property data.
@result returns kAudioServicesNoError if successful.
*/
extern OSStatus
AudioServicesSetProperty( AudioServicesPropertyID inPropertyID,
UInt32 inSpecifierSize,
const void * __nullable inSpecifier,
UInt32 inPropertyDataSize,
const void * inPropertyData)
API_AVAILABLE(macos(10.5), ios(2.0), watchos(2.0), tvos(9.0))
;
/*!
This function will be deprecated in a future release. Use AudioServicesPlayAlertSoundWithCompletion instead.
@function AudioServicesPlayAlertSound
@abstract Play an Alert Sound
@discussion Play the provided SystemSoundID with AlertSound behavior.
@param inSystemSoundID
A SystemSoundID for the System Sound server to play. On the desktop you
can pass the kSystemSoundID_UserPreferredAlert constant to playback the alert sound
selected by the user in System Preferences. On iOS there is no preferred user alert sound.
*/
extern void
AudioServicesPlayAlertSound(SystemSoundID inSystemSoundID)
API_AVAILABLE(macos(10.5), ios(2.0), watchos(2.0), tvos(9.0))
;
/*!
This function will be deprecated in a future release. Use AudioServicesPlaySystemSoundWithCompletion instead.
@function AudioServicesPlaySystemSound
@abstract Play the sound designated by the provided SystemSoundID.
@discussion A SystemSoundID indicating the desired System Sound to be played.
@param inSystemSoundID
A SystemSoundID for the System Sound server to play.
*/
extern void
AudioServicesPlaySystemSound(SystemSoundID inSystemSoundID)
API_AVAILABLE(macos(10.5), ios(2.0), watchos(2.0), tvos(9.0))
;
/*!
This function will be deprecated in a future release. Use AudioServicesPlayAlertSoundWithCompletion
or AudioServicesPlaySystemSoundWithCompletion instead.
@function AudioServicesAddSystemSoundCompletion
@abstract Call the provided Completion Routine when provided SystemSoundID
finishes playing.
@discussion Once set, the System Sound server will send a message to the System Sound client
indicating which SystemSoundID has finished playing.
@param inSystemSoundID
The SystemSoundID to associate with the provided completion
routine.
@param inRunLoop
A CFRunLoopRef indicating the desired run loop the completion routine should
be run on. Pass NULL to use the main run loop.
@param inRunLoopMode
A CFStringRef indicating the run loop mode for the runloop where the
completion routine will be executed. Pass NULL to use kCFRunLoopDefaultMode.
@param inCompletionRoutine
An AudioServicesSystemSoundCompletionProc to be called when the provided
SystemSoundID has completed playing in the server.
@param inClientData
A void* to pass client data to the completion routine.
*/
extern OSStatus
AudioServicesAddSystemSoundCompletion( SystemSoundID inSystemSoundID,
CFRunLoopRef __nullable inRunLoop,
CFStringRef __nullable inRunLoopMode,
AudioServicesSystemSoundCompletionProc inCompletionRoutine,
void * __nullable inClientData)
API_AVAILABLE(macos(10.5), ios(2.0), watchos(2.0), tvos(9.0))
;
/*!
This function will be deprecated in a future release. Use AudioServicesPlayAlertSoundWithCompletion
or AudioServicesPlaySystemSoundWithCompletion instead.
@function AudioServicesRemoveSystemSoundCompletion
@abstract Disassociate any completion proc for the specified SystemSoundID
@discussion Tells the SystemSound client to remove any completion proc associated with the
provided SystemSoundID
@param inSystemSoundID
The SystemSoundID for which completion routines should be
removed.
*/
extern void
AudioServicesRemoveSystemSoundCompletion(SystemSoundID inSystemSoundID)
API_AVAILABLE(macos(10.5), ios(2.0), watchos(2.0), tvos(9.0))
;
CF_ASSUME_NONNULL_END
#ifdef __cplusplus
}
#endif
#endif /* AudioToolbox_AudioServices_h */

View File

@@ -0,0 +1,863 @@
/*==================================================================================================
File: AudioToolbox/AudioSession.h
Contains: API for audio session services.
Copyright: (c) 2006 - 2013 by Apple, Inc., all rights reserved.
Bugs?: For bug reports, consult the following page on
the World Wide Web:
http://developer.apple.com/bugreporter/
==================================================================================================*/
#if !defined(__AudioSession_h__)
#define __AudioSession_h__
//==================================================================================================
/*!
@header AudioSession
This header describes the API for audio session services.
Note: As of iOS 7, this entire API has been deprecated in favor of AVAudioSession, part of the AVFoundation framework.
*/
//==================================================================================================
#pragma mark Includes
#include <TargetConditionals.h>
#include <Availability.h>
#if !defined(__COREAUDIO_USE_FLAT_INCLUDES__)
#if !TARGET_OS_IPHONE
#include <CoreAudio/AudioHardware.h>
#endif
#include <CoreFoundation/CoreFoundation.h>
#else
#include <AudioHardware.h>
#include <CFRunLoop.h>
#include <CFString.h>
#include <CFURL.h>
#endif
//==================================================================================================
#if defined(__cplusplus)
extern "C"
{
#endif
//==================================================================================================
#pragma mark -
#pragma mark AudioSession Error Constants
/*!
@enum AudioSession error codes
@abstract Error codes returned from the AudioSession portion of the API.
@constant kAudioSessionNoError
No error has occurred
@constant kAudioSessionNotInitialized
This error is returned when the AudioSessionInitialize function
was not called prior to calling any other AudioSession function.
@constant kAudioSessionAlreadyInitialized
This error is returned when you call AudioSessionInitialize more than once.
@constant kAudioSessionInitializationError
This error indicates an AudioSession initialization error.
@constant kAudioSessionUnsupportedPropertyError
The property is not supported. This error code can also be used to
indicate that a bad property value was passed in a SetProperty call,
an attempt was made to set a read-only property, an attempt was made to
read a write-only property, an attempt was made to read a property that
is only available by way of a property listener, or an attempt was made
to set a listener on a property for which listeners are not supported.
@constant kAudioSessionBadPropertySizeError
The size of the property data was not correct.
@constant kAudioSessionNotActiveError
The operation failed because the AudioSession is not active.
Calling AudioSessionSetActive(true) first will fix this error in most cases.
@constant kAudioSessionNoCategorySet
The requested operation failed because it requires that the session have had an
audio category explicitly set, and none was set.
@constant kAudioSessionIncompatibleCategory
The requested operation failed because the AudioSession has an incompatible
category (e.g. attempting to play or record when the category is AudioProcessing) or
the session is not active.
@constant kAudioSessionUnspecifiedError
An audio session unspecified error has occurred.
*/
enum
{
kAudioSessionNoError = 0,
kAudioSessionNotInitialized = '!ini',
kAudioSessionAlreadyInitialized = 'init',
kAudioSessionInitializationError = 'ini?',
kAudioSessionUnsupportedPropertyError = 'pty?',
kAudioSessionBadPropertySizeError = '!siz',
kAudioSessionNotActiveError = '!act',
kAudioServicesNoHardwareError = 'nohw',
kAudioSessionNoCategorySet = '?cat',
kAudioSessionIncompatibleCategory = '!cat',
kAudioSessionUnspecifiedError = 'what'
};
//==================================================================================================
#pragma mark -
#pragma mark AudioSession Types
/*!
@typedef AudioSessionPropertyID
@abstract Type used for specifying an AudioSession property.
*/
typedef UInt32 AudioSessionPropertyID;
//==================================================================================================
#pragma mark -
#pragma mark AudioSession Interruption States
/*!
@enum AudioSession interruptions states
@abstract These are used with the AudioSessionInterruptionListener to indicate
if an interruption begins or ends.
@constant kAudioSessionBeginInterruption
Indicates that this AudioSession has just been interrupted.
@constant kAudioSessionEndInterruption
Indicates the end of an interruption.
*/
enum {
kAudioSessionBeginInterruption = 1,
kAudioSessionEndInterruption = 0
};
//==================================================================================================
#pragma mark -
#pragma mark AudioSession Audio Categories
/*!
@enum AudioSession audio categories states
@abstract These are used with as values for the kAudioSessionProperty_AudioCategory property
to indicate the audio category of the AudioSession.
@constant kAudioSessionCategory_AmbientSound
Use this category for background sounds such as rain, car engine noise, etc.
Mixes with other music.
@constant kAudioSessionCategory_SoloAmbientSound
Use this category for background sounds. Other music will stop playing.
@constant kAudioSessionCategory_MediaPlayback
Use this category for music tracks.
@constant kAudioSessionCategory_RecordAudio
Use this category when recording audio.
@constant kAudioSessionCategory_PlayAndRecord
Use this category when recording and playing back audio.
@constant kAudioSessionCategory_AudioProcessing
Use this category when using a hardware codec or signal processor while
not playing or recording audio.
*/
enum {
kAudioSessionCategory_AmbientSound = 'ambi',
kAudioSessionCategory_SoloAmbientSound = 'solo',
kAudioSessionCategory_MediaPlayback = 'medi',
kAudioSessionCategory_RecordAudio = 'reca',
kAudioSessionCategory_PlayAndRecord = 'plar',
kAudioSessionCategory_AudioProcessing = 'proc'
};
#pragma mark AudioSession Audio Category Routing Overrides
/*!
@enum AudioSession audio category routing overrides
@abstract These are used with as values for the kAudioSessionProperty_OverrideAudioRoute property.
@constant kAudioSessionOverrideAudioRoute_None
No override. Return audio routing to the default state for the current audio category.
@constant kAudioSessionOverrideAudioRoute_Speaker
Route audio output to speaker. Use this override with the kAudioSessionCategory_PlayAndRecord
category, which by default routes the output to the receiver.
*/
enum {
kAudioSessionOverrideAudioRoute_None = 0,
kAudioSessionOverrideAudioRoute_Speaker = 'spkr'
};
//==================================================================================================
#pragma mark AudioSession reason codes for route change
/*!
@enum AudioSession reason codes for route change
@abstract These are codes used when the kAudioSessionProperty_AudioRoute property changes
@constant kAudioSessionRouteChangeReason_Unknown
The reason is unknown.
@constant kAudioSessionRouteChangeReason_NewDeviceAvailable
A new device became available (e.g. headphones have been plugged in).
@constant kAudioSessionRouteChangeReason_OldDeviceUnavailable
The old device became unavailable (e.g. headphones have been unplugged).
@constant kAudioSessionRouteChangeReason_CategoryChange
The audio category has changed (e.g. kAudioSessionCategory_MediaPlayback
has been changed to kAudioSessionCategory_PlayAndRecord).
@constant kAudioSessionRouteChangeReason_Override
The route has been overridden (e.g. category is kAudioSessionCategory_PlayAndRecord
and the output has been changed from the receiver, which is the default, to the speaker).
@constant kAudioSessionRouteChangeReason_WakeFromSleep
The device woke from sleep.
@constant kAudioSessionRouteChangeReason_NoSuitableRouteForCategory
Returned when there is no route for the current category (for instance RecordCategory
but no input device)
@constant kAudioSessionRouteChangeReason_RouteConfigurationChange
Indicates that the set of input and/our output ports has not changed, but some aspect of their
configuration has changed. For example, a port's selected data source has changed.
*/
enum {
kAudioSessionRouteChangeReason_Unknown = 0,
kAudioSessionRouteChangeReason_NewDeviceAvailable = 1,
kAudioSessionRouteChangeReason_OldDeviceUnavailable = 2,
kAudioSessionRouteChangeReason_CategoryChange = 3,
kAudioSessionRouteChangeReason_Override = 4,
kAudioSessionRouteChangeReason_WakeFromSleep = 6,
kAudioSessionRouteChangeReason_NoSuitableRouteForCategory = 7,
kAudioSessionRouteChangeReason_RouteConfigurationChange = 8
};
// see documentation for kAudioSessionProperty_AudioRouteChange
// Note: the string refers to "OutputDevice" for historical reasons. Audio routes may contain zero or more inputs and
// zero or more outputs.
#define kAudioSession_AudioRouteChangeKey_Reason "OutputDeviceDidChange_Reason"
// CFString version of kAudioSession_AudioRouteChangeKey_Reason. This is more convenient to use than the raw string version.
// Available in iOS 5.0 or greater
extern const CFStringRef kAudioSession_RouteChangeKey_Reason API_DEPRECATED("no longer supported", ios(5.0, 7.0), macCatalyst(14.0, 14.0)) API_UNAVAILABLE(macos) __WATCHOS_PROHIBITED __TVOS_PROHIBITED;
// CFDictionary keys for kAudioSessionProperty_AudioRouteChange
// Available in iOS 5.0 or greater
extern const CFStringRef kAudioSession_AudioRouteChangeKey_PreviousRouteDescription API_DEPRECATED("no longer supported", ios(5.0, 7.0), macCatalyst(14.0, 14.0)) API_UNAVAILABLE(macos) __WATCHOS_PROHIBITED __TVOS_PROHIBITED;
extern const CFStringRef kAudioSession_AudioRouteChangeKey_CurrentRouteDescription API_DEPRECATED("no longer supported", ios(5.0, 7.0), macCatalyst(14.0, 14.0)) API_UNAVAILABLE(macos) __WATCHOS_PROHIBITED __TVOS_PROHIBITED;
// CFDictionary keys for kAudioSessionProperty_AudioRouteDescription
// Available in iOS 5.0 or greater
extern const CFStringRef kAudioSession_AudioRouteKey_Inputs API_DEPRECATED("no longer supported", ios(5.0, 7.0), macCatalyst(14.0, 14.0)) API_UNAVAILABLE(macos) __WATCHOS_PROHIBITED __TVOS_PROHIBITED;
extern const CFStringRef kAudioSession_AudioRouteKey_Outputs API_DEPRECATED("no longer supported", ios(5.0, 7.0), macCatalyst(14.0, 14.0)) API_UNAVAILABLE(macos) __WATCHOS_PROHIBITED __TVOS_PROHIBITED;
// key(s) for the CFDictionary associated with each entry of the CFArrays returned by kAudioSession_AudioRouteKey_Inputs
// and kAudioSession_AudioRouteKey_Outputs.
// Available in iOS 5.0 or greater
extern const CFStringRef kAudioSession_AudioRouteKey_Type API_DEPRECATED("no longer supported", ios(5.0, 7.0), macCatalyst(14.0, 14.0)) API_UNAVAILABLE(macos) __WATCHOS_PROHIBITED __TVOS_PROHIBITED;
/*!
@enum AudioSession route input types
@abstract These are the strings used with the kAudioSession_AudioRouteKey_Type key for the CFDictionary associated
with kAudioSession_AudioRouteKey_Inputs.
Available in iOS 5.0 or greater
@constant kAudioSessionInputRoute_LineIn
A line in input
@constant kAudioSessionInputRoute_BuiltInMic
A built-in microphone input. (Note that some devices like early iPods do not have this input)
@constant kAudioSessionInputRoute_HeadsetMic
A microphone that is part of a headset (combined microphone and headphones)
@constant kAudioSessionInputRoute_BluetoothHFP
A microphone that is part of a Bluetooth Hands-Free Profile device
@constant kAudioSessionInputRoute_USBAudio
A Universal Serial Bus input
*/
extern const CFStringRef kAudioSessionInputRoute_LineIn API_DEPRECATED("no longer supported", ios(5.0, 7.0), macCatalyst(14.0, 14.0)) API_UNAVAILABLE(macos) __WATCHOS_PROHIBITED __TVOS_PROHIBITED;
extern const CFStringRef kAudioSessionInputRoute_BuiltInMic API_DEPRECATED("no longer supported", ios(5.0, 7.0), macCatalyst(14.0, 14.0)) API_UNAVAILABLE(macos) __WATCHOS_PROHIBITED __TVOS_PROHIBITED;
extern const CFStringRef kAudioSessionInputRoute_HeadsetMic API_DEPRECATED("no longer supported", ios(5.0, 7.0), macCatalyst(14.0, 14.0)) API_UNAVAILABLE(macos) __WATCHOS_PROHIBITED __TVOS_PROHIBITED;
extern const CFStringRef kAudioSessionInputRoute_BluetoothHFP API_DEPRECATED("no longer supported", ios(5.0, 7.0), macCatalyst(14.0, 14.0)) API_UNAVAILABLE(macos) __WATCHOS_PROHIBITED __TVOS_PROHIBITED;
extern const CFStringRef kAudioSessionInputRoute_USBAudio API_DEPRECATED("no longer supported", ios(5.0, 7.0), macCatalyst(14.0, 14.0)) API_UNAVAILABLE(macos) __WATCHOS_PROHIBITED __TVOS_PROHIBITED;
/*!
@enum AudioSession route output types
@abstract These are strings used with the kAudioSession_AudioRouteKey_Type key for the CFDictionary associated
with kAudioSession_AudioRouteKey_Outputs.
Available in iOS 5.0 or greater
@constant kAudioSessionOutputRoute_LineOut
A line out output
@constant kAudioSessionOutputRoute_Headphones
Speakers in a headset (mic and headphones) or simple headphones
@constant kAudioSessionOutputRoute_BluetoothHFP
Speakers that are part of a Bluetooth Hands-Free Profile device
@constant kAudioSessionOutputRoute_BluetoothA2DP
Speakers in a Bluetooth A2DP device
@constant kAudioSessionOutputRoute_BuiltInReceiver
The speaker you hold to your ear when on a phone call
@constant kAudioSessionOutputRoute_BuiltInSpeaker
The built-in speaker
@constant kAudioSessionOutputRoute_USBAudio
Speaker(s) in a Universal Serial Bus device
@constant kAudioSessionOutputRoute_HDMI
Output via High-Definition Multimedia Interface
@constant kAudioSessionOutputRoute_AirPlay
Output on a remote Air Play device
*/
extern const CFStringRef kAudioSessionOutputRoute_LineOut API_DEPRECATED("no longer supported", ios(5.0, 7.0), macCatalyst(14.0, 14.0)) API_UNAVAILABLE(macos) __WATCHOS_PROHIBITED __TVOS_PROHIBITED;
extern const CFStringRef kAudioSessionOutputRoute_Headphones API_DEPRECATED("no longer supported", ios(5.0, 7.0), macCatalyst(14.0, 14.0)) API_UNAVAILABLE(macos) __WATCHOS_PROHIBITED __TVOS_PROHIBITED;
extern const CFStringRef kAudioSessionOutputRoute_BluetoothHFP API_DEPRECATED("no longer supported", ios(5.0, 7.0), macCatalyst(14.0, 14.0)) API_UNAVAILABLE(macos) __WATCHOS_PROHIBITED __TVOS_PROHIBITED;
extern const CFStringRef kAudioSessionOutputRoute_BluetoothA2DP API_DEPRECATED("no longer supported", ios(5.0, 7.0), macCatalyst(14.0, 14.0)) API_UNAVAILABLE(macos) __WATCHOS_PROHIBITED __TVOS_PROHIBITED;
extern const CFStringRef kAudioSessionOutputRoute_BuiltInReceiver API_DEPRECATED("no longer supported", ios(5.0, 7.0), macCatalyst(14.0, 14.0)) API_UNAVAILABLE(macos) __WATCHOS_PROHIBITED __TVOS_PROHIBITED;
extern const CFStringRef kAudioSessionOutputRoute_BuiltInSpeaker API_DEPRECATED("no longer supported", ios(5.0, 7.0), macCatalyst(14.0, 14.0)) API_UNAVAILABLE(macos) __WATCHOS_PROHIBITED __TVOS_PROHIBITED;
extern const CFStringRef kAudioSessionOutputRoute_USBAudio API_DEPRECATED("no longer supported", ios(5.0, 7.0), macCatalyst(14.0, 14.0)) API_UNAVAILABLE(macos) __WATCHOS_PROHIBITED __TVOS_PROHIBITED;
extern const CFStringRef kAudioSessionOutputRoute_HDMI API_DEPRECATED("no longer supported", ios(5.0, 7.0), macCatalyst(14.0, 14.0)) API_UNAVAILABLE(macos) __WATCHOS_PROHIBITED __TVOS_PROHIBITED;
extern const CFStringRef kAudioSessionOutputRoute_AirPlay API_DEPRECATED("no longer supported", ios(5.0, 7.0), macCatalyst(14.0, 14.0)) API_UNAVAILABLE(macos) __WATCHOS_PROHIBITED __TVOS_PROHIBITED;
// CFDictionary keys for kAudioSessionProperty_InputSources
extern const CFStringRef kAudioSession_InputSourceKey_ID API_DEPRECATED("no longer supported", ios(5.0, 7.0), macCatalyst(14.0, 14.0)) API_UNAVAILABLE(macos) __WATCHOS_PROHIBITED __TVOS_PROHIBITED;
extern const CFStringRef kAudioSession_InputSourceKey_Description API_DEPRECATED("no longer supported", ios(5.0, 7.0), macCatalyst(14.0, 14.0)) API_UNAVAILABLE(macos) __WATCHOS_PROHIBITED __TVOS_PROHIBITED;
// CFDictionary keys for kAudioSessionProperty_OutputDestinations
extern const CFStringRef kAudioSession_OutputDestinationKey_ID API_DEPRECATED("no longer supported", ios(5.0, 7.0), macCatalyst(14.0, 14.0)) API_UNAVAILABLE(macos) __WATCHOS_PROHIBITED __TVOS_PROHIBITED;
extern const CFStringRef kAudioSession_OutputDestinationKey_Description API_DEPRECATED("no longer supported", ios(5.0, 7.0), macCatalyst(14.0, 14.0)) API_UNAVAILABLE(macos) __WATCHOS_PROHIBITED __TVOS_PROHIBITED;
//==================================================================================================
#pragma mark AudioSession interruption types for end interruption events
/*!
@enum AudioSession Interruption types
@abstract When an app's AudioSessionInterruptionListener is called at the end of an interruption event,
the app may query to see if it should resume audio or not. The interruption type can be
obtained through the kAudioSessionProperty_InterruptionType, available in iOS 4.0 and
greater.
@constant kAudioSessionInterruptionType_ShouldResume
Indicates that the interruption was one where it is appropriate to resume playback
at the conclusion of the interruption. (e.g.: a phone call was rejected)
@constant kAudioSessionInterruptionType_ShouldNotResume
Indicates that the interruption was one where it is not appropriate to resume playback
at the conclusion of the interruption. (e.g.: interruption due to iPod playback)
*/
enum { // typedef UInt32 AudioSessionInterruptionType
kAudioSessionInterruptionType_ShouldResume = 'irsm',
kAudioSessionInterruptionType_ShouldNotResume = '!rsm'
};
typedef UInt32 AudioSessionInterruptionType;
//==================================================================================================
#pragma mark AudioSession mode values
/*!
@enum AudioSession Modes
@abstract Modes modify the audio category in order to introduce behavior that is tailored to the specific
use of audio within an application. Available in iOS 5.0 and greater.
@constant kAudioSessionMode_Default
The default mode.
@constant kAudioSessionMode_VoiceChat
Only valid with kAudioSessionCategory_PlayAndRecord. Appropriate for Voice Over IP
(VOIP) applications. Reduces the number of allowable audio routes to be only those
that are appropriate for VOIP applications and may engage appropriate system-supplied
signal processing. Has the side effect of setting
kAudioSessionProperty_OverrideCategoryEnableBluetoothInput to true.
@constant kAudioSessionMode_VideoRecording
Only valid with kAudioSessionCategory_PlayAndRecord or kAudioSessionCategory_RecordAudio.
Modifies the audio routing options and may engage appropriate system-supplied signal processing.
@constant kAudioSessionMode_Measurement
Appropriate for applications that wish to minimize the effect of system-supplied signal
processing for input and/or output audio signals.
@constant kAudioSessionMode_GameChat
Set by Game Kit on behalf of an application that uses a GKVoiceChat object; valid
only with the kAudioSessionCategory_PlayAndRecord category.
Do not set this mode directly. If you need similar behavior and are not using
a GKVoiceChat object, use the kAudioSessionMode_VoiceChat mode.
*/
enum {
kAudioSessionMode_Default = 'dflt',
kAudioSessionMode_VoiceChat = 'vcct',
kAudioSessionMode_VideoRecording = 'vrcd',
kAudioSessionMode_Measurement = 'msmt',
kAudioSessionMode_GameChat = 'gmct'
};
//==================================================================================================
#pragma mark AudioSession Properties
/*!
@enum AudioSession property codes
@abstract These are the property codes used with the AudioSession API.
@constant kAudioSessionProperty_PreferredHardwareSampleRate
A Float64 indicating the preferred hardware sample rate for the AudioSession.
The actual sample rate may be different
@constant kAudioSessionProperty_PreferredHardwareIOBufferDuration
A Float32 indicating the preferred hardware IO buffer duration in seconds.
The actual IO buffer duration may be different
@constant kAudioSessionProperty_AudioCategory
A UInt32 value indicating the audio category for the AudioSession (see constants above).
@constant kAudioSessionProperty_AudioRouteChange
The value for this property is ONLY provided with the property changed callback. You
cannot get the value of this property (or set it).
The property changed callback provides a CFDictionaryRef with keyed values:
Key = kAudioSession_AudioRouteChangeKey_Reason; value is a CFNumberRef with one of the
reasons listed above.
Key = kAudioSession_AudioRouteChangeKey_PreviousRouteDescription; value is a CFDictionaryRef containing
information about the previous route. This dictionary is of exactly the same format as the
dictionary associated with kAudioSessionProperty_AudioRouteDescription. Available in iOS 5.0 or
greater.
Key = kAudioSession_AudioRouteChangeKey_CurrentRouteDescription; value is a CFDictionaryRef containing
information about the new route. This dictionary is of exactly the same format as the
dictionary associated with kAudioSessionProperty_AudioRouteDescription. Available in iOS 5.0 or
greater.
@constant kAudioSessionProperty_CurrentHardwareSampleRate
A Float64 indicating the current hardware sample rate
@constant kAudioSessionProperty_CurrentHardwareInputNumberChannels
A UInt32 indicating the current number of hardware input channels
@constant kAudioSessionProperty_CurrentHardwareOutputNumberChannels
A UInt32 indicating the current number of hardware output channels
@constant kAudioSessionProperty_CurrentHardwareOutputVolume
A Float32 indicating the current output volume
@constant kAudioSessionProperty_CurrentHardwareInputLatency
A Float32 indicating the current hardware input latency in seconds.
@constant kAudioSessionProperty_CurrentHardwareOutputLatency
A Float32 indicating the current hardware output latency in seconds.
@constant kAudioSessionProperty_CurrentHardwareIOBufferDuration
A Float32 indicating the current hardware IO buffer duration in seconds.
@constant kAudioSessionProperty_OtherAudioIsPlaying
A UInt32 with a value other than zero when someone else, typically the iPod application,
is playing audio
@constant kAudioSessionProperty_OverrideAudioRoute
A UInt32 with one of two values: kAudioSessionOverrideAudioRoute_None or
kAudioSessionOverrideAudioRoute_Speaker
@constant kAudioSessionProperty_AudioInputAvailable
A UInt32 with a value other than zero when audio input is available.
Use this property, rather than the device model, to determine if audio input is available.
A listener will notify you when audio input becomes available. For instance, when a headset
is attached to the second generation iPod Touch, audio input becomes available via the wired
microphone.
@constant kAudioSessionProperty_ServerDied
Available with iOS 3.0 or greater
The value for this property is ONLY provided with the property changed callback. You cannot get the
value of this property (or set it). The property changed callback notifies you that
the audio server has died.
@constant kAudioSessionProperty_OtherMixableAudioShouldDuck
Available with iOS 3.0 or greater
If the current session category of an application allows mixing (iPod playback in the background
for example), then that other audio will be ducked when the current application makes any sound.
An example of this is the Nike app that does this as it provides periodic updates to its user (it
ducks any iPod music currently being played while it provides its status).
This defaults to off (0). Note that the other audio will be ducked for as long as the current
session is active.
You will need to deactivate your audio session when you want full volume playback of the other audio.
If your category is the Playback category and you have this set to its default (non-mixable), setting
this value to on, will also make your category mixable with others
(kAudioSessionProperty_OverrideCategoryMixWithOthers will be set to true)
@constant kAudioSessionProperty_OverrideCategoryMixWithOthers
Available with iOS 3.0 or greater
This allows an application to change the default behavior of some audio session categories with regards to
whether other applications can play while your session is active. The two typical cases are:
(1) PlayAndRecord category
this will default to false, but can be set to true. This would allow iPod to play in the background
while an app had both audio input and output enabled
(2) MediaPlayback category
this will default to false, but can be set to true. This would allow iPod to play in the background,
but an app will still be able to play regardless of the setting of the ringer switch
(3) Other categories
this defaults to false and cannot be changed (that is, the mix with others setting of these categories
cannot be overridden
An application must be prepared for setting this property to fail as behaviour may change in future releases.
If an application changes their category, they should reassert the override (it is not sticky across
category changes)
@constant kAudioSessionProperty_OverrideCategoryDefaultToSpeaker
Available with iOS 3.1 or greater
This allows an application to change the default behaviour of some audio session categories with regards to
the audio route. The current category behavior is:
(1) PlayAndRecord category
this will default to false, but can be set to true. this will route to Speaker (instead of Receiver)
when no other audio route is connected.
(2) Other categories
this defaults to false and cannot be changed (that is, the default to speaker setting of these
categories cannot be overridden
An application must be prepared for setting this property to fail as behaviour may change in future releases.
If an application changes their category, they should reassert the override (it is not sticky across category changes)
@constant kAudioSessionProperty_OverrideCategoryEnableBluetoothInput
Available with iOS 3.1 or greater
This allows an application to change the default behaviour of some audio session categories with regards to showing
bluetooth devices as available routes. The current category behavior is:
(1) PlayAndRecord category
this will default to false, but can be set to true. This will allow a paired bluetooth device to show up as
an available route for input, while playing through the category-appropriate output
(2) Record category
this will default to false, but can be set to true. This will allow a paired bluetooth device to show up
as an available route for input
(3) Other categories
this defaults to false and cannot be changed (that is, enabling bluetooth for input in these categories is
not allowed)
An application must be prepared for setting this property to fail as behaviour may change in future releases.
If an application changes their category, they should reassert the override (it is not sticky across category changes)
@constant kAudioSessionProperty_InterruptionType
Available with iOS 4.0 or greater
This is a read-only property that gives the type of the end interruption event. Media playback apps (i.e.,
those apps that have a "play" button), may use this property as a guideline for when to resume playing after an
interruption ends. Apps without a "play" button, (e.g., games) should always resume audio playback when the
interruption ends. This property is only valid within the scope of the client app's AudioSessionInterruptionListener
callback and only valid for the AudioSessionEndInterruption event. Attempting to read the property at any other
time is invalid.
@constant kAudioSessionProperty_Mode
Available with iOS 5.0 or greater
A UInt32 value that specifies the mode to be combined with the Audio Category. See AudioSession mode
values defined above.
@constant kAudioSessionProperty_InputSources
Available with iOS 5.0 or greater
For use with certain accessories, such as some USB audio devices, that support input source selection.
If the attached accessory supports source selection, provides a description of the available sources.
Not to be confused with kAudioSessionProperty_AudioRouteDescription, which provides a description
of the current audio route.
A CFArray of CFDictionaries with the keys listed below. If no input sources are
available, a valid CFArray with 0 entries will be returned by a get operation.
Key = kAudioSession_InputSourceKey_ID; value is a CFNumberRef representing a system-defined identifier
for the input source. This is the identifier to be used when setting the input source.
Key = kAudioSession_InputSourceKey_Description; value is a CFStringRef description of the input source
suitable for displaying in a user interface. Examples: "Internal Mic", "External Mic",
"Ext 48V Mic", "Instrument", "External Line Connector"
@constant kAudioSessionProperty_OutputDestinations
Available with iOS 5.0 or greater
For use with certain accessories, such as some USB audio devices, that support output destination selection.
If the attached accessory supports destination selection, provides a description of the available destinations.
Not to be confused with kAudioSessionProperty_AudioRouteDescription, which provides a description
of the current audio route.
A CFArray of CFDictionaries with the keys listed below. If no output destinations are
available, a valid CFArray with 0 entries will be returned by a get operation.
Key = kAudioSession_OutputDestinationKey_ID; value is a CFNumberRef representing a system-defined identifier
for the output destination. This is the identifier to be used when setting the destination.
Key = kAudioSession_OutputDestinationKey_Description; value is a CFStringRef description of the output
destination suitable for displaying in a user interface.
@constant kAudioSessionProperty_InputSource
Available with iOS 5.0 or greater
For use with certain accessories, such as some USB audio devices, that support input source selection.
A CFNumberRef value that specifies the input source to be selected. The value must be one of the
IDs provided by the kAudioSession_InputSourceKey_ID as part of the data associated with
kAudioSessionProperty_InputSources.
@constant kAudioSessionProperty_OutputDestination
Available with iOS 5.0 or greater
For use with certain accessories, such as some USB audio devices, that support output destination selection.
A CFNumberRef value that specifies the output destination to be selected. The value must be one
of the IDs provided by the kAudioSession_OutputDestinationKey_ID as part of the data associated with
kAudioSessionProperty_OutputDestinations.
@constant kAudioSessionProperty_InputGainAvailable
Available with iOS 5.0 or greater
A UInt32 with a value other than zero when audio input gain is available. Some inputs may not
provide the ability to set the input gain, so check this value before attempting to set input gain.
@constant kAudioSessionProperty_InputGainScalar
Available with iOS 5.0 or greater
A Float32 value defined over the range [0.0, 1.0], with 0.0 corresponding to the lowest analog
gain setting and 1.0 corresponding to the highest analog gain setting. Attempting to set values
outside of the defined range will result in the value being "clamped" to a valid input. This is
a global input gain setting that applies to the current input source for the entire system.
When no applications are using the input gain control, the system will restore the default input
gain setting for the input source. Note that some audio accessories, such as USB devices, may
not have a default value. This property is only valid if kAudioSessionProperty_InputGainAvailable
is true. Note that route change events represent substantive changes to the audio system. Input
gain settings are not guaranteed to persist across route changes. Application code should be aware
that route change events can (and likely will) cause a change to input gain settings, and so should
be prepared to reassess the state of input gain after the new route is established.
@constant kAudioSessionProperty_AudioRouteDescription
Available with iOS 5.0 or greater
A CFDictionaryRef with information about the current audio route; keyed values:
Key = kAudioSession_AudioRouteKey_Inputs; value is a CFArray of CFDictionaries with information about the
inputs utilitized in the current audio route.
Key = kAudioSession_AudioRouteKey_Outputs; value is a CFArray of CFDictionaries with information about the
outputs utilitized in the current audio route.
Both kAudioSession_AudioRouteKey_Inputs and kAudioSession_AudioRouteKey_Outputs return a CFArray of
CFDictionaries with Key = kAudioSession_AudioRouteKey_Type; value is a CFString corresponding
to the input or output types documented above.
*/
enum { // typedef UInt32 AudioSessionPropertyID
kAudioSessionProperty_PreferredHardwareSampleRate = 'hwsr', // Float64 (get/set)
kAudioSessionProperty_PreferredHardwareIOBufferDuration = 'iobd', // Float32 (get/set)
kAudioSessionProperty_AudioCategory = 'acat', // UInt32 (get/set)
kAudioSessionProperty_AudioRouteChange = 'roch', // CFDictionaryRef (property listener)
kAudioSessionProperty_CurrentHardwareSampleRate = 'chsr', // Float64 (get only)
kAudioSessionProperty_CurrentHardwareInputNumberChannels = 'chic', // UInt32 (get only/property listener)
kAudioSessionProperty_CurrentHardwareOutputNumberChannels = 'choc', // UInt32 (get only/property listener)
kAudioSessionProperty_CurrentHardwareOutputVolume = 'chov', // Float32 (get only/property listener)
kAudioSessionProperty_CurrentHardwareInputLatency = 'cilt', // Float32 (get only)
kAudioSessionProperty_CurrentHardwareOutputLatency = 'colt', // Float32 (get only)
kAudioSessionProperty_CurrentHardwareIOBufferDuration = 'chbd', // Float32 (get only)
kAudioSessionProperty_OtherAudioIsPlaying = 'othr', // UInt32 (get only)
kAudioSessionProperty_OverrideAudioRoute = 'ovrd', // UInt32 (set only)
kAudioSessionProperty_AudioInputAvailable = 'aiav', // UInt32 (get only/property listener)
kAudioSessionProperty_ServerDied = 'died', // UInt32 (property listener)
kAudioSessionProperty_OtherMixableAudioShouldDuck = 'duck', // UInt32 (get/set)
kAudioSessionProperty_OverrideCategoryMixWithOthers = 'cmix', // UInt32 (get, some set)
kAudioSessionProperty_OverrideCategoryDefaultToSpeaker = 'cspk', // UInt32 (get, some set)
kAudioSessionProperty_OverrideCategoryEnableBluetoothInput = 'cblu', // UInt32 (get, some set)
kAudioSessionProperty_InterruptionType = 'type', // UInt32 (get only)
kAudioSessionProperty_Mode = 'mode', // UInt32 (get/set)
kAudioSessionProperty_InputSources = 'srcs', // CFArrayRef (get only/property listener)
kAudioSessionProperty_OutputDestinations = 'dsts', // CFArrayRef (get only/property listener)
kAudioSessionProperty_InputSource = 'isrc', // CFNumberRef (get/set)
kAudioSessionProperty_OutputDestination = 'odst', // CFNumberRef (get/set)
kAudioSessionProperty_InputGainAvailable = 'igav', // UInt32 (get only/property listener)
kAudioSessionProperty_InputGainScalar = 'igsc', // Float32 (get/set/property listener)
kAudioSessionProperty_AudioRouteDescription = 'crar' // CFDictionaryRef (get only)
};
//==================================================================================================
#pragma mark -
#pragma mark Callbacks
/*!
@typedef AudioSessionInterruptionListener
@abstract A function to be called when an interruption begins or ends.
@discussion AudioSessionInterruptionListener has to be provided by client applications in the
AudioSessionInitialize function. It will be called when an interruption begins or ends.
@param inClientData
The client user data to use when calling the listener.
@param inInterruptionState
Indicates if the interruption begins (kAudioSessionBeginInterruption)
or ends (kAudioSessionEndInterruption)
*/
typedef void (*AudioSessionInterruptionListener)(
void * inClientData,
UInt32 inInterruptionState);
/*!
@typedef AudioSessionPropertyListener
@abstract A function to be executed when a property changes.
@discussion AudioSessionPropertyListener may be provided by client application to be
called when a property changes.
@param inClientData
The client user data to use when calling the listener.
@param inID
The AudioSession property that changed
@param inDataSize
The size of the payload
@param inData
The payload of the property that changed (see data type for each property)
*/
typedef void (*AudioSessionPropertyListener)(
void * inClientData,
AudioSessionPropertyID inID,
UInt32 inDataSize,
const void * inData);
//==================================================================================================
#pragma mark -
#pragma mark AudioSession Functions
/*!
@functiongroup AudioSession
*/
/*!
@function AudioSessionInitialize
@abstract Initialize the AudioSession.
@discussion This function has to be called once before calling any other
AudioSession functions.
@param inRunLoop
A CFRunLoopRef indicating the desired run loop the interruption routine should
be run on. Pass NULL to use the main run loop.
@param inRunLoopMode
A CFStringRef indicating the run loop mode for the runloop where the
completion routine will be executed. Pass NULL to use kCFRunLoopDefaultMode.
@param inInterruptionListener
An AudioSessionInterruptionListener to be called when the AudioSession
is interrupted.
@param inClientData
The client user data to use when calling the interruption listener.
*/
extern OSStatus
AudioSessionInitialize( CFRunLoopRef inRunLoop,
CFStringRef inRunLoopMode,
AudioSessionInterruptionListener inInterruptionListener,
void *inClientData)
API_DEPRECATED("no longer supported", ios(2.0, 7.0), macCatalyst(14.0, 14.0)) API_UNAVAILABLE(macos) __WATCHOS_PROHIBITED __TVOS_PROHIBITED;
/*!
@function AudioSessionSetActive
@abstract Activate or deactivate the AudioSession.
@discussion Call this function with active set to true to activate this AudioSession (interrupt
the currently active AudioSession).
Call this function with active set to false to deactivate this AudioSession (allow
another interrupted AudioSession to resume).
When active is true this call may fail if the currently active AudioSession has a higher priority.
@param active
A Boolean indicating if you want to make this AudioSession active or inactive.
*/
extern OSStatus
AudioSessionSetActive( Boolean active)
API_DEPRECATED("no longer supported", ios(2.0, 7.0), macCatalyst(14.0, 14.0)) API_UNAVAILABLE(macos) __WATCHOS_PROHIBITED __TVOS_PROHIBITED;
//==================================================================================================
#pragma mark AudioSessionActivationFlags for AudioSessionSetActiveWithFlags
/*!
@enum Flags for AudioSessionSetActiveWithFlags
@abstract These are valid bitmap flags that may be combined and passed to AudioSessionSetActiveWithFlags
to refine this routine's behavior.
@constant kAudioSessionSetActiveFlag_NotifyOthersOnDeactivation
Notify an interrupted app that the interruption has ended and it may resume playback. Only
valid on session deactivation.
*/
enum {
kAudioSessionSetActiveFlag_NotifyOthersOnDeactivation = (1 << 0) // 0x01
};
/*!
@function AudioSessionSetActiveWithFlags
@abstract Same functionality as AudioSessionSetActive, with an additional flags parameter for
refining behavior.
@discussion Call this function with active set to true to activate this AudioSession (interrupt
the currently active AudioSession).
Call this function with active set to false to deactivate this AudioSession (allow
another interrupted AudioSession to resume).
Pass in one or more flags to refine the behavior during activation or deactivation.
When active is true this call may fail if the currently active AudioSession has a
higher priority.
@param active
A Boolean indicating if you want to make this AudioSession active or inactive.
@param inFlags
A bitmap containing one or more flags from the AudioSessionActivationFlags enum.
*/
extern OSStatus
AudioSessionSetActiveWithFlags( Boolean active,
UInt32 inFlags)
API_DEPRECATED("no longer supported", ios(4.0, 7.0), macCatalyst(14.0, 14.0)) API_UNAVAILABLE(macos) __WATCHOS_PROHIBITED __TVOS_PROHIBITED;
/*!
@function AudioSessionGetProperty
@abstract Get the value of a property.
@discussion This function can be called to get the value for a property of the AudioSession.
Valid properties are listed in an enum above.
@param inID
The AudioSessionPropertyID for which we want to get the value.
@param ioDataSize
The size of the data payload.
On entry it should contain the size of the memory pointed to by outData.
On exit it will contain the actual size of the data.
@param outData
The data for the property will be copied here.
@return kAudioSessionNoError if the operation was successful. If the property is a
write-only property or only available by way of property listeners,
kAudioSessionUnsupportedPropertyError will be returned. Other error codes
listed under AudioSession Error Constants also apply to this function.
*/
extern OSStatus
AudioSessionGetProperty( AudioSessionPropertyID inID,
UInt32 *ioDataSize,
void *outData)
API_DEPRECATED("no longer supported", ios(2.0, 7.0), macCatalyst(14.0, 14.0)) API_UNAVAILABLE(macos) __WATCHOS_PROHIBITED __TVOS_PROHIBITED;
/*!
@function AudioSessionSetProperty
@abstract Set the value of a property.
@discussion This function can be called to set the value for a property of the AudioSession.
Valid properties are listed in an enum above.
@param inID
The AudioSessionPropertyID for which we want to set the value.
@param inDataSize
The size of the data payload.
@param inData
The data for the property we want to set.
@return kAudioSessionNoError if the operation was successful. If the property is a
read-only property or an invalid property value is passed in,
kAudioSessionUnsupportedPropertyError will be returned. Other error codes
listed under AudioSession Error Constants also apply to
this function.
*/
extern OSStatus
AudioSessionSetProperty( AudioSessionPropertyID inID,
UInt32 inDataSize,
const void *inData)
API_DEPRECATED("no longer supported", ios(2.0, 7.0), macCatalyst(14.0, 14.0)) API_UNAVAILABLE(macos) __WATCHOS_PROHIBITED __TVOS_PROHIBITED;
/*!
@function AudioSessionGetPropertySize
@abstract Get the size of the payload for a property.
@discussion This function can be called to get the size for the payload of a property.
Valid properties are listed in an enum above.
@param inID
The AudioSessionPropertyID for which we want to get the size of the payload.
@param outDataSize
The size of the data payload will be copied here.
*/
extern OSStatus
AudioSessionGetPropertySize( AudioSessionPropertyID inID,
UInt32 *outDataSize)
API_DEPRECATED("no longer supported", ios(2.0, 7.0), macCatalyst(14.0, 14.0)) API_UNAVAILABLE(macos) __WATCHOS_PROHIBITED __TVOS_PROHIBITED;
/*!
@function AudioSessionAddPropertyListener
@abstract Add a property listener.
@discussion This function can be used to add a listener to be called when a property changes.
If a listener and user data already exist for this property, they will be replaced.
Valid properties are listed above.
@param inID
The AudioSessionPropertyID for which we want to set a listener.
@param inProc
The listener to be called when the property changes.
@param inClientData
The client user data to use when calling the listener.
@return kAudioSessionNoError if the operation was successful. If the property does
not support listeners, kAudioSessionUnsupportedPropertyError will be returned.
Other error codes listed under AudioSession Error Constants also apply to
this function.
*/
extern OSStatus
AudioSessionAddPropertyListener( AudioSessionPropertyID inID,
AudioSessionPropertyListener inProc,
void *inClientData)
API_DEPRECATED("no longer supported", ios(2.0, 7.0), macCatalyst(14.0, 14.0)) API_UNAVAILABLE(macos) __WATCHOS_PROHIBITED __TVOS_PROHIBITED;
/*!
@function AudioSessionRemovePropertyListener
@abstract see AudioSessionRemovePropertyListenerWithUserData
@discussion see AudioSessionRemovePropertyListenerWithUserData
*/
extern OSStatus
AudioSessionRemovePropertyListener( AudioSessionPropertyID inID)
API_DEPRECATED("no longer supported", ios(2.0, 2.0), macCatalyst(14.0, 14.0)) API_UNAVAILABLE(macos) __WATCHOS_PROHIBITED __TVOS_PROHIBITED;
/*!
@function AudioSessionRemovePropertyListener
@abstract Remove a property listener.
@discussion This function can be called to remove the listener for a property. The caller
provides the same proc and user data that was used to add the listener. This ensures
that there can be more than one listener established for a given property ID,
and each listener can be removed as requested.
Valid properties are listed above.
@param inID
The AudioSessionPropertyID for which we want to remove the listener.
@param inProc
The proc that was used to add the listener that needs to be removed.
@param inClientData
The client data that was used to add the listener that needs to be removed.
@return kAudioSessionNoError if the operation was successful. If the property does
not support listeners, kAudioSessionUnsupportedPropertyError will be returned.
Other error codes listed under AudioSession Error Constants also apply to
this function.
*/
extern OSStatus
AudioSessionRemovePropertyListenerWithUserData( AudioSessionPropertyID inID,
AudioSessionPropertyListener inProc,
void *inClientData)
API_DEPRECATED("no longer supported", ios(2.1, 7.0), macCatalyst(14.0, 14.0)) API_UNAVAILABLE(macos) __WATCHOS_PROHIBITED __TVOS_PROHIBITED;
#pragma mark -
#pragma mark Deprecated
/*!
@enum AudioSession audio categories states
@abstract These two session categories are deprecated in iOS 3.0 or later
@constant kAudioSessionCategory_UserInterfaceSoundEffects
use kAudioSessionCategory_AmbientSound
@constant kAudioSessionCategory_LiveAudio
use kAudioSessionCategory_MediaPlayback
*/
enum {
kAudioSessionCategory_UserInterfaceSoundEffects = 'uifx',
kAudioSessionCategory_LiveAudio = 'live'
};
/*!
@enum AudioSession audio categories states
@abstract Deprecated AudioSession properties
@constant kAudioSessionProperty_AudioRoute
Deprecated in iOS 5.0; Use kAudioSessionProperty_AudioRouteDescription
*/
enum {
kAudioSessionProperty_AudioRoute = 'rout', // CFStringRef (get only)
};
// deprecated dictionary keys
// Deprecated in iOS 5.0; Use kAudioSession_AudioRouteChangeKey_PreviousRouteDescription instead
#define kAudioSession_AudioRouteChangeKey_OldRoute "OutputDeviceDidChange_OldRoute"
//==================================================================================================
#ifdef __cplusplus
}
#endif
#endif /* __AudioSession_h__ */

View File

@@ -0,0 +1,6 @@
---
Name: AudioToolbox
Enumerators:
- Name: kMusicSequenceLoadSMF_PreserveTracks
SwiftName: smf_PreserveTracks

View File

@@ -0,0 +1,153 @@
/*!
@file AudioToolbox.h
@framework AudioToolbox.framework
@copyright (c) 2002-2018 by Apple, Inc., all rights reserved.
@abstract Umbrella header for AudioToolbox framework.
*/
#ifndef AudioToolbox_AudioToolbox_h
#define AudioToolbox_AudioToolbox_h
#define AUDIO_TOOLBOX_VERSION 1060
#include <Availability.h>
#include <TargetConditionals.h>
#include <AudioToolbox/AudioCodec.h>
#include <AudioToolbox/AUComponent.h>
#include <AudioToolbox/AUGraph.h>
#include <AudioToolbox/AudioComponent.h>
#include <AudioToolbox/AudioConverter.h>
#include <AudioToolbox/AudioFile.h>
#include <AudioToolbox/AudioFileStream.h>
#include <AudioToolbox/AudioFormat.h>
#include <AudioToolbox/AudioOutputUnit.h>
#include <AudioToolbox/AudioQueue.h>
#include <AudioToolbox/AudioServices.h>
#include <AudioToolbox/AudioUnitParameters.h>
#include <AudioToolbox/AudioUnitProperties.h>
#include <AudioToolbox/AudioWorkInterval.h>
#include <AudioToolbox/CAFFile.h>
#include <AudioToolbox/CAShow.h>
#include <AudioToolbox/ExtendedAudioFile.h>
#include <AudioToolbox/MusicDevice.h>
#include <AudioToolbox/MusicPlayer.h>
#if !TARGET_OS_IPHONE
// macOS only
#include <AudioToolbox/AudioFileComponent.h>
#include <AudioToolbox/AudioUnitUtilities.h>
#include <AudioToolbox/AUMIDIController.h>
#include <AudioToolbox/CoreAudioClock.h>
#endif
#ifdef __OBJC2__
// iOS (all architectures), macOS 64-bit only
#import <AudioToolbox/AUAudioUnit.h>
#import <AudioToolbox/AUAudioUnitImplementation.h>
#import <AudioToolbox/AUParameters.h>
#endif
#if TARGET_OS_OSX || TARGET_OS_IOS
#include <AudioToolbox/AudioSession.h>
#endif
/*! @mainpage
@section section_intro Introduction
The AudioUnit framework contains a set of related API's dealing with:
- Audio components, providing various types of plug-in functionality.
- Audio Units, audio processing plug-ins.
- Audio codecs, plug-ins which decode and encode compressed audio.
@section section_component Audio Components
See AudioComponent.h for API's to find and use audio components, as well as information
on how audio components are packaged and built.
In addition, `<AVFoundation/AVAudioUnitComponent.h>` provides a higher-level interface for
finding audio unit components.
See @ref AUExtensionPackaging and AUAudioUnitImplementation.h for information on creating
version 3 audio units.
@section section_audiounit Audio Units
*/
#include <stdio.h>
CF_ASSUME_NONNULL_BEGIN
#if defined(__cplusplus)
extern "C"
{
#endif
#if !TARGET_OS_IPHONE
// this will return the name of a sound bank from a sound bank file
// the name should be released by the caller
struct FSRef;
OS_EXPORT OSStatus GetNameFromSoundBank (const struct FSRef *inSoundBankRef, CFStringRef __nullable * __nonnull outName)
API_DEPRECATED("no longer supported", macos(10.2, 10.5)) API_UNAVAILABLE(ios, watchos, tvos);
#endif
/*!
@function CopyNameFromSoundBank
@discussion This will return the name of a sound bank from a DLS or SF2 bank.
The name should be released by the caller.
@param inURL
The URL for the sound bank.
@param outName
A pointer to a CFStringRef to be created and returned by the function.
@result returns noErr if successful.
*/
OS_EXPORT OSStatus
CopyNameFromSoundBank (CFURLRef inURL, CFStringRef __nullable * __nonnull outName)
API_AVAILABLE(macos(10.5), ios(7.0), watchos(2.0), tvos(9.0));
/*!
@function CopyInstrumentInfoFromSoundBank
@discussion This will return a CFArray of CFDictionaries, one per instrument found in the DLS or SF2 bank.
Each dictionary will contain four items accessed via CFStringRef versions of the keys kInstrumentInfoKey_MSB,
kInstrumentInfoKey_LSB, kInstrumentInfoKey_Program, and kInstrumentInfoKey_Name.
MSB: An NSNumberRef for the most-significant byte of the bank number. GM melodic banks will return 120 (0x78).
GM percussion banks will return 121 (0x79). Custom banks will return their literal value.
LSB: An NSNumberRef for the least-significant byte of the bank number. All GM banks will return
the bank variation number (0-127).
Program Number: An NSNumberRef for the program number (0-127) of an instrument within a particular bank.
Name: A CFStringRef containing the name of the instrument.
Using these MSB, LSB, and Program values will guarantee that the correct instrument is loaded by the DLS synth
or Sampler Audio Unit.
The CFArray should be released by the caller.
@param inURL
The URL for the sound bank.
@param outInstrumentInfo
A pointer to a CFArrayRef to be created and returned by the function.
@result returns noErr if successful.
*/
OS_EXPORT OSStatus
CopyInstrumentInfoFromSoundBank (CFURLRef inURL, CFArrayRef __nullable * __nonnull outInstrumentInfo)
API_AVAILABLE(macos(10.8), ios(7.0), watchos(2.0), tvos(9.0));
#define kInstrumentInfoKey_Name "name"
#define kInstrumentInfoKey_MSB "MSB"
#define kInstrumentInfoKey_LSB "LSB"
#define kInstrumentInfoKey_Program "program"
#if defined(__cplusplus)
}
#endif
CF_ASSUME_NONNULL_END
#endif // AudioToolbox_AudioToolbox_h

View File

@@ -0,0 +1,38 @@
#if (defined(__USE_PUBLIC_HEADERS__) && __USE_PUBLIC_HEADERS__) || (defined(USE_AUDIOTOOLBOX_PUBLIC_HEADERS) && USE_AUDIOTOOLBOX_PUBLIC_HEADERS) || !__has_include(<AudioToolboxCore/AudioUnit.h>)
/*!
@file AudioUnit.h
@framework AudioToolbox.framework
@copyright (c) 2002-2015 Apple, Inc. All rights reserved.
@brief Former umbrella header for AudioUnit framework; now part of AudioToolbox.
*/
#ifndef _AudioToolbox_AudioUnit_h
#define _AudioToolbox_AudioUnit_h
#include <TargetConditionals.h>
#ifndef AUDIO_UNIT_VERSION
#define AUDIO_UNIT_VERSION 1070
#endif
#include <AudioToolbox/AudioComponent.h>
#include <AudioToolbox/AUComponent.h>
#include <AudioToolbox/AudioOutputUnit.h>
#include <AudioToolbox/AudioUnitProperties.h>
#include <AudioToolbox/AudioUnitParameters.h>
#include <AudioToolbox/MusicDevice.h>
#ifdef __OBJC2__
#import <AudioToolbox/AUAudioUnit.h>
#import <AudioToolbox/AUAudioUnitImplementation.h>
#import <AudioToolbox/AUParameters.h>
#endif
#if !TARGET_OS_IPHONE
#include <AudioToolbox/AudioCodec.h>
#endif
#endif /* _AudioToolbox_AudioUnit_h */
#else
#include <AudioToolboxCore/AudioUnit.h>
#endif

View File

@@ -0,0 +1,189 @@
/*!
@file AudioUnitCarbonView.h
@framework AudioToolbox.framework
@copyright (c) 2000-2015 Apple, Inc. All rights reserved.
@abstract Deprecated interfaces for using Carbon-based views of Audio Units.
*/
#ifndef AudioUnit_AudioUnitCarbonView_h
#define AudioUnit_AudioUnitCarbonView_h
#include <TargetConditionals.h>
#if TARGET_OS_OSX
#if !defined(__COREAUDIO_USE_FLAT_INCLUDES__)
#include <Carbon/Carbon.h>
#include <AudioToolbox/AUComponent.h>
#else
#include <MacWindows.h>
#include <Controls.h>
#include <AUComponent.h>
#endif
#ifdef __cplusplus
extern "C" {
#endif
#if PRAGMA_STRUCT_ALIGN
#pragma options align=mac68k
#elif PRAGMA_STRUCT_PACKPUSH
#pragma pack(push, 2)
#elif PRAGMA_STRUCT_PACK
#pragma pack(2)
#endif
/*!
@typedef AudioUnitCarbonView
@abstract An audio unit Carbon view is of type ComponentInstance, defined by the Component Manager.
*/
typedef ComponentInstance AudioUnitCarbonView;
/*!
@enum Carbon view component types and subtypes
@constant kAudioUnitCarbonViewComponentType
The four char-code type of a carbon-based view component
@constant kAUCarbonViewSubType_Generic
The four char-code subtype of a carbon-based view component
*/
CF_ENUM(UInt32)
{
kAudioUnitCarbonViewComponentType = 'auvw',
kAUCarbonViewSubType_Generic = 'gnrc'
};
/*!
@enum Carbon view events
@constant kAudioUnitCarbonViewEvent_MouseDownInControl
The event type indicating that the mouse is pressed in a control
@constant kAudioUnitCarbonViewEvent_MouseUpInControl
The event type indicating that the mouse is released in a control
*/
enum
{
kAudioUnitCarbonViewEvent_MouseDownInControl = 0,
kAudioUnitCarbonViewEvent_MouseUpInControl = 1
};
/*!
@typedef AudioUnitcarbViewEventID
@abstract Specifies an event passed to an AudioUnitCarbonViewEventListener callback.
*/
typedef SInt32 AudioUnitCarbonViewEventID;
/*!
@typedef AudioUnitCarbonViewEventListener
@abstract Defines a callback function that is called when certain events occur in an
Audio Unit Carbon view, such as mouse-down and up events on a control.
@param inUserData
A user-defined pointer that was passed to an AudioUnitCarbonViewSetEventListener callback.
@param inView
The Audio unit Carbon vIew that generated the message.
@param inParameter
The parameter associated with the control generating the message.
@param inEvent
The type of event, as listed in Audio unit Carbon view events.
@param inEventParam
Further information about the event, dependent on its type.
*/
#ifndef __LP64__
typedef void
(*AudioUnitCarbonViewEventListener)( void * inUserData,
AudioUnitCarbonView inView,
const AudioUnitParameter * inParameter,
AudioUnitCarbonViewEventID inEvent,
const void * inEventParam);
#endif
/*!
@function AudioUnitCarbonViewCreate
@abstract A callback that tells an Audio unit Carbon view to open its user interface (user pane).
@discussion The host application specifies the audio unit which the view is to control. The host
also provides the window, parent control, and rectangle into which the Audio unit
Carbon view component (of type AudioUnitCarbonView) is to create itself.
The host application is responsible for closing the component (by calling the
CloseComponent function) before closing its window.
@param inView
The view component instance.
@param inAudioUnit
The audio unit component instance which the view is to control.
@param inWindow
The Carbon window in which the user interface is to be opened.
@param inParentControl
The Carbon control into which the user interface is to be embedded.
(This is typically the window's root control).
@param inLocation
The host application's requested location for the view. The view should
always create itself at the specified location.
@param inSize
The host application's requested size for the view. The view may choose a
different size for itself. The actual dimensions of the view are described
by the value of the outControl parameter.
@param outControl
The Carbon control which contains the entire user interface for the view.
*/
#ifndef __LP64__
extern OSStatus
AudioUnitCarbonViewCreate( AudioUnitCarbonView inView,
AudioUnit inAudioUnit,
WindowRef inWindow,
ControlRef inParentControl,
const Float32Point * inLocation,
const Float32Point * inSize,
ControlRef * outControl) API_DEPRECATED("no longer supported", macos(10.2, 10.11)) API_UNAVAILABLE(ios, watchos, tvos);
/*!
@function AudioUnitCarbonViewSetEventListener
@abstract Add an event listener to the carbon view.
@deprecated in macOS version 10.4
@discussion Use the AUEventListener functions in <AudioToolbox/AudioUnitUtilities.h> instead.
@param inView
The Carbon view component instance.
@param inCallback
The event listener callback function.
@param inUserData
A user data pointer passed to the callback.
*/
extern OSStatus
AudioUnitCarbonViewSetEventListener( AudioUnitCarbonView inView,
AudioUnitCarbonViewEventListener inCallback,
void * inUserData)
API_DEPRECATED("no longer supported", macos(10.2, 10.4)) API_UNAVAILABLE(ios, watchos, tvos);
#endif
/*!
@enum Selectors for component calls
@constant kAudioUnitCarbonViewRange
Range of selectors
@constant kAudioUnitCarbonViewCreateSelect
Selector for creating the carbon view
@constant kAudioUnitCarbonViewSetEventListenerSelect
Selector for setting the event listener callback
*/
enum
{
kAudioUnitCarbonViewRange = 0x0300, // range of selectors
kAudioUnitCarbonViewCreateSelect = 0x0301,
kAudioUnitCarbonViewSetEventListenerSelect = 0x0302
};
#if PRAGMA_STRUCT_ALIGN
#pragma options align=reset
#elif PRAGMA_STRUCT_PACKPUSH
#pragma pack(pop)
#elif PRAGMA_STRUCT_PACK
#pragma pack()
#endif
#ifdef __cplusplus
}
#endif
#endif // TARGET_OS_OSX
#endif /* AudioUnit_AudioUnitCarbonView_h */

View File

@@ -0,0 +1,606 @@
#if (defined(__USE_PUBLIC_HEADERS__) && __USE_PUBLIC_HEADERS__) || (defined(USE_AUDIOTOOLBOX_PUBLIC_HEADERS) && USE_AUDIOTOOLBOX_PUBLIC_HEADERS) || !__has_include(<AudioToolboxCore/AudioUnitUtilities.h>)
/*!
@file AudioUnitUtilities.h
@framework AudioToolbox.framework
@copyright (c) 2002-2015 by Apple, Inc., all rights reserved.
@abstract Higher-level utility functions for the use of AudioUnit clients.
@discussion
The AU Parameter Listener is designed to provide notifications when an Audio Unit's parameters
or other state changes. It makes it unnecessary for UI components to continually poll an Audio
Unit to determine if a parameter value has been changed. In order for this notification
mechanism to work properly, parameter values should be changed using the AUParameterSet call
(discussed below). This also makes it unnecessary for an Audio Unit to provide and support a
notification mechanism, particularly as AudioUnitSetParameter may be received by an Audio Unit
during the render process.
The AUEventListener API's extend the AUParameterListener API's by supporting event types
other than parameter changes. Events, including parameter changes are delivered serially to the
listener, preserving the time order of the events and parameter changes.
There are also some utilities for converting between non-linear and linear value ranges. These
are useful for displaying a non-linear parameter (such as one whose units are in Hertz or
decibels) using a linear control mechanism, such as a slider, to ensure that the user has a
wider perceived range of control over the parameter value.
*/
#ifndef AudioToolbox_AudioUnitUtilities_h
#define AudioToolbox_AudioUnitUtilities_h
#include <Availability.h>
#include <AudioToolbox/AudioUnit.h>
#ifdef __BLOCKS__
#include <dispatch/dispatch.h>
#endif
CF_ASSUME_NONNULL_BEGIN
#ifdef __cplusplus
extern "C" {
#endif
/* ============================================================================= */
/*!
@constant kAUParameterListener_AnyParameter
A wildcard value for an AudioUnitParameterID. Note that this is
only valid when sending a notification (with AUParameterListenerNotify),
not when registering to receive one.
*/
CF_ENUM(AudioUnitParameterID) {
kAUParameterListener_AnyParameter = 0xFFFFFFFF
};
/*!
@enum AudioUnitEventType
@abstract Types of Audio Unit Events.
@constant kAudioUnitEvent_ParameterValueChange
The event is a change to a parameter value
@constant kAudioUnitEvent_BeginParameterChangeGesture
The event signifies a gesture (e.g. mouse-down) beginning a potential series of
related parameter value change events.
@constant kAudioUnitEvent_EndParameterChangeGesture
The event signifies a gesture (e.g. mouse-up) ending a series of related
parameter value change events.
@constant kAudioUnitEvent_PropertyChange
The event is a change to a property value.
*/
typedef CF_ENUM(UInt32, AudioUnitEventType) {
kAudioUnitEvent_ParameterValueChange = 0,
kAudioUnitEvent_BeginParameterChangeGesture = 1,
kAudioUnitEvent_EndParameterChangeGesture = 2,
kAudioUnitEvent_PropertyChange = 3
};
/* ============================================================================= */
/*!
@typedef AUParameterListenerRef
@abstract An object which receives notifications of Audio Unit parameter value changes.
*/
typedef struct AUListenerBase *AUParameterListenerRef;
// opaque
// old-style listener, may not be passed to new functions
/*!
@typedef AUEventListenerRef
@abstract An object which receives Audio Unit events.
@discussion An AUEventListenerRef may be passed to API's taking an AUEventListenerRef
as an argument.
*/
typedef AUParameterListenerRef AUEventListenerRef;
// new-style listener, can be passed to both old and new functions
/*!
@struct AudioUnitEvent
@abstract Describes a change to an Audio Unit's state.
@var mEventType
The type of event.
@var mArgument
Specifies the parameter or property which has changed.
*/
struct AudioUnitEvent {
AudioUnitEventType mEventType;
union {
AudioUnitParameter mParameter; // for parameter value change, begin and end gesture
AudioUnitProperty mProperty; // for kAudioUnitEvent_PropertyChange
} mArgument;
};
typedef struct AudioUnitEvent AudioUnitEvent;
#ifdef __BLOCKS__
/*!
@typedef AUParameterListenerBlock
@abstract A block called when a parameter value changes.
@param inObject
The object which generated the parameter change.
@param inParameter
Signifies the parameter whose value changed.
@param inValue
The parameter's new value.
*/
typedef void (^AUParameterListenerBlock)( void * __nullable inObject,
const AudioUnitParameter * inParameter,
AudioUnitParameterValue inValue);
/*!
@typedef AUEventListenerBlock
@abstract A block called when an Audio Unit event occurs.
@param inObject
The object which generated the parameter change.
@param inEvent
The event which occurred.
@param inEventHostTime
The host time at which the event occurred.
@param inParameterValue
If the event is parameter change, the parameter's new value (otherwise, undefined).
*/
typedef void (^AUEventListenerBlock)( void * __nullable inObject,
const AudioUnitEvent * inEvent,
UInt64 inEventHostTime,
AudioUnitParameterValue inParameterValue);
#endif
/*!
@typedef AUParameterListenerProc
@abstract A function called when a parameter value changes.
@param inUserData
The value passed to AUListenerCreate when the callback function was installed.
@param inObject
The object which generated the parameter change.
@param inParameter
Signifies the parameter whose value changed.
@param inValue
The parameter's new value.
*/
typedef void (*AUParameterListenerProc)( void * __nullable inUserData,
void * __nullable inObject,
const AudioUnitParameter * inParameter,
AudioUnitParameterValue inValue);
/*!
@typedef AUEventListenerProc
@abstract A function called when an Audio Unit event occurs.
@param inUserData
The value passed to AUListenerCreate when the callback function was installed.
@param inObject
The object which generated the parameter change.
@param inEvent
The event which occurred.
@param inEventHostTime
The host time at which the event occurred.
@param inParameterValue
If the event is parameter change, the parameter's new value (otherwise, undefined).
*/
typedef void (*AUEventListenerProc)(void * __nullable inUserData,
void * __nullable inObject,
const AudioUnitEvent * inEvent,
UInt64 inEventHostTime,
AudioUnitParameterValue inParameterValue);
/* ============================================================================= */
/*!
@functiongroup AUListener
*/
#ifdef __BLOCKS__
/*!
@function AUListenerCreateWithDispatchQueue
@abstract Create an object for fielding notifications when AudioUnit parameter values change.
@param outListener
On successful return, an AUParameterListenerRef.
@param inNotificationInterval
The minimum time interval, in seconds, at which the callback will be called.
If multiple parameter value changes occur within this time interval, the
listener will only receive a notification for the last value change that
occurred before the callback. If inNotificationInterval is 0, the inRunLoop
and inRunLoopMode arguments are ignored, and the callback will be issued
immediately, on the thread on which the parameter was changed.
@param inDispatchQueue
Dispatch queue on which the callback is called.
@param inBlock
Block called when the parameter's value changes.
@discussion
Note that only parameter changes issued through AUParameterSet will generate
notifications to listeners; thus, in most cases, AudioUnit clients should use
AUParameterSet in preference to AudioUnitSetParameterValue.
*/
extern OSStatus
AUListenerCreateWithDispatchQueue( AUParameterListenerRef __nullable * __nonnull outListener,
Float32 inNotificationInterval,
dispatch_queue_t inDispatchQueue,
AUParameterListenerBlock inBlock) API_AVAILABLE(macos(10.6), ios(6.0), watchos(2.0), tvos(9.0));
#endif
/*!
@function AUListenerCreate
@abstract Create an object for fielding notifications when AudioUnit parameter values change.
@param inProc
Function called when the parameter's value changes.
@param inUserData
A reference value for the use of the callback function.
@param inRunLoop
The run loop on which the callback is called. If NULL,
CFRunLoopGetCurrent() is used.
@param inRunLoopMode
The run loop mode in which the callback's underlying run loop source will be
attached. If NULL, kCFRunLoopDefaultMode is used.
@param inNotificationInterval
The minimum time interval, in seconds, at which the callback will be called.
If multiple parameter value changes occur within this time interval, the
listener will only receive a notification for the last value change that
occurred before the callback. If inNotificationInterval is 0, the inRunLoop
and inRunLoopMode arguments are ignored, and the callback will be issued
immediately, on the thread on which the parameter was changed.
@param outListener
On successful return, an AUParameterListenerRef.
@discussion
Note that only parameter changes issued through AUParameterSet will generate
notifications to listeners; thus, in most cases, AudioUnit clients should use
AUParameterSet in preference to AudioUnitSetParameter.
*/
extern OSStatus
AUListenerCreate( AUParameterListenerProc inProc,
void * inUserData,
CFRunLoopRef __nullable inRunLoop,
CFStringRef __nullable inRunLoopMode,
Float32 inNotificationInterval,
AUParameterListenerRef __nullable * __nonnull outListener) API_AVAILABLE(macos(10.2), ios(6.0), watchos(2.0), tvos(9.0));
/*!
@function AUListenerDispose
@abstract Dispose a parameter listener object.
@param inListener
The parameter listener to dispose.
*/
extern OSStatus
AUListenerDispose( AUParameterListenerRef inListener) API_AVAILABLE(macos(10.2), ios(6.0), watchos(2.0), tvos(9.0));
/*!
@function AUListenerAddParameter
@abstract Connect a parameter to a listener.
@param inListener
The parameter listener which will receive the callback.
@param inObject
The object which is interested in the value of the parameter. This will be
passed as the inObject parameter to the listener callback function when the
parameter changes.
@param inParameter
The parameter whose value changes are to generate callbacks.
@discussion
Associates an arbitrary object (often a user interface widget) with an
AudioUnitParameter, and delivers notifications to the specified listener, telling it
that the object needs to be informed of the parameter's value change.
*/
extern OSStatus
AUListenerAddParameter( AUParameterListenerRef inListener,
void * __nullable inObject,
const AudioUnitParameter * inParameter) API_AVAILABLE(macos(10.2), ios(6.0), watchos(2.0), tvos(9.0));
/*!
@function AUListenerRemoveParameter
@abstract Remove a parameter/listener connection.
@param inListener
The parameter listener to stop receiving callbacks.
@param inObject
The object which is no longer interested in the value of the parameter.
@param inParameter
The parameter whose value changes are to stop generating callbacks.
*/
extern OSStatus
AUListenerRemoveParameter( AUParameterListenerRef inListener,
void * __nullable inObject,
const AudioUnitParameter * inParameter) API_AVAILABLE(macos(10.2), ios(6.0), watchos(2.0), tvos(9.0));
/*!
@function AUParameterSet
@abstract Set an AudioUnit parameter value and notify listeners.
@param inSendingListener
A parameter listener generating the change and which does not want to
receive a callback as a result of it. May be NULL.
@param inSendingObject
The object generating the change and which does not want to receive a
callback as a result of it. NULL is treated specially when inListener is
non-null; it signifies that none of the specified listener's objects will
receive notifications.
@param inParameter
The parameter being changed.
@param inValue
The new value of the parameter.
@param inBufferOffsetInFrames
The offset into the next rendered buffer at which the parameter change will take
effect.
@discussion
Calls AudioUnitSetParameter, and performs/schedules notification callbacks to all
parameter listeners, for that parameter -- except that no callback will be generated to
the inListener/inObject pair.
*/
extern OSStatus
AUParameterSet( AUParameterListenerRef __nullable inSendingListener,
void * __nullable inSendingObject,
const AudioUnitParameter * inParameter,
AudioUnitParameterValue inValue,
UInt32 inBufferOffsetInFrames)
API_AVAILABLE(macos(10.2), ios(6.0), watchos(2.0), tvos(9.0));
/*!
@function AUParameterListenerNotify
@abstract Notify listeners of a past parameter change.
@param inSendingListener
A parameter listener generating the change and which does not want to
receive a callback as a result of it. May be NULL.
@param inSendingObject
The object generating the change and which does not want to receive a
callback as a result of it. NULL is treated specially when inListener is
non-null; it signifies that none of the specified listener's objects will
receive notifications.
@param inParameter
The parameter which was changed.
@discussion
Performs and schedules the notification callbacks of AUParameterSet, without
actually setting an AudioUnit parameter value.
Clients scheduling ramped parameter changes to AudioUnits must make this call
dynamically during playback in order for AudioUnitViews to be updated. When the view's
listener receives a notification, it will be passed the current value of the parameter.
A special meaning is applied if the mParameterID value of inParameter is equal to
kAUParameterListener_AnyParameter. In this case, ANY listener for ANY parameter value
changes on the specified AudioUnit will be notified of the current value of that
parameter.
*/
extern OSStatus
AUParameterListenerNotify( AUParameterListenerRef __nullable inSendingListener,
void * __nullable inSendingObject,
const AudioUnitParameter * inParameter) API_AVAILABLE(macos(10.2), ios(6.0), watchos(2.0), tvos(9.0));
/* ============================================================================= */
/*!
@functiongroup AUEventListener
*/
#ifdef __BLOCKS__
/*!
@function AUEventListenerCreateWithDispatchQueue
@abstract Creates an Audio Unit event listener.
@param outListener
On successful return, an AUEventListenerRef.
@param inNotificationInterval
The minimum time interval, in seconds, at which the callback will be called.
@param inValueChangeGranularity
Determines how parameter value changes occurring within this interval are
queued; when an event follows a previous one by a smaller time interval than
the granularity, then the listener will only be notified for the second
parameter change.
@param inDispatchQueue
The dispatch queue on which the callback is called.
@param inBlock
Block called when an event occurs.
@discussion
AUEventListener is a specialization of AUParameterListener; use AUListenerDispose to
dispose of an AUEventListener. You may use AUListenerAddParameter and
AUListenerRemoveParameter with AUEventListerRef's, in addition to
AUEventListenerAddEventType / AUEventListenerRemoveEventType.
Some examples illustrating inNotificationInterval and inValueChangeGranularity:
[1] a UI receiver: inNotificationInterval = 100 ms, inValueChangeGranularity = 100 ms.
User interfaces almost never care about previous values, only the current one,
and don't wish to perform redraws too often.
[2] An automation recorder: inNotificationInterval = 200 ms, inValueChangeGranularity = 10 ms.
Automation systems typically wish to record events with a high degree of timing precision,
but do not need to be woken up for each event.
In case [1], the listener will be called within 100 ms (the notification interval) of an
event. It will only receive one notification for any number of value changes to the
parameter concerned, occurring within a 100 ms window (the granularity).
In case [2], the listener will be received within 200 ms (the notification interval) of
an event It can receive more than one notification per parameter, for the last of each
group of value changes occurring within a 10 ms window (the granularity).
In both cases, thread scheduling latencies may result in more events being delivered to
the listener callback than the theoretical maximum (notification interval /
granularity).
*/
extern OSStatus
AUEventListenerCreateWithDispatchQueue(
AUEventListenerRef __nullable * __nonnull outListener,
Float32 inNotificationInterval, // seconds
Float32 inValueChangeGranularity, // seconds
dispatch_queue_t inDispatchQueue,
AUEventListenerBlock inBlock) API_AVAILABLE(macos(10.6), ios(6.0), watchos(2.0), tvos(9.0));
#endif
/*!
@function AUEventListenerCreate
@abstract Creates an Audio Unit event listener.
@param inProc
Function called when an event occurs.
@param inUserData
A reference value for the use of the callback function.
@param inRunLoop
The run loop on which the callback is called. If NULL,
CFRunLoopGetCurrent() is used.
@param inRunLoopMode
The run loop mode in which the callback's underlying run loop source will be
attached. If NULL, kCFRunLoopDefaultMode is used.
@param inNotificationInterval
The minimum time interval, in seconds, at which the callback will be called.
@param inValueChangeGranularity
Determines how parameter value changes occurring within this interval are
queued; when an event follows a previous one by a smaller time interval than
the granularity, then the listener will only be notified for the second
parameter change.
@param outListener
On successful return, an AUEventListenerRef.
@discussion
See the discussion of AUEventListenerCreateWithDispatchQueue.
*/
extern OSStatus
AUEventListenerCreate( AUEventListenerProc inProc,
void * __nullable inUserData,
CFRunLoopRef __nullable inRunLoop,
CFStringRef __nullable inRunLoopMode,
Float32 inNotificationInterval,
Float32 inValueChangeGranularity,
AUEventListenerRef __nullable * __nonnull outListener) API_AVAILABLE(macos(10.3), ios(6.0), watchos(2.0), tvos(9.0));
/*!
@function AUEventListenerAddEventType
@abstract Begin delivering a particular type of events to a listener.
@param inListener
The parameter listener which will receive the events.
@param inObject
The object which is interested in the value of the parameter. This will be
passed as the inObject parameter to the listener callback function when the
parameter changes.
@param inEvent
The type of event to listen for.
@result An OSStatus error code.
*/
extern OSStatus
AUEventListenerAddEventType( AUEventListenerRef inListener,
void * __nullable inObject,
const AudioUnitEvent * inEvent) API_AVAILABLE(macos(10.3), ios(6.0), watchos(2.0), tvos(9.0));
/*!
@function AUEventListenerRemoveEventType
@abstract Stop delivering a particular type of events to a listener.
@param inListener
The parameter listener to stop receiving events.
@param inObject
The object which is no longer interested in the value of the parameter.
@param inEvent
The type of event to stop listening for.
@result An OSStatus error code.
*/
extern OSStatus
AUEventListenerRemoveEventType( AUEventListenerRef inListener,
void * __nullable inObject,
const AudioUnitEvent * inEvent) API_AVAILABLE(macos(10.3), ios(6.0), watchos(2.0), tvos(9.0));
/*!
@function AUEventListenerNotify
@abstract Deliver an AudioUnitEvent to all listeners registered to receive it.
@discussion This is only to be used for notifications about parameter changes (and gestures).
It can not be used for notifying changes to property values as these are
internal to an audio unit and should not be issued outside of the audio unit itself.
@param inSendingListener
A parameter listener generating the change and which does not want to
receive a callback as a result of it. May be NULL.
@param inSendingObject
The object generating the change and which does not want to receive a
callback as a result of it. NULL is treated specially when inListener is
non-null; it signifies that none of the specified listener's objects will
receive notifications.
@param inEvent
The event to be delivered.
@result An OSStatus error code.
*/
extern OSStatus
AUEventListenerNotify( AUEventListenerRef __nullable inSendingListener,
void * __nullable inSendingObject,
const AudioUnitEvent * inEvent) API_AVAILABLE(macos(10.3), ios(6.0), watchos(2.0), tvos(9.0));
/* ============================================================================= */
/*!
@functiongroup Parameter value utilities
*/
/*!
@function AUParameterValueFromLinear
@abstract Converts a linear value to a parameter value according to the parameter's units.
@param inLinearValue
The linear value (0.0-1.0) to convert.
@param inParameter
The parameter, including its Audio Unit, that will define the conversion of
the supplied linear value to a value that is natural to that parameter.
@result
The converted parameter value, in the parameter's natural units.
*/
extern AudioUnitParameterValue
AUParameterValueFromLinear( Float32 inLinearValue,
const AudioUnitParameter * inParameter) API_AVAILABLE(macos(10.2), ios(6.0), watchos(2.0), tvos(9.0));
/*!
@function AUParameterValueToLinear
@abstract Converts a parameter value to a linear value according to the parameter's units.
@param inParameterValue
The value in the natural units of the specified parameter.
@param inParameter
The parameter, including its Audio Unit, that will define the conversion of
the supplied parameter value to a corresponding linear value.
@result
A number 0.0-1.0.
*/
extern Float32
AUParameterValueToLinear( AudioUnitParameterValue inParameterValue,
const AudioUnitParameter * inParameter) API_AVAILABLE(macos(10.2), ios(6.0), watchos(2.0), tvos(9.0));
// returns 0-1
/*!
@function AUParameterFormatValue
@abstract Format a parameter value into a string.
@param inParameterValue
The parameter value to be formatted.
@param inParameter
The Audio Unit, scope, element, and parameter whose value this is.
@param inTextBuffer
The character array to receive the formatted text. Should be at least 32
characters.
@param inDigits
The resolution of the string (see example above).
@result
`inTextBuffer`
@discussion
Formats a floating point value into a string. Computes a power of 10 to which the value
will be rounded and displayed as follows: if the the parameter is logarithmic (Hertz),
the number of significant digits is inDigits - pow10(inParameterValue) + 1. Otherwise,
it is inDigits - pow10(maxValue - minValue) + 1.
Example for inDigits=3:
pow10 | range | digits after decimal place display
------|--------------|------------------------------------
-2 | .0100-.0999 | 4
-1 | .100-.999 | 3
0 | 1.00-9.99 | 2
1 | 10.0-99.9 | 1
2 | 100-999 | 0
3 | 1000-9990 | -1
4 | 10000-99900 | -2
*/
extern char *
AUParameterFormatValue( Float64 inParameterValue,
const AudioUnitParameter * inParameter,
char * inTextBuffer,
UInt32 inDigits) API_AVAILABLE(macos(10.2), ios(6.0), watchos(2.0), tvos(9.0));
#ifdef __cplusplus
}
#endif
CF_ASSUME_NONNULL_END
#endif // AudioToolbox_AudioUnitUtilities_h
#else
#include <AudioToolboxCore/AudioUnitUtilities.h>
#endif

View File

@@ -0,0 +1,102 @@
#if (defined(__USE_PUBLIC_HEADERS__) && __USE_PUBLIC_HEADERS__) || (defined(USE_AUDIOTOOLBOX_PUBLIC_HEADERS) && USE_AUDIOTOOLBOX_PUBLIC_HEADERS) || !__has_include(<AudioToolboxCore/AudioWorkInterval.h>)
/*!
@file AudioWorkInterval.h
@framework AudioToolbox.framework
@copyright (c) 2020 by Apple Inc., all rights reserved.
@abstract API to create workgroups.
Workgroups express that a collection of realtime threads are working in tandem to produce audio
for a common deadline. Such threads span multiple processes including the audio server and
client applications. The system uses workgroups to observe the CPU usage of audio realtime
threads and dynamically balance the competing considerations of power consumption vs. rendering
capacity.
Workgroups have "work intervals", or "workgroup intervals", which express the duty cycle of the
main thread in the workgroup. We sometimes use these terms interchangeably with "workgroup".
Core Audio devices own a workgroup whose lifetime is the same as that of the device. This
`os_workgroup_t` can be obtained via `kAudioDevicePropertyIOThreadOSWorkgroup`.
For Audio I/O units which are associated with an audio device, that device-owned workgroup is
readable as an Audio Unit property. With the C API (AudioUnitGetProperty()), use
`kAudioOutputUnitProperty_OSWorkgroup`. With the ObjC API (AUAudioUnit), use the osWorkgroup
property. If an I/O unit's device assignment changes, as a side effect, its workgroup will also
change.
An audio app or plug-in may create auxiliary rendering threads. When such a thread has realtime
priority, it should be associated with a workgroup, as follows:
1. If an auxiliary realtime thread operates with the same cadence as the Core Audio
realtime I/O thread, that is, it is triggered by code known to be running on the device's
I/O thread and has a deadline within the current I/O cycle, that auxiliary thread should be
joined to the device thread's workgroup, using the join/leave APIs in
<os/workgroup_object.h>.
2. If an Audio Unit's auxiliary realtime thread operates with the same cadence as the
requests to render the plug-in, that is, it is triggered by the rendering thread and is
expected to finish rendering before that render request completes, the plug-in should
implement a render context observer, and join its auxiliary thread(s) to any workgroup
passed to that observer. See the Audio Unit properties
`kAudioUnitProperty_RenderContextObserver` (v2) and `AUAudioUnit.renderContextObserver` (v3).
3. If an app or plug-in creates realtime threads that operate asynchronously, i.e. at a
cadence independent of any audio hardware or Audio Unit rendering cycle, then that app or
plug-in should create its own workgroup interval, using AudioWorkIntervalCreate(). All
threads processing to this work interval's deadline should join its workgroup, using
the join/leave APIs in <os/workgroup_object.h>. The "master" thread, the one coordinating
the activities of all of the threads in the workgroup (if there are multiple), should
signify the beginning and ending of each work cycle using `os_workgroup_interval_start()` and
`os_workgroup_interval_finish()`.
The properties and API described here are available beginning in macOS 10.16 and iOS 14.0.
Note that they are unavailable from Swift, because these API's pertain exclusively to realtime
threads, while the Swift runtime is unsafe for use on realtime threads.
See also: <os/workgroup_object.h>, <os/workgroup_interval.h>.
*/
#ifndef AudioToolbox_AudioWorkInterval_h
#define AudioToolbox_AudioWorkInterval_h
#include <CoreFoundation/CFBase.h>
#include <os/workgroup.h>
#ifdef __cplusplus
extern "C" {
#endif
CF_ASSUME_NONNULL_BEGIN
/*!
@fn AudioWorkIntervalCreate
@brief Create an OS workgroup interval for use with audio realtime threads.
@param name
A name for the created work interval.
@param clock
The clockid in which interval timestamps are specified, e.g. `OS_CLOCK_MACH_ABSOLUTE_TIME`
from <os/clock.h>.
@param attr
This field is currently not used and should be NULL.
@return
A new os_workgroup_interval_t. The client should call `os_workgroup_interval_start()`
and `os_workgroup_interval_finish()` to notify the system of the beginning and ending
of each work duty cycle. The caller is responsible for releasing this object when finished
with it (if not using automatic reference counting).
*/
OS_WORKGROUP_RETURNS_RETAINED
os_workgroup_interval_t AudioWorkIntervalCreate(
const char* name, os_clockid_t clock, os_workgroup_attr_t _Nullable attr)
API_AVAILABLE(macos(11.0), ios(14.0), watchos(7.0), tvos(14.0))
__SWIFT_UNAVAILABLE_MSG("Swift is not supported for use with audio realtime threads");
CF_ASSUME_NONNULL_END
#ifdef __cplusplus
}
#endif
#endif /* AudioToolbox_AudioWorkInterval_h */
#else
#include <AudioToolboxCore/AudioWorkInterval.h>
#endif

View File

@@ -0,0 +1,368 @@
#if (defined(__USE_PUBLIC_HEADERS__) && __USE_PUBLIC_HEADERS__) || (defined(USE_AUDIOTOOLBOX_PUBLIC_HEADERS) && USE_AUDIOTOOLBOX_PUBLIC_HEADERS) || !__has_include(<AudioToolboxCore/CAFFile.h>)
/*!
@file CAFFile.h
@framework AudioToolbox.framework
@copyright (c) 2004-2015 by Apple, Inc., all rights reserved.
@abstract The data structures contained within a CAF (Core Audio Format) file.
*/
#ifndef AudioToolbox_CAFFile_h
#define AudioToolbox_CAFFile_h
#include <CoreAudioTypes/CoreAudioTypes.h>
#if TARGET_OS_WIN32
#define ATTRIBUTE_PACKED
#pragma pack(push, 1)
#else
#define ATTRIBUTE_PACKED __attribute__((__packed__))
#endif
// In a CAF File all of these types' byte order is big endian.
// When reading or writing these values the program will need to flip byte order to native endian
// CAF File Header
CF_ENUM(UInt32) {
kCAF_FileType = 'caff',
kCAF_FileVersion_Initial = 1
};
// CAF Chunk Types
CF_ENUM(UInt32) {
kCAF_StreamDescriptionChunkID = 'desc',
kCAF_AudioDataChunkID = 'data',
kCAF_ChannelLayoutChunkID = 'chan',
kCAF_FillerChunkID = 'free',
kCAF_MarkerChunkID = 'mark',
kCAF_RegionChunkID = 'regn',
kCAF_InstrumentChunkID = 'inst',
kCAF_MagicCookieID = 'kuki',
kCAF_InfoStringsChunkID = 'info',
kCAF_EditCommentsChunkID = 'edct',
kCAF_PacketTableChunkID = 'pakt',
kCAF_StringsChunkID = 'strg',
kCAF_UUIDChunkID = 'uuid',
kCAF_PeakChunkID = 'peak',
kCAF_OverviewChunkID = 'ovvw',
kCAF_MIDIChunkID = 'midi',
kCAF_UMIDChunkID = 'umid',
kCAF_FormatListID = 'ldsc',
kCAF_iXMLChunkID = 'iXML'
};
struct CAFFileHeader
{
UInt32 mFileType; // 'caff'
UInt16 mFileVersion; //initial revision set to 1
UInt16 mFileFlags; //initial revision set to 0
} ATTRIBUTE_PACKED;
typedef struct CAFFileHeader CAFFileHeader;
struct CAFChunkHeader
{
UInt32 mChunkType; // four char code
SInt64 mChunkSize; // size in bytes of the chunk data (not including this header).
// mChunkSize is SInt64 not UInt64 because negative values for
// the data size can have a special meaning
} ATTRIBUTE_PACKED;
typedef struct CAFChunkHeader CAFChunkHeader;
struct CAF_UUID_ChunkHeader
{
CAFChunkHeader mHeader;
UInt8 mUUID[16];
} ATTRIBUTE_PACKED;
typedef struct CAF_UUID_ChunkHeader CAF_UUID_ChunkHeader;
// these are the flags if the format ID is 'lpcm'
// <CoreAudioTypes/CoreAudioTypes.h> declares some of the format constants
// that can be used as Data Formats in a CAF file
typedef CF_OPTIONS(UInt32, CAFFormatFlags)
{
kCAFLinearPCMFormatFlagIsFloat = (1L << 0),
kCAFLinearPCMFormatFlagIsLittleEndian = (1L << 1)
};
// Every file MUST have this chunk. It MUST be the first chunk in the file
struct CAFAudioDescription
{
Float64 mSampleRate;
UInt32 mFormatID;
CAFFormatFlags mFormatFlags;
UInt32 mBytesPerPacket;
UInt32 mFramesPerPacket;
UInt32 mChannelsPerFrame;
UInt32 mBitsPerChannel;
} ATTRIBUTE_PACKED;
typedef struct CAFAudioDescription CAFAudioDescription;
// 'ldsc' format list chunk.
// for data formats like AAC SBR which can be decompressed to multiple formats, this chunk contains a list of
// CAFAudioFormatListItem describing those formats. The list is ordered from best to worst by number of channels
// and sample rate in that order. mChannelLayoutTag is an AudioChannelLayoutTag as defined in CoreAudioTypes.h
struct CAFAudioFormatListItem
{
CAFAudioDescription mFormat;
UInt32 mChannelLayoutTag;
} ATTRIBUTE_PACKED;
// 'chan' Optional chunk.
// struct AudioChannelLayout as defined in CoreAudioTypes.h.
// 'free'
// this is a padding chunk for reserving space in the file. content is meaningless.
// 'kuki'
// this is the magic cookie chunk. bag of bytes.
// 'data' Every file MUST have this chunk.
// actual audio data can be any format as described by the 'asbd' chunk.
// if mChunkSize is < 0 then this is the last chunk in the file and the actual length
// should be determined from the file size.
// The motivation for this is to allow writing the files without seeking to update size fields after every
// write in order to keep the file legal.
// The program can put a -1 in the mChunkSize field and
// update it only once at the end of recording.
// If the program were to crash during recording then the file is still well defined.
// 'pakt' Required if either/or mBytesPerPacket or mFramesPerPacket in the Format Description are zero
// For formats that are packetized and have variable sized packets.
// The table is stored as an array of one or two variable length integers.
// (a) size in bytes of the data of a given packet.
// (b) number of frames in a given packet.
// These sizes are encoded as variable length integers
// The packet description entries are either one or two values depending on the format.
// There are three possibilities
// (1)
// If the format has variable bytes per packets (desc.mBytesPerPacket == 0) and constant frames per packet
// (desc.mFramesPerPacket != 0) then the packet table contains single entries representing the bytes in a given packet
// (2)
// If the format is a constant bit rate (desc.mBytesPerPacket != 0) but variable frames per packet
// (desc.mFramesPerPacket == 0) then the packet table entries contains single entries
// representing the number of frames in a given packet
// (3)
// If the format has variable frames per packet (asbd.mFramesPerPacket == 0) and variable bytes per packet
// (desc.mBytesPerPacket == 0) then the packet table entries are a duple of two values. The first value
// is the number of bytes in a given packet, the second value is the number of frames in a given packet
struct CAFPacketTableHeader
{
SInt64 mNumberPackets;
SInt64 mNumberValidFrames;
SInt32 mPrimingFrames;
SInt32 mRemainderFrames;
UInt8 mPacketDescriptions[1]; // this is a variable length array of mNumberPackets elements
} ATTRIBUTE_PACKED;
typedef struct CAFPacketTableHeader CAFPacketTableHeader;
struct CAFDataChunk
{
UInt32 mEditCount;
UInt8 mData[1]; // this is a variable length data field based off the size of the data chunk
} ATTRIBUTE_PACKED;
typedef struct CAFDataChunk CAFDataChunk;
// markers types
CF_ENUM(UInt32) {
kCAFMarkerType_Generic = 0,
kCAFMarkerType_ProgramStart = 'pbeg',
kCAFMarkerType_ProgramEnd = 'pend',
kCAFMarkerType_TrackStart = 'tbeg',
kCAFMarkerType_TrackEnd = 'tend',
kCAFMarkerType_Index = 'indx',
kCAFMarkerType_RegionStart = 'rbeg',
kCAFMarkerType_RegionEnd = 'rend',
kCAFMarkerType_RegionSyncPoint = 'rsyc',
kCAFMarkerType_SelectionStart = 'sbeg',
kCAFMarkerType_SelectionEnd = 'send',
kCAFMarkerType_EditSourceBegin = 'cbeg',
kCAFMarkerType_EditSourceEnd = 'cend',
kCAFMarkerType_EditDestinationBegin = 'dbeg',
kCAFMarkerType_EditDestinationEnd = 'dend',
kCAFMarkerType_SustainLoopStart = 'slbg',
kCAFMarkerType_SustainLoopEnd = 'slen',
kCAFMarkerType_ReleaseLoopStart = 'rlbg',
kCAFMarkerType_ReleaseLoopEnd = 'rlen',
kCAFMarkerType_SavedPlayPosition = 'sply',
kCAFMarkerType_Tempo = 'tmpo',
kCAFMarkerType_TimeSignature = 'tsig',
kCAFMarkerType_KeySignature = 'ksig'
};
CF_ENUM(UInt32)
{
kCAF_SMPTE_TimeTypeNone = 0,
kCAF_SMPTE_TimeType24 = 1,
kCAF_SMPTE_TimeType25 = 2,
kCAF_SMPTE_TimeType30Drop = 3,
kCAF_SMPTE_TimeType30 = 4,
kCAF_SMPTE_TimeType2997 = 5,
kCAF_SMPTE_TimeType2997Drop = 6,
kCAF_SMPTE_TimeType60 = 7,
kCAF_SMPTE_TimeType5994 = 8,
kCAF_SMPTE_TimeType60Drop = 9,
kCAF_SMPTE_TimeType5994Drop = 10,
kCAF_SMPTE_TimeType50 = 11,
kCAF_SMPTE_TimeType2398 = 12
};
struct CAF_SMPTE_Time
{
SInt8 mHours;
SInt8 mMinutes;
SInt8 mSeconds;
SInt8 mFrames;
UInt32 mSubFrameSampleOffset;
} ATTRIBUTE_PACKED;
typedef struct CAF_SMPTE_Time CAF_SMPTE_Time;
struct CAFMarker
{
UInt32 mType;
Float64 mFramePosition;
UInt32 mMarkerID;
CAF_SMPTE_Time mSMPTETime;
UInt32 mChannel;
} ATTRIBUTE_PACKED;
typedef struct CAFMarker CAFMarker;
struct CAFMarkerChunk
{
UInt32 mSMPTE_TimeType;
UInt32 mNumberMarkers;
CAFMarker mMarkers[1]; // this is a variable length array of mNumberMarkers elements
} ATTRIBUTE_PACKED;
typedef struct CAFMarkerChunk CAFMarkerChunk;
#define kCAFMarkerChunkHdrSize offsetof(CAFMarkerChunk, mMarkers)
typedef CF_OPTIONS(UInt32, CAFRegionFlags) {
kCAFRegionFlag_LoopEnable = 1,
kCAFRegionFlag_PlayForward = 2,
kCAFRegionFlag_PlayBackward = 4
};
struct CAFRegion
{
UInt32 mRegionID;
CAFRegionFlags mFlags;
UInt32 mNumberMarkers;
CAFMarker mMarkers[1]; // this is a variable length array of mNumberMarkers elements
} ATTRIBUTE_PACKED;
typedef struct CAFRegion CAFRegion;
/* because AudioFileRegions are variable length, you cannot access them as an array. Use NextAudioFileRegion to walk the list. */
#define NextCAFRegion(inCAFRegionPtr) \
((CAFRegion*)((char*)(inCAFRegionPtr) + offsetof(CAFRegion, mMarkers) + ((inCAFRegionPtr)->mNumberMarkers)*sizeof(CAFMarker)))
struct CAFRegionChunk
{
UInt32 mSMPTE_TimeType;
UInt32 mNumberRegions;
CAFRegion mRegions[1]; // this is a variable length array of mNumberRegions elements
} ATTRIBUTE_PACKED;
typedef struct CAFRegionChunk CAFRegionChunk;
#define kCAFRegionChunkHdrSize offsetof(CAFRegionChunk, mRegions)
struct CAFInstrumentChunk
{
Float32 mBaseNote;
UInt8 mMIDILowNote;
UInt8 mMIDIHighNote;
UInt8 mMIDILowVelocity;
UInt8 mMIDIHighVelocity;
Float32 mdBGain;
UInt32 mStartRegionID;
UInt32 mSustainRegionID;
UInt32 mReleaseRegionID;
UInt32 mInstrumentID;
} ATTRIBUTE_PACKED;
typedef struct CAFInstrumentChunk CAFInstrumentChunk;
struct CAFStringID {
UInt32 mStringID;
SInt64 mStringStartByteOffset;
} ATTRIBUTE_PACKED;
typedef struct CAFStringID CAFStringID;
struct CAFStrings
{
UInt32 mNumEntries;
CAFStringID mStringsIDs[1]; // this is a variable length array of mNumEntries elements
// this struct is only fictionally described due to the variable length fields
// UInt8 mStrings[ variable num elements ]; // null terminated UTF8 strings
} ATTRIBUTE_PACKED;
typedef struct CAFStrings CAFStrings;
struct CAFInfoStrings
{
UInt32 mNumEntries;
// These are only fictionally defined in the struct due to the variable length fields.
// struct {
// UInt8 mKey[ variable num elements ]; // null terminated UTF8 string
// UInt8 mValue[ variable num elements ]; // null terminated UTF8 string
// } mStrings[ variable num elements ];
} ATTRIBUTE_PACKED;
typedef struct CAFInfoStrings CAFInfoStrings;
struct CAFPositionPeak
{
Float32 mValue;
UInt64 mFrameNumber;
} ATTRIBUTE_PACKED;
typedef struct CAFPositionPeak CAFPositionPeak;
struct CAFPeakChunk
{
UInt32 mEditCount;
CAFPositionPeak mPeaks[1]; // this is a variable length array of peak elements (calculated from the size of the chunk)
} ATTRIBUTE_PACKED;
typedef struct CAFPeakChunk CAFPeakChunk;
struct CAFOverviewSample
{
SInt16 mMinValue;
SInt16 mMaxValue;
} ATTRIBUTE_PACKED;
typedef struct CAFOverviewSample CAFOverviewSample;
struct CAFOverviewChunk
{
UInt32 mEditCount;
UInt32 mNumFramesPerOVWSample;
CAFOverviewSample mData[1]; // data is of variable size, calculated from the sizeo of the chunk.
} ATTRIBUTE_PACKED;
typedef struct CAFOverviewChunk CAFOverviewChunk;
struct CAFUMIDChunk
{
UInt8 mBytes[64];
} ATTRIBUTE_PACKED;
typedef struct CAFUMIDChunk CAFUMIDChunk;
#if TARGET_OS_WIN32
#pragma pack(pop)
#endif
////////////////////////////////////////////////////////////////////////////////////////////////
#endif // AudioToolbox_CAFFile_h
#else
#include <AudioToolboxCore/CAFFile.h>
#endif

View File

@@ -0,0 +1,40 @@
#if (defined(__USE_PUBLIC_HEADERS__) && __USE_PUBLIC_HEADERS__) || (defined(USE_AUDIOTOOLBOX_PUBLIC_HEADERS) && USE_AUDIOTOOLBOX_PUBLIC_HEADERS) || !__has_include(<AudioToolboxCore/CAShow.h>)
/*!
@file CAShow.h
@framework AudioToolbox.framework
@copyright (c) 2002-2018 by Apple, Inc., all rights reserved.
@abstract Interfaces to log the internal state of various AudioToolbox objects.
*/
#ifndef AudioToolbox_CAShow_h
#define AudioToolbox_CAShow_h
#include <Availability.h>
#include <CoreFoundation/CFBase.h>
#include <os/base.h>
#include <stdio.h>
CF_ASSUME_NONNULL_BEGIN
#ifdef __cplusplus
extern "C" {
#endif
/// Print the internal state of an object to os_log.
OS_EXPORT void CAShow(void *inObject)
API_AVAILABLE(macos(10.2), ios(2.0), watchos(2.0), tvos(9.0));
/// Print the internal state of an object to the supplied FILE*.
OS_EXPORT void CAShowFile(void *inObject, FILE *inFile)
API_AVAILABLE(macos(10.2), ios(2.0), watchos(2.0), tvos(9.0));
#ifdef __cplusplus
}
#endif
CF_ASSUME_NONNULL_END
#endif /* AudioToolbox_CAShow_h */
#else
#include <AudioToolboxCore/CAShow.h>
#endif

View File

@@ -0,0 +1,940 @@
/*!
@file CoreAudioClock.h
@framework AudioToolbox.framework
@copyright (c) 2004-2015 by Apple, Inc., all rights reserved.
@abstract Services for audio and MIDI-related synchronization and
time unit conversions.
*/
#ifndef AudioToolbox_CoreAudioClock_h
#define AudioToolbox_CoreAudioClock_h
//==================================================================================================
#include <TargetConditionals.h>
#if TARGET_OS_OSX
#include <Availability.h>
#include <CoreAudioTypes/CoreAudioTypes.h>
#include <AudioToolbox/MusicPlayer.h>
CF_ASSUME_NONNULL_BEGIN
//==================================================================================================
/*!
@enum CAClockPropertyID
@abstract The properties of a CoreAudioClock, accessible via CAClockGetProperty and
CAClockSetProperty.
@constant kCAClockProperty_InternalTimebase
Type: CAClockTimebase. Selects the internal time reference for the clock
(currently, host time, an audio device, or audio output unit).
@constant kCAClockProperty_TimebaseSource
Type: according to the internal timebase. If the timebase is
kCAClockTimebase_AudioDevice, the value is an AudioDeviceID. For
kCAClockTimebase_AudioOutputUnit, the value is an AudioUnit.
@constant kCAClockProperty_SyncMode
Type: CAClockSyncMode. Selects between internal synchronization and multiple
external synchronization modes such as MIDI Time Code and MIDI beat clock.
@constant kCAClockProperty_SyncSource
Type: according to the sync mode. For kCAClockSyncMode_MIDIClockTransport or
kCAClockSyncMode_MTCTransport, the value is a MIDIEndpointRef.
@constant kCAClockProperty_SMPTEFormat
Type: CAClockSMPTEFormat. Specifies the SMPTE format (fps, drop or non-drop)
expected for received SMPTE messages, and used for transmitted SMPTE
messages and SMPTE time representations.
@constant kCAClockProperty_SMPTEOffset
Type: CAClockSeconds. The SMPTE time, represented in seconds since
00:00:00:00, corresponding to a timeline position of 0 seconds.
@constant kCAClockProperty_MIDIClockDestinations
Type: array of MIDIEndpointRef. When non-empty, the clock will transmit
MIDI beat clock to the MIDI endpoints in this list. (As of macOS 10.6,
the endpoints may be virtual sources. Previously, they had to be destinations.)
@constant kCAClockProperty_MTCDestinations
Type: array of MIDIEndpointRef. When non-empty, the clock will transmit
MIDI Time Code to the MIDI endpoints in this list. (As of macOS 10.6,
the endpoints may be virtual sources. Previously, they had to be destinations.)
@constant kCAClockProperty_MTCFreewheelTime
Type: CAClockSeconds. When the sync mode is MIDI Time Code, this controls
how long the reader will keep running after the last MTC message is received
before stopping (default: 1 sec). Should be at least ~4 SMPTE frames in
duration.
@constant kCAClockProperty_TempoMap
Type: array of CATempoMapEntry. Specifies a tempo map for the clock,
defining the relationship between timeline positions in seconds and musical
beats. Defaults to a constant tempo of 120 bpm.
@constant kCAClockProperty_MeterTrack
Type: array of CAMeterTrackEntry. Specifies the positions of musical time
signature changes in the timeline. Used only for converting between beats
and CABarBeatTime's (a display representation of a beat time).
@constant kCAClockProperty_Name
Type: CFStringRef. Sets a name for the clock. When a client sets the
property, the clock retains a reference to the string. When a client gets
the property, it receives a borrowed reference (i.e. the client must not
release the string).
@constant kCAClockProperty_SendMIDISPP
Type: UInt32. Specifies whether MIDI Song Position Pointer messages are
sent to the clock's MIDI clock destinations (if any). Available starting
in macOS 10.6.
*/
typedef CF_ENUM(UInt32, CAClockPropertyID) {
kCAClockProperty_InternalTimebase = 'intb',
kCAClockProperty_TimebaseSource = 'itbs',
kCAClockProperty_SyncMode = 'synm',
kCAClockProperty_SyncSource = 'syns',
kCAClockProperty_SMPTEFormat = 'smpf',
kCAClockProperty_SMPTEOffset = 'smpo',
kCAClockProperty_MIDIClockDestinations = 'mbcd',
kCAClockProperty_MTCDestinations = 'mtcd',
kCAClockProperty_MTCFreewheelTime = 'mtfw',
kCAClockProperty_TempoMap = 'tmpo',
kCAClockProperty_MeterTrack = 'metr',
kCAClockProperty_Name = 'name',
kCAClockProperty_SendMIDISPP = 'mspp'
};
/*!
@enum CAClockTimebase
@abstract The available internal hardware time references for a clock.
@constant kCAClockTimebase_HostTime
The clock's reference time is host time (as returned
by <code>mach_absolute_time()</code> or
<code>HostTime()</code>).
@constant kCAClockTimebase_AudioDevice
The clock's reference time is derived from an audio
device.
@constant kCAClockTimebase_AudioOutputUnit
The clock's reference time is derived from the audio
device addressed by an output Audio Unit.
*/
typedef CF_ENUM(UInt32, CAClockTimebase) {
kCAClockTimebase_HostTime = 'host',
kCAClockTimebase_AudioDevice = 'audi',
kCAClockTimebase_AudioOutputUnit = 'auou'
};
/*!
@enum CAClockSyncMode
@abstract Specifies internal synchronization, or an external sync source type.
@constant kCAClockSyncMode_Internal
The clock is not driven by an external sync source.
@constant kCAClockSyncMode_MIDIClockTransport
The clock is driven by MIDI beat clock received from a CoreMIDI source
endpoint.
@constant kCAClockSyncMode_MTCTransport
The clock is driven by MIDI Time Code received from a CoreMIDI source
endpoint.
*/
typedef CF_ENUM(UInt32, CAClockSyncMode) {
kCAClockSyncMode_Internal = 'intr', // sync to the internal timebase
kCAClockSyncMode_MIDIClockTransport = 'mclk', // sync to MIDI beat clock, external transport
kCAClockSyncMode_MTCTransport = 'mmtc' // sync to MIDI Time Code, external transport
};
/* From CoreAudioTypes.h:
enum {
kSMPTETimeType24 = 0,
kSMPTETimeType25 = 1,
kSMPTETimeType30Drop = 2,
kSMPTETimeType30 = 3,
kSMPTETimeType2997 = 4,
kSMPTETimeType2997Drop = 5
};
*/
// we can remove this after the SDK's have the real declaration.
#if !defined(COREAUDIOTYPES_VERSION) || COREAUDIOTYPES_VERSION <= 1051
#define SMPTETimeType UInt32
#endif
/*!
@typedef CAClockSMPTEFormat
@abstract A SMPTE format, specifying the frames per second (fps) and
whether it is drop frame.
The possible values of a CAClockSMPTEFormat are found in <CoreAudioTypes/CoreAudioTypes.h>.
Values include kSMPTETimeType30, kSMPTETimeType30Drop, etc. Note that formats with more than 30
fps are not usable with MIDI Time Code.
*/
typedef SMPTETimeType CAClockSMPTEFormat;
/*!
@enum CAClockMessage
@abstract The messages sent to a CAClockListenerProc to notify the client of
changes to the clock's state.
@constant kCAClockMessage_StartTimeSet
A new start time was set or received from an external sync source.
@constant kCAClockMessage_Started
The clock's time has started moving.
@constant kCAClockMessage_Stopped
The clock's time has stopped moving.
@constant kCAClockMessage_Armed
The client has called CAClockArm().
@constant kCAClockMessage_Disarmed
The client has called CAClockDisarm().
@constant kCAClockMessage_PropertyChanged
A clock property has been changed.
@constant kCAClockMessage_WrongSMPTEFormat
The clock is receiving SMPTE (MTC) messages in a SMPTE format that does not
match the clock's SMPTE format.
*/
typedef CF_ENUM(UInt32, CAClockMessage) {
kCAClockMessage_StartTimeSet = 'stim',
kCAClockMessage_Started = 'strt',
kCAClockMessage_Stopped = 'stop',
kCAClockMessage_Armed = 'armd',
kCAClockMessage_Disarmed = 'darm',
kCAClockMessage_PropertyChanged = 'pchg',
kCAClockMessage_WrongSMPTEFormat = '?smp'
};
/*!
@enum CAClockTimeFormat
@abstract The various units in which a clock can represent and report time.
@constant kCAClockTimeFormat_HostTime
Absolute host time, as returned by <code>mach_absolute_time()</code>.
@constant kCAClockTimeFormat_Samples
Absolute audio samples, as a Float64. Available when the internal timebase
is an audio device (or audio output unit). The units are in arbitrary sample
numbers, corresponding to the audio device's current time, and at the
device's current sample rate.
@constant kCAClockTimeFormat_Beats
Musical beats, as a Float64. This is a position on the clock's timeline.
@constant kCAClockTimeFormat_Seconds
Seconds, as a Float64. This is a position on the clock's timeline.
@constant kCAClockTimeFormat_SMPTESeconds
Seconds, as a Float64. This is the same as kCAClockTimeFormat_Seconds,
except that the clock's SMPTE offset has been applied.
@constant kCAClockTimeFormat_SMPTETime
SMPTETime structure.
*/
typedef CF_ENUM(UInt32, CAClockTimeFormat) {
kCAClockTimeFormat_HostTime = 'host',
kCAClockTimeFormat_Samples = 'samp',
kCAClockTimeFormat_Beats = 'beat', // relative position on media timeline
kCAClockTimeFormat_Seconds = 'secs', // relative position on media timeline
kCAClockTimeFormat_SMPTESeconds = 'smps', // absolute SMPTE position in seconds
kCAClockTimeFormat_SMPTETime = 'smpt', // SMPTETime structure
kCAClockTimeFormat_AbsoluteSeconds = 'asec'
};
CF_ENUM(OSStatus) { // errors
kCAClock_UnknownPropertyError = -66816,
kCAClock_InvalidPropertySizeError = -66815,
kCAClock_InvalidTimeFormatError = -66814,
kCAClock_InvalidSyncModeError = -66813,
kCAClock_InvalidSyncSourceError = -66812,
kCAClock_InvalidTimebaseError = -66811,
kCAClock_InvalidTimebaseSourceError = -66810,
kCAClock_InvalidSMPTEFormatError = -66809,
kCAClock_InvalidSMPTEOffsetError = -66808,
kCAClock_InvalidUnitError = -66807, // e.g. asking for audio samples when sync source
// not associated with an audio device
kCAClock_InvalidPlayRateError = -66806,
kCAClock_CannotSetTimeError = -66805 // can't SetCurrentTime unless stopped
// or can't SetCurrentTempo unless running
};
//==================================================================================================
/*!
@typedef CAClockRef
@abstract A reference to a Core Audio Clock object.
*/
typedef struct OpaqueCAClock * CAClockRef;
/*!
@typedef CAClockBeats
@abstract MIDI quarter notes (see MIDI specs)
*/
typedef Float64 CAClockBeats;
/*!
@typedef CAClockTempo
@abstract A musical tempo in beats per minute.
*/
typedef Float64 CAClockTempo; // beats per minute
/*
@typedef CAClockSamples
@abstract Audio samples.
*/
typedef Float64 CAClockSamples;
/*
@typedef CAClockSeconds
@abstract Seconds.
*/
typedef Float64 CAClockSeconds;
struct MIDIPacketList;
//==================================================================================================
/*!
@typedef CAClockListenerProc
@abstract A client-supplied function called when the clock's state changes.
@param userData
The value passed to CAClockAddListener when the callback function
was installed.
@param message
Signifies the kind of event which occurred.
@param param
This value is specific to the message (currently no messages have values).
*/
typedef void (*CAClockListenerProc)(void *userData, CAClockMessage message, const void *param);
/*!
@struct CAClockTime
@abstract Represents a time value using one of several possible units.
@var format
Specifies the time's format and units.
@var reserved
Must be 0.
@var time
The time value. Use the member of the union appropriate to the format (see the
description of CAClockTimeFormat).
*/
struct CAClockTime {
CAClockTimeFormat format;
UInt32 reserved;
union {
UInt64 hostTime;
CAClockSamples samples;
CAClockBeats beats;
CAClockSeconds seconds;
SMPTETime smpte;
} time;
};
typedef struct CAClockTime CAClockTime;
/*!
@struct CATempoMapEntry
@abstract A tempo change event.
The clock's tempo map defines the correspondence between seconds and musical
beats, and is used in conversions between the two.
@var beats
The beat time at which the tempo changes.
@var tempoBPM
The new tempo as of that time.
*/
struct CATempoMapEntry {
CAClockBeats beats;
CAClockTempo tempoBPM; // beats per minute
};
typedef struct CATempoMapEntry CATempoMapEntry;
/*!
@struct CAMeterTrackEntry
@abstract A time signature change event.
The meter track is used for converting between beats as floating-point
numbers (CAClockBeats) and their display representations (CABarBeatTime).
@var beats
The beat time at which the time signature (meter) changes.
@var meterNumer
The numerator of the new time signature.
@var meterDenom
The denominator of the new time signature (1, 2, 4, 8, etc.).
*/
struct CAMeterTrackEntry {
CAClockBeats beats;
UInt16 meterNumer;
UInt16 meterDenom; // 1,2,4,8 etc.
};
typedef struct CAMeterTrackEntry CAMeterTrackEntry;
//==================================================================================================
#ifdef __cplusplus
extern "C" {
#endif
// -----------------------------------------------------------------------------
/*!
@function CAClockNew
@abstract Create a new clock object.
@param inReservedFlags
Must be 0.
@param outCAClock
Must be non-null. On successful return, the new clock object.
@result An OSStatus error code.
*/
extern OSStatus
CAClockNew( UInt32 inReservedFlags,
CAClockRef __nullable * __nonnull outCAClock) API_AVAILABLE(macos(10.4)) API_UNAVAILABLE(ios, watchos, tvos);
// -----------------------------------------------------------------------------
/*!
@function CAClockDispose
@abstract Dispose a clock object.
@param inCAClock
The clock object to be disposed.
@result An OSStatus error code.
*/
extern OSStatus
CAClockDispose( CAClockRef inCAClock) API_AVAILABLE(macos(10.4)) API_UNAVAILABLE(ios, watchos, tvos);
// -----------------------------------------------------------------------------
/*!
@function CAClockGetPropertyInfo
@abstract Gets information about a clock's property.
@param inCAClock
The clock object.
@param inPropertyID
The property being queried.
@param outSize
If non-null, on exit, this is set to the size of the
property's value.
@param outWritable
If non-null, on exit, this indicates whether the
property value is settable.
@result An OSStatus error code.
*/
extern OSStatus
CAClockGetPropertyInfo( CAClockRef inCAClock,
CAClockPropertyID inPropertyID,
UInt32 * __nullable outSize,
Boolean * __nullable outWritable) API_AVAILABLE(macos(10.4)) API_UNAVAILABLE(ios, watchos, tvos);
// -----------------------------------------------------------------------------
/*!
@function CAClockGetProperty
@abstract Gets the current value of a clock's property.
@param inCAClock
The clock object.
@param inPropertyID
The property being fetched.
@param ioPropertyDataSize
On entry, the size (in bytes) of the memory pointed to
by outPropertyData. On exit, the actual size of the
property data returned.
@param outPropertyData
The value of the property is copied to the memory
this points to.
@result An OSStatus error code.
*/
extern OSStatus
CAClockGetProperty( CAClockRef inCAClock,
CAClockPropertyID inPropertyID,
UInt32 * ioPropertyDataSize,
void * outPropertyData) API_AVAILABLE(macos(10.4)) API_UNAVAILABLE(ios, watchos, tvos);
// -----------------------------------------------------------------------------
/*!
@function CAClockSetProperty
@abstract Changes the value of a clock's property.
@param inCAClock
The clock object.
@param inPropertyID
The property being set.
@param inPropertyDataSize
The size of the property data, in bytes.
@param inPropertyData
Points to the property's new value.
@result An OSStatus error code.
*/
extern OSStatus
CAClockSetProperty( CAClockRef inCAClock,
CAClockPropertyID inPropertyID,
UInt32 inPropertyDataSize,
const void * inPropertyData) API_AVAILABLE(macos(10.4)) API_UNAVAILABLE(ios, watchos, tvos);
// -----------------------------------------------------------------------------
/*!
@function CAClockAddListener
@abstract Adds a callback function to receive notifications of changes to the clock's
state.
Note: The CAClockListenerProc may be called on a realtime thread internal to
the clock object.
@param inCAClock
The clock object.
@param inListenerProc
The callback function.
@param inUserData
This value is passed to the callback function, in the userData
parameter.
@result An OSStatus error code.
*/
extern OSStatus
CAClockAddListener( CAClockRef inCAClock,
CAClockListenerProc inListenerProc,
void * inUserData) API_AVAILABLE(macos(10.4)) API_UNAVAILABLE(ios, watchos, tvos);
// -----------------------------------------------------------------------------
/*!
@function CAClockRemoveListener
@abstract Removes a listener callback function.
@param inCAClock
The clock object.
@param inListenerProc
The callback function.
@param inUserData
The same value as was passed for inUserData when this
function was registered with CAClockAddListener. (This
allows a single callback function to be registered more
than once, with different userData arguments.)
@result An OSStatus error code.
*/
extern OSStatus
CAClockRemoveListener( CAClockRef inCAClock,
CAClockListenerProc inListenerProc,
void * inUserData) API_AVAILABLE(macos(10.4)) API_UNAVAILABLE(ios, watchos, tvos);
// -----------------------------------------------------------------------------
/*!
@function CAClockSetCurrentTime
@abstract Sets the clock's current position on the media timeline.
Call this to specify where on the media timeline playback will begin. The
supplied time must be in seconds, beats, or SMPTE (not host time or audio
samples). Must only be called when stopped.
@param inCAClock
The clock object.
@param inTime
The new time position.
@result An OSStatus error code.
*/
extern OSStatus
CAClockSetCurrentTime( CAClockRef inCAClock,
const CAClockTime * inTime) API_AVAILABLE(macos(10.4)) API_UNAVAILABLE(ios, watchos, tvos);
// -----------------------------------------------------------------------------
/*!
@function CAClockGetCurrentTime
@abstract Obtain the clock's current position on the media timeline.
@param inCAClock
The clock object.
@param inTimeFormat
Specifies the desired format for outTime.
@param outTime
On exit, the clock's current time position.
@result An OSStatus error code.
*/
extern OSStatus
CAClockGetCurrentTime( CAClockRef inCAClock,
CAClockTimeFormat inTimeFormat,
CAClockTime * outTime) API_AVAILABLE(macos(10.4)) API_UNAVAILABLE(ios, watchos, tvos);
// -----------------------------------------------------------------------------
/*!
@function CAClockGetStartTime
@abstract Obtain the position on the media timeline where playback will start,
or has already started.
@param inCAClock
The clock object.
@param inTimeFormat
Specifies the desired format for outTime.
@param outTime
On exit, the clock's start time position.
@result An OSStatus error code.
*/
extern OSStatus
CAClockGetStartTime( CAClockRef inCAClock,
CAClockTimeFormat inTimeFormat,
CAClockTime * outTime) API_AVAILABLE(macos(10.4)) API_UNAVAILABLE(ios, watchos, tvos);
// -----------------------------------------------------------------------------
/*!
@function CAClockTranslateTime
@abstract Convert between time units.
@param inCAClock
The clock object.
@param inTime
The time to be converted.
@param inOutputTimeFormat
Specifies the desired format for outTime
@param outTime
On exit, a time corresponding to inTime, converted to the desired
time format.
@result An OSStatus error code.
*/
extern OSStatus
CAClockTranslateTime( CAClockRef inCAClock,
const CAClockTime * inTime,
CAClockTimeFormat inOutputTimeFormat,
CAClockTime * outTime) API_AVAILABLE(macos(10.4)) API_UNAVAILABLE(ios, watchos, tvos);
// -----------------------------------------------------------------------------
/*!
@function CAClockStart
@abstract Begin advancing the clock on its media timeline.
@param inCAClock
The clock object.
@result An OSStatus error code.
*/
extern OSStatus
CAClockStart( CAClockRef inCAClock) API_AVAILABLE(macos(10.4)) API_UNAVAILABLE(ios, watchos, tvos);
// -----------------------------------------------------------------------------
/*!
@function CAClockStop
@abstract Stop advancing the clock on its media timeline.
@param inCAClock
The clock object.
@result An OSStatus error code.
*/
extern OSStatus
CAClockStop( CAClockRef inCAClock) API_AVAILABLE(macos(10.4)) API_UNAVAILABLE(ios, watchos, tvos);
// -----------------------------------------------------------------------------
/*!
@function CAClockArm
@abstract Allow received sync messages to start the clock.
If a clock is following and being controlled by an external transport
(e.g. MIDI Time Code), call this to indicate that the client is ready to
start its transport in response to the external transport having started.
The external time source will set the clock's start position and start
the clock.
@param inCAClock
The clock object.
@result An OSStatus error code.
*/
extern OSStatus
CAClockArm( CAClockRef inCAClock) API_AVAILABLE(macos(10.4)) API_UNAVAILABLE(ios, watchos, tvos);
// -----------------------------------------------------------------------------
/*!
@function CAClockDisarm
@abstract Disallow received sync messages from starting the clock.
@param inCAClock
The clock object.
@result An OSStatus error code.
*/
extern OSStatus
CAClockDisarm( CAClockRef inCAClock) API_AVAILABLE(macos(10.4)) API_UNAVAILABLE(ios, watchos, tvos);
// -----------------------------------------------------------------------------
/*!
@function CAClockSetPlayRate
@abstract Alter the clock's playback rate.
Adjusts the ratio between the timebase and media time; e.g. at 0.5, the
media time will move half as quickly as timebase time.
@param inCAClock
The clock object.
@param inPlayRate
The clock's desired play rate.
@result An OSStatus error code.
*/
extern OSStatus
CAClockSetPlayRate( CAClockRef inCAClock,
Float64 inPlayRate) API_AVAILABLE(macos(10.4)) API_UNAVAILABLE(ios, watchos, tvos);
// -----------------------------------------------------------------------------
/*!
@function CAClockGetPlayRate
@abstract Obtain the clock's playback rate.
Returns the clock's current play rate. If the clock is internally synced,
this will be the last rate set by CAClockSetPlayRate. If the clock is
externally synced, it will be the rate of the external sync source, where
1.0 means that it is running at exactly the same rate as the clock's
timebase. (2.0 means twice as fast).
@param inCAClock
The clock object.
@param outPlayRate
On exit, the clock's playback rate.
@result An OSStatus error code.
*/
extern OSStatus
CAClockGetPlayRate( CAClockRef inCAClock,
Float64 * outPlayRate) API_AVAILABLE(macos(10.4)) API_UNAVAILABLE(ios, watchos, tvos);
// -----------------------------------------------------------------------------
/*!
@function CAClockGetCurrentTempo
@abstract Obtain the clock's current musical tempo.
Returns the current instantaneous tempo and a timestamp indicating where on the
timeline the tempo most recently changed.
If the clock is externally synced, the returned tempo will not reflect the
effective tempo; this routine always reflects the client-specified tempo. To
obtain the effective tempo, multiply the current tempo by the current play
rate.
@param inCAClock
The clock object.
@param outTempo
On exit, the current tempo.
@param outTimestamp
If non-null, on exit, the time at which the tempo last changed.
@result An OSStatus error code.
*/
extern OSStatus
CAClockGetCurrentTempo( CAClockRef inCAClock,
CAClockTempo * outTempo,
CAClockTime * __nullable outTimestamp) API_AVAILABLE(macos(10.4)) API_UNAVAILABLE(ios, watchos, tvos);
// -----------------------------------------------------------------------------
/*!
@function CAClockSetCurrentTempo
@abstract Manually override the clock's musical tempo during playback.
Effects a manual override of the tempo map while running. After stopping and
restarting, the original tempo map will be used again.
@param inCAClock
The clock object.
@param inTempo
The new desired tempo.
@param inTimestamp
Specifies a precise point on the timeline where the tempo change is to
take effect. If null, the tempo change takes effect immediately.
@result
An OSStatus error code. If this call is made while stopped,
kCAClock_CannotSetTimeError is returned.
*/
extern OSStatus
CAClockSetCurrentTempo( CAClockRef inCAClock,
CAClockTempo inTempo,
const CAClockTime * __nullable inTimestamp) API_AVAILABLE(macos(10.4)) API_UNAVAILABLE(ios, watchos, tvos);
// -----------------------------------------------------------------------------
/*!
@function CAClockSecondsToSMPTETime
@abstract Converts seconds to a SMPTE time representation.
Converts seconds on the media timeline to a SMPTE time. The clock's current
SMPTE format and offset must be set appropriately.
@param inCAClock
The clock object.
@param inSeconds
The number of seconds to be converted (e.g. 3600 = 1 hour).
@param inSubframeDivisor
The number of subframes per frame desired in outSMPTETime.
@param outSMPTETime
On exit, the SMPTE time corresponding to inSeconds.
@result An OSStatus error code.
*/
extern OSStatus
CAClockSecondsToSMPTETime( CAClockRef inCAClock,
CAClockSeconds inSeconds,
UInt16 inSubframeDivisor,
SMPTETime * outSMPTETime) API_AVAILABLE(macos(10.4)) API_UNAVAILABLE(ios, watchos, tvos);
// -----------------------------------------------------------------------------
/*!
@function CAClockSMPTETimeToSeconds
@abstract Converts a SMPTE time representation to seconds.
Converts SMPTE time to seconds on the media timeline. The clock's current
SMPTE format and offset must be set appropriately.
@param inCAClock
The clock object.
@param inSMPTETime
The SMPTE time to be converted to seconds.
@param outSeconds
On exit, the number of seconds corresponding to inSMPTETime.
@result An OSStatus error code.
*/
extern OSStatus
CAClockSMPTETimeToSeconds( CAClockRef inCAClock,
const SMPTETime * inSMPTETime,
CAClockSeconds * outSeconds) API_AVAILABLE(macos(10.4)) API_UNAVAILABLE(ios, watchos, tvos);
// -----------------------------------------------------------------------------
/*!
@function CAClockBeatsToBarBeatTime
@abstract Converts a number of beats to a CABarBeatTime structure.
Converts a beat position on the media timeline to a CABarBeatTime, using the
clock's meter track. Examples using 4/4 time and a subbeat divisor of 480:
inBeats | outBarBeatTime: bars . beats . units
--------|-------------------------------------
0 | 1.1.0
1 | 1.2.0
4 | 2.1.0
4.5 | 2.1.240
@param inCAClock
The clock object.
@param inBeats
The absolute beat count to be converted.
@param inSubbeatDivisor
The number of units per beat.
@param outBarBeatTime
On exit, the bar/beat/subbeat time corresponding to inBeats.
@result An OSStatus error code.
*/
extern OSStatus
CAClockBeatsToBarBeatTime( CAClockRef inCAClock,
CAClockBeats inBeats,
UInt16 inSubbeatDivisor,
CABarBeatTime * outBarBeatTime) API_AVAILABLE(macos(10.4)) API_UNAVAILABLE(ios, watchos, tvos);
// -----------------------------------------------------------------------------
/*!
@function CAClockBarBeatTimeToBeats
@abstract Converts a CABarBeatTime structure to a number of beats.
Converts a CABarBeatTime structure (bars/beats/subbeats) to a beat
position, using the clock's meter track.
@param inCAClock
The clock object.
@param inBarBeatTime
The bar/beat/subunit time to be converted to beats.
@param outBeats
On exit, the number of absolute beats corresponding to inBarBeatTime.
@result An OSStatus error code.
*/
extern OSStatus
CAClockBarBeatTimeToBeats( CAClockRef inCAClock,
const CABarBeatTime *inBarBeatTime,
CAClockBeats * outBeats) API_AVAILABLE(macos(10.4)) API_UNAVAILABLE(ios, watchos, tvos);
// -----------------------------------------------------------------------------
/*!
@function CAClockParseMIDI
@abstract Provides MIDI messages to a clock without using CoreMIDI
In some situations, a client may wish to drive a clock using MIDI Time Code or
beat clock obtained from a source other than Core MIDI. To do so,
construct MIDIPacketLists containing the timecode or beat clock messages,
and pass them to this function.
@param inCAClock
The clock object.
@param inMIDIPacketList
The MIDI events to be parsed.
@result An OSStatus error code.
*/
extern OSStatus
CAClockParseMIDI( CAClockRef inCAClock,
const struct MIDIPacketList *inMIDIPacketList) API_AVAILABLE(macos(10.5)) API_UNAVAILABLE(ios, watchos, tvos);
#ifdef __cplusplus
}
#endif
CF_ASSUME_NONNULL_END
#endif // TARGET_OS_OSX
#endif // AudioToolbox_CoreAudioClock_h

View File

@@ -0,0 +1,36 @@
/*!
@file DefaultAudioOutput.h
@framework AudioToolbox.framework
@copyright (c) 2000-2015 by Apple, Inc., all rights reserved.
@deprecated Contains deprecated API's.
*/
#ifndef AudioToolbox_DefaultAudioOutput_h
#define AudioToolbox_DefaultAudioOutput_h
#if !__LP64__
#include <Availability.h>
#if !defined(__COREAUDIO_USE_FLAT_INCLUDES__)
#include <AudioToolbox/AudioUnit.h>
#else
#include <AudioUnit.h>
#endif
#ifdef __cplusplus
extern "C" {
#endif
// Open an instance of the default audio output unit (it can be closed with CloseComponent).
extern OSStatus OpenDefaultAudioOutput(AudioUnit *outUnit) API_DEPRECATED("no longer supported", macos(10.0, 10.3)) API_UNAVAILABLE(ios, watchos, tvos);
extern OSStatus OpenSystemSoundAudioOutput(AudioUnit *outUnit) API_DEPRECATED("no longer supported", macos(10.1, 10.5)) API_UNAVAILABLE(ios, watchos, tvos);
// for system sounds like alerts, modems, etc.
#ifdef __cplusplus
}
#endif
#endif // !__LP64__
#endif // AudioToolbox_DefaultAudioOutput_h

View File

@@ -0,0 +1,610 @@
#if (defined(__USE_PUBLIC_HEADERS__) && __USE_PUBLIC_HEADERS__) || (defined(USE_AUDIOTOOLBOX_PUBLIC_HEADERS) && USE_AUDIOTOOLBOX_PUBLIC_HEADERS) || !__has_include(<AudioToolboxCore/ExtendedAudioFile.h>)
/*!
@file ExtendedAudioFile.h
@framework AudioToolbox.framework
@copyright (c) 2004-2015 by Apple, Inc., all rights reserved.
@abstract API's to support reading and writing files in encoded audio formats.
@discussion
The ExtendedAudioFile provides high-level audio file access, building
on top of the AudioFile and AudioConverter API sets. It provides a single
unified interface to reading and writing both encoded and unencoded files.
*/
#ifndef AudioToolbox_ExtendedAudioFile_h
#define AudioToolbox_ExtendedAudioFile_h
#include <AudioToolbox/AudioFile.h>
#ifdef __cplusplus
extern "C" {
#endif
CF_ASSUME_NONNULL_BEGIN
//==================================================================================================
// Types
/*!
@typedef ExtAudioFileRef
@abstract An extended audio file object.
*/
typedef struct OpaqueExtAudioFile * ExtAudioFileRef;
typedef SInt32 ExtAudioFilePacketTableInfoOverride;
CF_ENUM(ExtAudioFilePacketTableInfoOverride) {
kExtAudioFilePacketTableInfoOverride_UseFileValue = -1,
kExtAudioFilePacketTableInfoOverride_UseFileValueIfValid = -2
};
//==================================================================================================
// Properties
typedef UInt32 ExtAudioFilePropertyID;
/*!
enum ExtAudioFilePropertyID
@constant kExtAudioFileProperty_FileDataFormat
An AudioStreamBasicDescription. Represents the file's actual
data format. Read-only.
@constant kExtAudioFileProperty_FileChannelLayout
An AudioChannelLayout.
If writing: the channel layout is written to the file, if the format
supports the layout. If the format does not support the layout, the channel
layout is still interpreted as the destination layout when performing
conversion from the client channel layout, if any.
If reading: the specified layout overrides the one read from the file, if
any.
When setting this, it must be set before the client format or channel
layout.
@constant kExtAudioFileProperty_ClientDataFormat
An AudioStreamBasicDescription.
The format must be linear PCM (kAudioFormatLinearPCM).
You must set this in order to encode or decode a non-PCM file data format.
You may set this on PCM files to specify the data format used in your calls
to read/write.
@constant kExtAudioFileProperty_ClientChannelLayout
An AudioChannelLayout. Specifies the channel layout of the
AudioBufferList's passed to ExtAudioFileRead() and
ExtAudioFileWrite(). The layout may be different from the file's
channel layout, in which the ExtAudioFileRef's underlying AudioConverter
performs the remapping. This must be set after ClientDataFormat, and the
number of channels in the layout must match.
@constant kExtAudioFileProperty_CodecManufacturer
A UInt32 specifying the manufacturer of the codec to be used. This must be
specified before setting kExtAudioFileProperty_ClientDataFormat, which
triggers the creation of the codec. This can be used on iOS
to choose between a hardware or software encoder, by specifying
kAppleHardwareAudioCodecManufacturer or kAppleSoftwareAudioCodecManufacturer.
Available starting on macOS version 10.7 and iOS version 4.0.
@constant kExtAudioFileProperty_AudioConverter
AudioConverterRef. The underlying AudioConverterRef, if any. Read-only.
Note: If you alter any properties of the AudioConverterRef, for example,
an encoder's bit rate, you must set the kExtAudioFileProperty_ConverterConfig
property on the ExtAudioFileRef afterwards. A NULL configuration is
sufficient. This will ensure that the output file's data format is consistent
with the format being produced by the converter.
```
CFArrayRef config = NULL;
err = ExtAudioFileSetProperty(myExtAF, kExtAudioFileProperty_ConverterConfig,
sizeof(config), &config);
```
@constant kExtAudioFileProperty_AudioFile
The underlying AudioFileID. Read-only.
@constant kExtAudioFileProperty_FileMaxPacketSize
UInt32 representing the file data format's maximum packet size in bytes.
Read-only.
@constant kExtAudioFileProperty_ClientMaxPacketSize
UInt32 representing the client data format's maximum packet size in bytes.
Read-only.
@constant kExtAudioFileProperty_FileLengthFrames
SInt64 representing the file's length in sample frames. Read-only on
non-PCM formats; writable for files in PCM formats.
@constant kExtAudioFileProperty_ConverterConfig
CFArrayRef representing the underlying AudioConverter's configuration, as
specified by kAudioConverterPropertySettings.
This may be NULL to force resynchronization of the converter's output format
with the file's data format.
@constant kExtAudioFileProperty_IOBufferSizeBytes
UInt32 representing the size of the buffer through which the converter
reads/writes the audio file (when there is an AudioConverter).
@constant kExtAudioFileProperty_IOBuffer
void *. This is the memory buffer which the ExtAudioFileRef will use for
disk I/O when there is a conversion between the client and file data
formats. A client may be able to share buffers between multiple
ExtAudioFileRef instances, in which case, it can set this property to point
to its own buffer. After setting this property, the client must
subsequently set the kExtAudioFileProperty_IOBufferSizeBytes property. Note
that a pointer to a pointer should be passed to ExtAudioFileSetProperty.
@constant kExtAudioFileProperty_PacketTable
This AudioFilePacketTableInfo can be used both to override the priming and
remainder information in an audio file and to retrieve the current priming
and remainder frames information for a given ExtAudioFile object. If the
underlying file type does not provide packet table info, the Get call will
return an error.
If you set this, then you can override the setting for these values in the
file to ones that you want to use. When setting this, you can use
kExtAudioFilePacketTableInfoOverride_UseFileValue (-1) for either the
priming or remainder frames to signal that the value currently stored in
the file should be used. If you set this to a non-negative number (or zero)
then that value will override whatever value is stored in the file that
you are reading. Retrieving the value of the property will always retrieve
the value the ExtAudioFile object is using (whether this is derived from
the file, or from your override). If you want to determine what the value
is in the file, you should use the AudioFile property:
kAudioFilePropertyPacketTableInfo
If the value of mNumberValidFrames is positive, it will be used to override
the count of valid frames stored in the file. If you wish to override only
the priming and remainder frame values, you should set mNumberValidFrames
to zero.
For example, a file encoded using AAC may have 2112 samples of priming at
the start of the file and a remainder of 823 samples at the end. When
ExtAudioFile returns decoded samples to you, it will trim `mPrimingFrames`
at the start of the file, and `mRemainderFrames` at the end. It will get
these numbers initially from the file. A common use case for overriding this
would be to set the priming and remainder samples to 0, so in this example
you would retrieve an additional 2112 samples of silence from the start of
the file and 823 samples of silence at the end of the file (silence, because
the encoders use silence to pad out these priming and remainder samples)
A value of kExtAudioFilePacketTableInfoOverride_UseFileValueIfValid (-2)
for priming, remainder, or valid frames will cause the corresponding value
stored in the file to be used if the total number of frames produced by the
file matches the total frames accounted for by the packet table info stored
in the file. If these do not match, for priming or remainder frames a value
of 0 will be used instead, and for valid frames a value will be calculated
that causes the total frames accounted for by the overriding packet table
info to match the count of frames produced by the file.
*/
CF_ENUM(ExtAudioFilePropertyID) {
kExtAudioFileProperty_FileDataFormat = 'ffmt', // AudioStreamBasicDescription
kExtAudioFileProperty_FileChannelLayout = 'fclo', // AudioChannelLayout
kExtAudioFileProperty_ClientDataFormat = 'cfmt', // AudioStreamBasicDescription
kExtAudioFileProperty_ClientChannelLayout = 'cclo', // AudioChannelLayout
kExtAudioFileProperty_CodecManufacturer = 'cman', // UInt32
// read-only:
kExtAudioFileProperty_AudioConverter = 'acnv', // AudioConverterRef
kExtAudioFileProperty_AudioFile = 'afil', // AudioFileID
kExtAudioFileProperty_FileMaxPacketSize = 'fmps', // UInt32
kExtAudioFileProperty_ClientMaxPacketSize = 'cmps', // UInt32
kExtAudioFileProperty_FileLengthFrames = '#frm', // SInt64
// writable:
kExtAudioFileProperty_ConverterConfig = 'accf', // CFPropertyListRef
kExtAudioFileProperty_IOBufferSizeBytes = 'iobs', // UInt32
kExtAudioFileProperty_IOBuffer = 'iobf', // void *
kExtAudioFileProperty_PacketTable = 'xpti' // AudioFilePacketTableInfo
};
CF_ENUM(OSStatus) {
kExtAudioFileError_InvalidProperty = -66561,
kExtAudioFileError_InvalidPropertySize = -66562,
kExtAudioFileError_NonPCMClientFormat = -66563,
kExtAudioFileError_InvalidChannelMap = -66564, // number of channels doesn't match format
kExtAudioFileError_InvalidOperationOrder = -66565,
kExtAudioFileError_InvalidDataFormat = -66566,
kExtAudioFileError_MaxPacketSizeUnknown = -66567,
kExtAudioFileError_InvalidSeek = -66568, // writing, or offset out of bounds
kExtAudioFileError_AsyncWriteTooLarge = -66569,
kExtAudioFileError_AsyncWriteBufferOverflow = -66570 // an async write could not be completed in time
};
#if TARGET_OS_IPHONE
/*!
@enum ExtAudioFile errors
@constant kExtAudioFileError_CodecUnavailableInputConsumed
iOS only. Returned when ExtAudioFileWrite was interrupted. You must stop calling
ExtAudioFileWrite. If the underlying audio converter can resume after an
interruption (see kAudioConverterPropertyCanResumeFromInterruption), you must
wait for an EndInterruption notification from AudioSession, and call AudioSessionSetActive(true)
before resuming. In this situation, the buffer you provided to ExtAudioFileWrite was successfully
consumed and you may proceed to the next buffer.
@constant kExtAudioFileError_CodecUnavailableInputNotConsumed
iOS only. Returned when ExtAudioFileWrite was interrupted. You must stop calling
ExtAudioFileWrite. If the underlying audio converter can resume after an
interruption (see kAudioConverterPropertyCanResumeFromInterruption), you must
wait for an EndInterruption notification from AudioSession, and call AudioSessionSetActive(true)
before resuming. In this situation, the buffer you provided to ExtAudioFileWrite was not
successfully consumed and you must try to write it again.
*/
CF_ENUM(OSStatus) {
kExtAudioFileError_CodecUnavailableInputConsumed = -66559,
kExtAudioFileError_CodecUnavailableInputNotConsumed = -66560,
};
#endif
//==================================================================================================
// Creation/Destruction
/*!
@functiongroup Creation/Destruction
*/
/*!
@function ExtAudioFileOpenURL
@abstract Opens an audio file specified by a CFURLRef.
@param inURL
The audio file to read.
@param outExtAudioFile
On exit, a newly-allocated ExtAudioFileRef.
@result An OSStatus error code.
@discussion
Allocates a new ExtAudioFileRef, for reading an existing audio file.
*/
extern OSStatus
ExtAudioFileOpenURL( CFURLRef inURL,
ExtAudioFileRef __nullable * __nonnull outExtAudioFile) API_AVAILABLE(macos(10.5), ios(2.1), watchos(2.0), tvos(9.0));
/*!
@function ExtAudioFileWrapAudioFileID
@abstract Wrap an AudioFileID in an ExtAudioFileRef.
@param inFileID
The AudioFileID to wrap.
@param inForWriting
True if the AudioFileID is a new file opened for writing.
@param outExtAudioFile
On exit, a newly-allocated ExtAudioFileRef.
@result An OSStatus error code.
@discussion
Allocates a new ExtAudioFileRef which wraps an existing AudioFileID. The
client is responsible for keeping the AudioFileID open until the
ExtAudioFileRef is disposed. Disposing the ExtAudioFileRef will not close
the AudioFileID when this Wrap API call is used, so the client is also
responsible for closing the AudioFileID when finished with it.
*/
extern OSStatus
ExtAudioFileWrapAudioFileID(AudioFileID inFileID,
Boolean inForWriting,
ExtAudioFileRef __nullable * __nonnull outExtAudioFile)
API_AVAILABLE(macos(10.4), ios(2.1), watchos(2.0), tvos(9.0));
/*!
@function ExtAudioFileCreateWithURL
@abstract Create a new audio file.
@param inURL
The URL of the new audio file.
@param inFileType
The type of file to create. This is a constant from AudioToolbox/AudioFile.h, e.g.
kAudioFileAIFFType. Note that this is not an HFSTypeCode.
@param inStreamDesc
The format of the audio data to be written to the file.
@param inChannelLayout
The channel layout of the audio data. If non-null, this must be consistent
with the number of channels specified by inStreamDesc.
@param inFlags
The same flags as are used with AudioFileCreateWithURL
Can use these to control whether an existing file is overwritten (or not).
@param outExtAudioFile
On exit, a newly-allocated ExtAudioFileRef.
@result An OSStatus error code.
@discussion
Creates a new audio file.
If the file to be created is in an encoded format, it is permissible for the
sample rate in inStreamDesc to be 0, since in all cases, the file's encoding
AudioConverter may produce audio at a different sample rate than the source. The
file will be created with the audio format actually produced by the encoder.
*/
extern OSStatus
ExtAudioFileCreateWithURL( CFURLRef inURL,
AudioFileTypeID inFileType,
const AudioStreamBasicDescription * inStreamDesc,
const AudioChannelLayout * __nullable inChannelLayout,
UInt32 inFlags,
ExtAudioFileRef __nullable * __nonnull outExtAudioFile)
API_AVAILABLE(macos(10.5), ios(2.1), watchos(2.0), tvos(9.0));
#if !TARGET_OS_IPHONE
/*!
@function ExtAudioFileOpen
@abstract Opens an audio file specified by an FSRef.
@param inFSRef
The audio file to read.
@param outExtAudioFile
On exit, a newly-allocated ExtAudioFileRef.
@result An OSStatus error code.
@discussion
Allocates a new ExtAudioFileRef, for reading an existing audio file.
This function is deprecated as of Mac OS 10.6. ExtAudioFileOpenURL is preferred.
*/
extern OSStatus
ExtAudioFileOpen( const struct FSRef * inFSRef,
ExtAudioFileRef __nullable * __nonnull outExtAudioFile) API_DEPRECATED("no longer supported", macos(10.4, 10.6)) API_UNAVAILABLE(ios, watchos, tvos);
/*!
@function ExtAudioFileCreateNew
@abstract Creates a new audio file.
@param inParentDir
The directory in which to create the new file.
@param inFileName
The name of the new file.
@param inFileType
The type of file to create. This is a constant from AudioToolbox/AudioFile.h, e.g.
kAudioFileAIFFType. Note that this is not an HFSTypeCode.
@param inStreamDesc
The format of the audio data to be written to the file.
@param inChannelLayout
The channel layout of the audio data. If non-null, this must be consistent
with the number of channels specified by inStreamDesc.
@param outExtAudioFile
On exit, a newly-allocated ExtAudioFileRef.
@result An OSStatus error code.
@discussion
If the file to be created is in an encoded format, it is permissible for the
sample rate in inStreamDesc to be 0, since in all cases, the file's encoding
AudioConverter may produce audio at a different sample rate than the source. The
file will be created with the audio format actually produced by the encoder.
This function is deprecated as of Mac OS 10.6. ExtAudioFileCreateWithURL is preferred.
*/
extern OSStatus
ExtAudioFileCreateNew( const struct FSRef * inParentDir,
CFStringRef inFileName,
AudioFileTypeID inFileType,
const AudioStreamBasicDescription * inStreamDesc,
const AudioChannelLayout * __nullable inChannelLayout,
ExtAudioFileRef __nullable * __nonnull outExtAudioFile)
API_DEPRECATED("no longer supported", macos(10.4, 10.6)) API_UNAVAILABLE(ios, watchos, tvos);
#endif
/*!
@function ExtAudioFileDispose
@abstract Close the file and dispose the object.
@param inExtAudioFile
The extended audio file object.
@result An OSStatus error code.
@discussion
Closes the file and deletes the object.
*/
extern OSStatus
ExtAudioFileDispose( ExtAudioFileRef inExtAudioFile)
API_AVAILABLE(macos(10.4), ios(2.1), watchos(2.0), tvos(9.0));
//==================================================================================================
// I/O
/*!
@functiongroup I/O
*/
/*!
@function ExtAudioFileRead
@abstract Perform a synchronous sequential read.
@param inExtAudioFile
The extended audio file object.
@param ioNumberFrames
On entry, ioNumberFrames is the number of frames to be read from the file.
On exit, it is the number of frames actually read. A number of factors may
cause a fewer number of frames to be read, including the supplied buffers
not being large enough, and internal optimizations. If 0 frames are
returned, however, this indicates that end-of-file was reached.
@param ioData
Buffer(s) into which the audio data is read.
@result An OSStatus error code.
@discussion
If the file has a client data format, then the audio data from the file is
translated from the file data format to the client format, via the
ExtAudioFile's internal AudioConverter.
(Note that the use of sequential reads/writes means that an ExtAudioFile must
not be read on multiple threads; clients wishing to do this should use the
lower-level AudioFile API set).
*/
extern OSStatus
ExtAudioFileRead( ExtAudioFileRef inExtAudioFile,
UInt32 * ioNumberFrames,
AudioBufferList * ioData)
API_AVAILABLE(macos(10.4), ios(2.1), watchos(2.0), tvos(9.0));
/*!
@function ExtAudioFileWrite
@abstract Perform a synchronous sequential write.
@param inExtAudioFile
The extended audio file object.
@param inNumberFrames
The number of frames to write.
@param ioData
The buffer(s) from which audio data is written to the file.
@result An OSStatus error code.
@discussion
If the file has a client data format, then the audio data in ioData is
translated from the client format to the file data format, via the
ExtAudioFile's internal AudioConverter.
*/
extern OSStatus
ExtAudioFileWrite( ExtAudioFileRef inExtAudioFile,
UInt32 inNumberFrames,
const AudioBufferList * ioData)
API_AVAILABLE(macos(10.4), ios(2.1), watchos(2.0), tvos(9.0));
/*!
@function ExtAudioFileWriteAsync
@abstract Perform an asynchronous sequential write.
@param inExtAudioFile
The extended audio file object.
@param inNumberFrames
The number of frames to write.
@param ioData
The buffer(s) from which audio data is written to the file.
@result An OSStatus error code.
@discussion
Writes the provided buffer list to an internal ring buffer and notifies an
internal thread to perform the write at a later time. The first time this is
called, allocations may be performed. You can call this with 0 frames and null
buffer in a non-time-critical context to initialize the asynchronous mechanism.
Once initialized, subsequent calls are very efficient and do not take locks;
thus this may be used to write to a file from a realtime thread.
The client must not mix synchronous and asynchronous writes to the same file.
Pending writes are not guaranteed to be flushed to disk until
ExtAudioFileDispose is called.
N.B. Errors may occur after this call has returned. Such errors may be returned
from subsequent calls to this function.
*/
extern OSStatus
ExtAudioFileWriteAsync( ExtAudioFileRef inExtAudioFile,
UInt32 inNumberFrames,
const AudioBufferList * __nullable ioData)
API_AVAILABLE(macos(10.4), ios(2.1), watchos(2.0), tvos(9.0));
/*!
@function ExtAudioFileSeek
@abstract Seek to a specific frame position.
@param inExtAudioFile
The extended audio file object.
@param inFrameOffset
The desired seek position, in sample frames, relative to the beginning of
the file. This is specified in the sample rate and frame count of the file's format
(not the client format)
@result An OSStatus error code.
@discussion
Sets the file's read position to the specified sample frame number. The next call
to ExtAudioFileRead will return samples from precisely this location, even if it
is located in the middle of a packet.
This function's behavior with files open for writing is currently undefined.
*/
extern OSStatus
ExtAudioFileSeek( ExtAudioFileRef inExtAudioFile,
SInt64 inFrameOffset)
API_AVAILABLE(macos(10.4), ios(2.1), watchos(2.0), tvos(9.0));
/*!
@function ExtAudioFileTell
@abstract Return the file's read/write position.
@param inExtAudioFile
The extended audio file object.
@param outFrameOffset
On exit, the file's current read/write position in sample frames. This is specified in the
sample rate and frame count of the file's format (not the client format)
@result An OSStatus error code.
*/
extern OSStatus
ExtAudioFileTell( ExtAudioFileRef inExtAudioFile,
SInt64 * outFrameOffset)
API_AVAILABLE(macos(10.4), ios(2.1), watchos(2.0), tvos(9.0));
//==================================================================================================
// Property Access
/*!
@functiongroup Property Access
*/
/*!
@function ExtAudioFileGetPropertyInfo
@abstract Get information about a property
@param inExtAudioFile
The extended audio file object.
@param inPropertyID
The property being queried.
@param outSize
If non-null, on exit, this is set to the size of the property's value.
@param outWritable
If non-null, on exit, this indicates whether the property value is settable.
@result An OSStatus error code.
*/
extern OSStatus
ExtAudioFileGetPropertyInfo(ExtAudioFileRef inExtAudioFile,
ExtAudioFilePropertyID inPropertyID,
UInt32 * __nullable outSize,
Boolean * __nullable outWritable)
API_AVAILABLE(macos(10.4), ios(2.1), watchos(2.0), tvos(9.0));
/*!
@function ExtAudioFileGetProperty
@abstract Get a property value.
@param inExtAudioFile
The extended audio file object.
@param inPropertyID
The property being fetched.
@param ioPropertyDataSize
On entry, the size (in bytes) of the memory pointed to by outPropertyData.
On exit, the actual size of the property data returned.
@param outPropertyData
The value of the property is copied to the memory this points to.
@result An OSStatus error code.
*/
extern OSStatus
ExtAudioFileGetProperty( ExtAudioFileRef inExtAudioFile,
ExtAudioFilePropertyID inPropertyID,
UInt32 * ioPropertyDataSize,
void * outPropertyData)
API_AVAILABLE(macos(10.4), ios(2.1), watchos(2.0), tvos(9.0));
/*!
@function ExtAudioFileSetProperty
@abstract Set a property value.
@param inExtAudioFile
The extended audio file object.
@param inPropertyID
The property being set.
@param inPropertyDataSize
The size of the property data, in bytes.
@param inPropertyData
Points to the property's new value.
@result An OSStatus error code.
*/
extern OSStatus
ExtAudioFileSetProperty( ExtAudioFileRef inExtAudioFile,
ExtAudioFilePropertyID inPropertyID,
UInt32 inPropertyDataSize,
const void * inPropertyData)
API_AVAILABLE(macos(10.4), ios(2.1), watchos(2.0), tvos(9.0));
CF_ASSUME_NONNULL_END
#ifdef __cplusplus
}
#endif
#endif // AudioToolbox_ExtendedAudioFile_h
#else
#include <AudioToolboxCore/ExtendedAudioFile.h>
#endif

View File

@@ -0,0 +1,481 @@
#if (defined(__USE_PUBLIC_HEADERS__) && __USE_PUBLIC_HEADERS__) || (defined(USE_AUDIOTOOLBOX_PUBLIC_HEADERS) && USE_AUDIOTOOLBOX_PUBLIC_HEADERS) || !__has_include(<AudioToolboxCore/MusicDevice.h>)
/*!
@file MusicDevice.h
@framework AudioToolbox.framework
@copyright (c) 2000-2015 Apple, Inc. All rights reserved.
@abstract Additional Audio Unit API for software musical instruments.
@discussion
A music device audio unit, commonly referred to as a music instrument, is used to render notes.
A note is a sound, usually pitched, that is started and stopped with a note number or pitch
specifier. A note is played on a group (in MIDI this is called a MIDI Channel) and the various
state values of a group (such as pitch bend, after-touch, etc) is inherited and controlled by
every playing note on a given group. A note can be individually stopped (which is the common
case), or stopped with the "All Notes Off" message that is sent to a specific group.
A music instrument can be multi-timbral - that is, each group can have a particular patch (or
sound) associated with it, and different groups can have different patches. This is a common
case for music instruments that implement the General MIDI specification. In this case, the
music instrument should return the number of available patches at a given time as the value for
the _InstrumentCount property.
It is also common for instruments to be mono-timbral - that is, they are only capable of
producing notes using a single patch/sound and typically only respond to commands on one group.
In this case, the music instrument should return 0 as the value for the _InstrumentCount
property.
Parameters can be defined in Group Scope, and these parameter IDs within the range of 0 < 1024,
are equivalent to the standard definitions of control in the MIDI specification (up to the ID
of). Parameters in group scope above 1024 are audio unit defined.
Notes can be created/started with one of two methods. To stop a note it must be stopped with the
same API group as was used to start it (MIDI or the extended Start/Stop note API.
(1) the MIDI Note on event (MusicDeviceMIDIEvent)
- notes must be stopped with the MIDI note off event (MusicDeviceMIDIEvent)
The MIDI Note number is used to turn the note off for the specified channel
(2) the extended Note API (MusicDeviceStartNote). This API returns a note instance ID.
This is unique and can be used with the kAudioUnitScope_Note.
It is also used to turn the note off with MusicDeviceStopNote
*/
#ifndef AudioUnit_MusicDevice_h
#define AudioUnit_MusicDevice_h
#include <AudioToolbox/AUComponent.h>
CF_ASSUME_NONNULL_BEGIN
#ifdef __cplusplus
extern "C" {
#endif
//=====================================================================================================================
#pragma mark -
#pragma mark Types
/*!
@typedef MusicDeviceInstrumentID
@abstract type for instrument identifiers
*/
typedef UInt32 MusicDeviceInstrumentID;
/*!
@struct MusicDeviceStdNoteParams
@abstract convenience struct for specifying a note and velocity
@discussion This struct is the common usage for MusicDeviceStartNote, as most synths that implement this functionality
will only allow for the specification of a note number and velocity when starting a new note.
@var argCount
Should be set to 2
@var mPitch
The pitch of the new note, typically specified using a MIDI note number (and a fractional pitch) within the
range of 0 < 128. So 60 is middle C, 60.5 is middle C + 50 cents.
@var mVelocity
The velocity of the new note - this can be a fractional value - specified as MIDI (within the range of 0 < 128)
*/
struct MusicDeviceStdNoteParams
{
UInt32 argCount; /* should be 2*/
Float32 mPitch;
Float32 mVelocity;
};
typedef struct MusicDeviceStdNoteParams MusicDeviceStdNoteParams;
/*!
@struct NoteParamsControlValue
@abstract used to describe a control and value
@discussion This struct is used to describe a parameterID (a control in MIDI terminology, though it is not limited to
MIDI CC specifications) and the value of this parameter.
@var mID
The parameter ID
@var mValue
The value of that parameter
*/
struct NoteParamsControlValue
{
AudioUnitParameterID mID;
AudioUnitParameterValue mValue;
};
typedef struct NoteParamsControlValue NoteParamsControlValue;
/*!
@struct MusicDeviceNoteParams
@abstract Used to hold the value of the inParams parameter for the MusicDeviceStartNote function.
@discussion The generic version of this structure describes an arg count (which is the number of mControls values
+ 1 for mPitch and 1 for mVelocity). So, argCount should at least be two. See MusicDeviceStdNoteParams
for the common use case, as many audio unit instruments will not respond to control values provided
in the start note function
@var argCount
The number of controls + 2 (for mPitch and mVelocity)
@var mPitch
The pitch of the new note, typically specified using a MIDI note number (and a fractional pitch) within the
range of 0 < 128. So 60 is middle C, 60.5 is middle C + 50 cents.
@var mVelocity
The velocity of the new note - this can be a fractional value - specified as MIDI (within the range of 0 < 128)
@var mControls
A variable length array with the number of elements: argCount - 2.
*/
struct MusicDeviceNoteParams
{
UInt32 argCount;
Float32 mPitch;
Float32 mVelocity;
NoteParamsControlValue mControls[1]; /* arbitrary length */
};
typedef struct MusicDeviceNoteParams MusicDeviceNoteParams;
/*!
enum MusicNoteEvent
@discussion This is used to signify that the patch used to start a note (its sound) is defined by the current
selection for the group ID; this is the normal usage in MIDI as any notes started on a given channel
(group ID) use the sound (patch) defined for that channel. See MusicDeviceStartNote
@constant kMusicNoteEvent_UseGroupInstrument
Use the patch (instrument number) assigned to the new notes group ID
@constant kMusicNoteEvent_Unused
The instrument ID is not specified
*/
enum {
kMusicNoteEvent_UseGroupInstrument = 0xFFFFFFFF,
kMusicNoteEvent_Unused = 0xFFFFFFFF
};
/*!
@typedef MusicDeviceGroupID
@discussion The type used to specify which group (channel number in MIDI) is used with a given command (new note,
control or parameter value change)
*/
typedef UInt32 MusicDeviceGroupID;
/*!
@typedef NoteInstanceID
@discussion The type used to hold an unique identifier returned by MusicDeviceStartNote that is used to then address
that note (typically to turn the note off). An ID must be used for notes, because notes can be specified
by fractional pitches, and so using the MIDI note number is not sufficient to identify the note to turn
it off (or to apply polyphonic after touch).
*/
typedef UInt32 NoteInstanceID;
/*!
@typedef MusicDeviceComponent
@discussion The unique type of a MusicDevice audio unit (which is an AudioComponentInstance)
*/
typedef AudioComponentInstance MusicDeviceComponent;
/*!
@struct MIDIEventList
@abstract Forward declaration of MIDIEventList found in <CoreMIDI/MIDIServices.h>
*/
typedef struct MIDIEventList MIDIEventList;
//=====================================================================================================================
#pragma mark -
#pragma mark Functions
/*!
@function MusicDeviceMIDIEvent
@abstract Used to sent MIDI channel messages to an audio unit
@discussion This is the API used to send MIDI channel messages to an audio unit. The status and data parameters
are used exactly as described by the MIDI specification, including the combination of channel and
command in the status byte. All events sent via MusicDeviceMIDIEventList will be delivered to the
audio unit in the MIDI protocol returned by kAudioUnitProperty_AudioUnitMIDIProtocol.
@param inUnit
The audio unit
@param inStatus
The MIDI status byte
@param inData1
The first MIDI data byte (value is in the range 0 < 128)
@param inData2
The second MIDI data byte (value is in the range 0 < 128). If the MIDI status byte only has one
data byte, this should be set to zero.
@param inOffsetSampleFrame
If you are scheduling the MIDI Event from the audio unit's render thread, then you can supply a
sample offset that the audio unit may apply when applying that event in its next audio unit render.
This allows you to schedule to the sample, the time when a MIDI command is applied and is particularly
important when starting new notes. If you are not scheduling in the audio unit's render thread,
then you should set this value to 0
@result noErr, or an audio unit error code
*/
extern OSStatus
MusicDeviceMIDIEvent( MusicDeviceComponent inUnit,
UInt32 inStatus,
UInt32 inData1,
UInt32 inData2,
UInt32 inOffsetSampleFrame) API_AVAILABLE(macos(10.0), ios(5.0), watchos(2.0), tvos(9.0));
/*!
@function MusicDeviceSysEx
@abstract used to send any non-channel MIDI event to an audio unit
@discussion This is used to send any non-channel MIDI event to an audio unit. In practise this is a System Exclusive
(SysEx) MIDI message
@param inUnit
The audio unit
@param inData
The complete MIDI SysEx message including the F0 and F7 start and termination bytes
@param inLength
The size, in bytes, of the data
@result noErr, or an audio unit error code
*/
extern OSStatus
MusicDeviceSysEx( MusicDeviceComponent inUnit,
const UInt8 * inData,
UInt32 inLength) API_AVAILABLE(macos(10.0), ios(5.0), watchos(2.0), tvos(9.0));
/*!
@function MusicDeviceMIDIEventList
@abstract Used to send MIDI messages to an audio unit
@discussion This API is suitable for sending Universal MIDI Packet (UMP) MIDI messages to an audio unit. The message must be
a full non-SysEx event, a partial SysEx event, or a complete SysEx event. Running status is not allowed. MIDI 1.0 in
universal packets (MIDI-1UP) and MIDI 2.0 messages are allowed. All events sent via MusicDeviceMIDIEventList will
be delivered to the audio unit in the MIDI protocol returned by kAudioUnitProperty_AudioUnitMIDIProtocol.
This is bridged to the v2 API property kAudioUnitProperty_MIDIOutputCallback.
@param inUnit
The audio unit
@param inOffsetSampleFrame
If you are scheduling the MIDIEventList from the audio unit's render thread, then you can supply a
sample offset that the audio unit may apply within its next audio unit render.
This allows you to schedule to the sample, the time when a MIDI command is applied and is particularly
important when starting new notes. If you are not scheduling in the audio unit's render thread,
then you should set this value to 0
inOffsetSampleFrame should serve as the base offset for each packet's timestamp i.e.
sampleOffset = inOffsetSampleFrame + evtList.packet[0].timeStamp
@param evtList
The MIDIEventList to be sent
@result noErr, or an audio unit error code
*/
extern OSStatus
MusicDeviceMIDIEventList( MusicDeviceComponent inUnit,
UInt32 inOffsetSampleFrame,
const struct MIDIEventList * evtList) API_AVAILABLE(macos(12), ios(15.0), tvos(15.0));
/*!
@function MusicDeviceStartNote
@abstract used to start a note
@discussion This function is used to start a note. The caller must provide a NoteInstanceID to receive a
token that is then used to stop the note. The MusicDeviceStopNote call should be used to stop
notes started with this API. The token can also be used to address individual notes on the
kAudioUnitScope_Note if the audio unit supports it. The instrumentID is no longer used and the
kMusicNoteEvent_Unused constant should be specified (this takes the current patch for the
specifed group as the sound to use for the note).
The Audio unit must provide an unique ID for the note instance ID. This ID must be non-zero and not
0xFFFFFFFF (any other UInt32 value is valid).
Not all Music Device audio units implement the semantics of this API (though it is strongly recommended
that they do). A host application shoudl query the kMusicDeviceProperty_SupportsStartStopNote to
check that this is supported.
@param inUnit
The audio unit
@param inInstrument
The instrumentID is no longer used and the kMusicNoteEvent_Unused constant should be specified (this takes
the current patch for the specifed group as the sound to use for the note)
@param inGroupID
The group ID that this note will be attached too. As with MIDI, all notes sounding on a groupID can be
controlled through the various parameters (such as pitch bend, etc) that can be specified on the Group
Scope
@param outNoteInstanceID
A pointer to receive the token that is used to identify the note. This parameter must be specified
@param inOffsetSampleFrame
If you are scheduling the MIDI Event from the audio unit's render thread, then you can supply a sample offset
that the audio unit may apply when starting the note in its next audio unit render. This allows you to
schedule to the sample and is particularly important when starting new notes. If you are not scheduling
in the audio unit's render thread, then you should set this value to 0
@param inParams
The parameters to be used when starting the note - pitch and velocity must be specified
@result noErr, or an audio unit error code
*/
extern OSStatus
MusicDeviceStartNote( MusicDeviceComponent inUnit,
MusicDeviceInstrumentID inInstrument,
MusicDeviceGroupID inGroupID,
NoteInstanceID * outNoteInstanceID,
UInt32 inOffsetSampleFrame,
const MusicDeviceNoteParams * inParams) API_AVAILABLE(macos(10.0), ios(5.0), watchos(2.0), tvos(9.0));
/*!
@function MusicDeviceStopNote
@abstract used to stop notes started with the MusicDeviceStartNote call
@discussion This call is used to stop notes that have been started with the MusicDeviceStartNote call; both the group ID
that the note was started on and the noteInstanceID should be specified.
@param inUnit
The audio unit
@param inGroupID
the group ID
@param inNoteInstanceID
the note instance ID
@param inOffsetSampleFrame
the sample offset within the next buffer rendered that the note should be turned off at
@result noErr, or an audio unit error code
*/
extern OSStatus
MusicDeviceStopNote( MusicDeviceComponent inUnit,
MusicDeviceGroupID inGroupID,
NoteInstanceID inNoteInstanceID,
UInt32 inOffsetSampleFrame) API_AVAILABLE(macos(10.0), ios(5.0), watchos(2.0), tvos(9.0));
/*!
@enum Music Device range
@constant kMusicDeviceRange
delineates the start of the selector ranges for music devices
@constant kMusicDeviceMIDIEventSelect
@constant kMusicDeviceSysExSelect
@constant kMusicDevicePrepareInstrumentSelect
@constant kMusicDeviceReleaseInstrumentSelect
@constant kMusicDeviceStartNoteSelect
@constant kMusicDeviceStopNoteSelect
@constant kMusicDeviceMIDIEventListSelect
*/
enum {
kMusicDeviceRange = 0x0100,
kMusicDeviceMIDIEventSelect = 0x0101,
kMusicDeviceSysExSelect = 0x0102,
kMusicDevicePrepareInstrumentSelect = 0x0103,
kMusicDeviceReleaseInstrumentSelect = 0x0104,
kMusicDeviceStartNoteSelect = 0x0105,
kMusicDeviceStopNoteSelect = 0x0106,
kMusicDeviceMIDIEventListSelect = 0x0107
};
//=====================================================================================================================
#pragma mark -
#pragma mark Fast-dispatch function prototypes
/*!
@typedef MusicDeviceMIDIEventProc
@discussion This proc can be exported through the FastDispatch property or is used as the prototype for
an audio component dispatch for this selector.
The arguments are the same as are provided to the corresponding API call
@param self
For a component manager component, this is the component instance storage pointer
@result noErr, or an audio unit error code
*/
typedef OSStatus
(*MusicDeviceMIDIEventProc)( void * self,
UInt32 inStatus,
UInt32 inData1,
UInt32 inData2,
UInt32 inOffsetSampleFrame);
/*!
@typedef MusicDeviceSysExProc
@discussion This proc can be exported through the FastDispatch property or is used as the prototype for
an audio component dispatch for this selector.
The arguments are the same as are provided to the corresponding API call
@param self
For a component manager component, this is the component instance storage pointer
@result noErr, or an audio unit error code
*/
typedef OSStatus
(*MusicDeviceSysExProc)( void * self,
const UInt8 * inData,
UInt32 inLength);
/*!
@typedef MusicDeviceStartNoteProc
@discussion This proc can be exported through the FastDispatch property or is used as the prototype for
an audio component dispatch for this selector.
The arguments are the same as are provided to the corresponding API call
@param self
For a component manager component, this is the component instance storage pointer
@result noErr, or an audio unit error code
*/
typedef OSStatus
(*MusicDeviceStartNoteProc)( void * self,
MusicDeviceInstrumentID inInstrument,
MusicDeviceGroupID inGroupID,
NoteInstanceID * outNoteInstanceID,
UInt32 inOffsetSampleFrame,
const MusicDeviceNoteParams * inParams);
/*!
@typedef MusicDeviceStopNoteProc
@discussion This proc can be exported through the FastDispatch property or is used as the prototype for
an audio component dispatch for this selector.
The arguments are the same as are provided to the corresponding API call
@param self
For a component manager component, this is the component instance storage pointer
@result noErr, or an audio unit error code
*/
typedef OSStatus
(*MusicDeviceStopNoteProc)( void * self,
MusicDeviceGroupID inGroupID,
NoteInstanceID inNoteInstanceID,
UInt32 inOffsetSampleFrame);
//=====================================================================================================================
#pragma mark -
#pragma mark Deprecated
/*
The notion of instruments (separate voices assigned to different control groups) is a deprecated concept.
Going forward, multitimbral synths are implemented using Part Scopes.
Thus, the Prepare and Release Instrument API calls are deprecated (see also MusicDeviceStartNote)
*/
extern OSStatus
MusicDevicePrepareInstrument( MusicDeviceComponent inUnit,
MusicDeviceInstrumentID inInstrument)
API_DEPRECATED("no longer supported", macos(10.0, 10.5)) API_UNAVAILABLE(ios, watchos, tvos);
extern OSStatus
MusicDeviceReleaseInstrument( MusicDeviceComponent inUnit,
MusicDeviceInstrumentID inInstrument)
API_DEPRECATED("no longer supported", macos(10.0, 10.5)) API_UNAVAILABLE(ios, watchos, tvos);
#ifdef __cplusplus
}
#endif
CF_ASSUME_NONNULL_END
#endif /* AudioUnit_MusicDevice_h */
#else
#include <AudioToolboxCore/MusicDevice.h>
#endif

View File

@@ -0,0 +1,11 @@
framework module AudioToolbox [extern_c] [system] {
umbrella header "AudioToolbox.h"
export *
module * { export * }
explicit module DefaultAudioOutput { header "DefaultAudioOutput.h" export * }
explicit module AUCocoaUIView { header "AUCocoaUIView.h" export * }
explicit module AudioUnitCarbonView { header "AudioUnitCarbonView.h" export * }
}