AVAssetWriterInput Class Reference

Inherits from
Conforms to
Framework
/System/Library/Frameworks/AVFoundation.framework
Availability
Available in iOS 4.1 and later.
Companion guide
Declared in
AVAssetWriterInput.h
Related sample code

Overview

You use an AVAssetWriterInput to append media samples packaged as CMSampleBuffer objects (see CMSampleBufferRef), or collections of metadata, to a single track of the output file of an AVAssetWriter object.

When there are multiple inputs, AVAssetWriter tries to write media data in an ideal interleaving pattern for efficiency in storage and playback. Each of its inputs signals its readiness to receive media data for writing according to that pattern via the value of readyForMoreMediaData. If readyForMoreMediaData is YES, an input can accept additional media data while maintaining appropriate interleaving. You can only append media data to an input while its readyForMoreMediaData property is YES.

The value of readyForMoreMediaData will often change from NO to YES asynchronously, as previously-supplied media data is processed and written to the output. It is possible for all of an asset writer’s inputs temporarily to return NO for readyForMoreMediaData.

Tasks

Creating an Asset Writer Input Instance

Adding Samples

Configuring a Writer Input

Managing Track Associations

Inspecting a Writer Input

Managing Language Settings

Properties

expectsMediaDataInRealTime

Indicates whether the input should tailor its processing of media data for real-time sources.

@property(nonatomic) BOOL expectsMediaDataInRealTime
Discussion

If you are appending media data to an input from a real-time source, such as an AVCaptureOutput, you should set expectsMediaDataInRealTime to YES. This will ensure that readyForMoreMediaData is calculated appropriately for real-time usage.

You cannot set this property after writing has started.

Availability
  • Available in iOS 4.1 and later.
Related Sample Code
Declared In
AVAssetWriterInput.h

extendedLanguageTag

Language tag to associate with the track corresponding to the receiver

@property(nonatomic, copy) NSString *extendedLanguageTag
Discussion

The value is specified as an RFC 4646 language tag; can be nil in which case no tag is written to the track.

Extended language tags are normally set only when an ISO 639-2/T language code by itself is ambiguous, as in cases in which media data should be distinguished not only by language but also by the regional dialect in use or the writing system employed.

Availability
  • Available in iOS 7.0 and later.
Declared In
AVAssetWriterInput.h

languageCode

Language to associate with the track corresponding to the receiver.

@property(nonatomic, copy) NSString *languageCode
Discussion

The value is specified as an ISO 639-2/T language code; can be nil in which case no language code is written to the track..

Availability
  • Available in iOS 7.0 and later.
Declared In
AVAssetWriterInput.h

marksOutputTrackAsEnabled

Returns whether the receiver’s track is enabled.

@property(nonatomic) BOOL marksOutputTrackAsEnabled
Discussion

For file types that support enabled and disabled tracks, such as QuickTime Movie files, specifies whether the track corresponding to the receiver should be enabled by default for playback and processing.

The default value is YES.

Availability
  • Available in iOS 7.0 and later.
Declared In
AVAssetWriterInput.h

mediaTimeScale

Specifies the media time scale to be used

@property(nonatomic) CMTimeScale mediaTimeScale
Discussion

For file types that support media time scales, such as QuickTime Movie files, specifies the media time scale to be used. The default value of this property is 0, which indicates that the writer input object should choose an appropriate value.

It is an error to assign a value other than 0 to this property if the object’s mediaType property is set to to AVMediaTypeAudio.

You cannot set this property after writing has started.

In order to avoid inconsistencies between the track's media time scale and the result's media time scale (see AVAssetWriter property movieTimeScale ) both should be set to equal or compatible values.

Availability
  • Available in iOS 4.3 and later.
Declared In
AVAssetWriterInput.h

mediaType

The media type of the samples that can be appended to the input. (read-only)

@property(nonatomic, readonly) NSString *mediaType
Discussion

The value of this property is one of the media type strings defined in AV Foundation Constants Reference.

Availability
  • Available in iOS 4.1 and later.
Declared In
AVAssetWriterInput.h

metadata

The collection of track-level metadata for association with the asset and for carriage in the output file.

@property(nonatomic, copy) NSArray *metadata
Discussion

The array contains AVMetadataItem objects representing the collection of track-level metadata to be written in the output file.

You cannot set this property after writing has started.

Availability
  • Available in iOS 4.1 and later.
Declared In
AVAssetWriterInput.h

naturalSize

Size specified in the output file as the natural dimensions of the visual media data for display.

@property(nonatomic) CGSize naturalSize
Discussion

If the default value, CGSizeZero, is specified, the naturalSize of the track corresponding to the receiver is set according to dimensions indicated by the format descriptions that are ultimately written to the output track.

Availability
  • Available in iOS 7.0 and later.
Declared In
AVAssetWriterInput.h

outputSettings

The settings used for encoding the media appended to the output. (read-only)

@property(nonatomic, readonly) NSDictionary *outputSettings
Discussion

A value of nil specifies that appended samples should not be re-encoded.

Availability
  • Available in iOS 4.1 and later.
Declared In
AVAssetWriterInput.h

preferredVolume

Preferred volume level to be stored in the output file.

@property(nonatomic) float preferredVolume
Discussion

The value for this property should typically be in the range of 0.0 to 1.0.

The default value is 1.0, which is equivalent to a “normal” volume level.

Availability
  • Available in iOS 7.0 and later.
Declared In
AVAssetWriterInput.h

readyForMoreMediaData

A Boolean value that indicates the readiness of the input to accept more media data. (read-only)

@property(nonatomic, readonly, getter=isReadyForMoreMediaData) BOOL readyForMoreMediaData
Discussion

This property is observable using key-value observing (see Key-Value Observing Programming Guide). Observers should not assume that they will be notified of changes on a specific thread.

Availability
  • Available in iOS 4.1 and later.
Related Sample Code
Declared In
AVAssetWriterInput.h

sourceFormatHint

A hint about the format of buffers that will be appended. (read-only)

@property(nonatomic, readonly) CMFormatDescriptionRef sourceFormatHint
Discussion

An AVAssetWriterInput object may be able to use this hint to fill in missing output settings or perform more upfront validation.

Availability
  • Available in iOS 6.0 and later.
Declared In
AVAssetWriterInput.h

transform

The transform specified in the output file as the preferred transformation of the visual media data for display purposes.

@property(nonatomic) CGAffineTransform transform
Discussion

If no value is specified, the identity transform is used.

Availability
  • Available in iOS 4.1 and later.
Related Sample Code
Declared In
AVAssetWriterInput.h

Class Methods

assetWriterInputWithMediaType:outputSettings:

Returns a new writer input object initialized with the specified media type and output settings.

+ (AVAssetWriterInput *)assetWriterInputWithMediaType:(NSString *)mediaType outputSettings:(NSDictionary *)outputSettings
Parameters
mediaType

The type of samples to be accepted by the input object. For a list of media types, see AV Foundation Constants Reference.

outputSettings

The settings used for encoding the media appended to the output. Pass nil to specify that the appended samples should not be re-encoded.

Audio output settings keys are defined in AV Foundation Audio Settings Constants. Video output settings keys are defined in AV Foundation Constants Reference. Video output settings with keys from <CoreVideo/CVPixelBuffer.h> are not currently supported.

Return Value

A new writer input object that can accept samples of the specified media type and write them to the output file.

Discussion

Each new input accepts data for a new track of the asset writer’s output file. You add an input to an asset writer using the AVAssetWriter method addInput:.

Passing nil for outputSettings instructs the input to pass through appended samples, doing no processing before they are written to the output file. This is useful if, for example, you are appending buffers that are already in a desirable compressed format. However, passthrough is currently supported only when writing to QuickTime Movie files (i.e. the AVAssetWriter was initialized with AVFileTypeQuickTimeMovie). For other file types, you must specify non-nil output settings.

Availability
  • Available in iOS 4.1 and later.
Declared In
AVAssetWriterInput.h

assetWriterInputWithMediaType:outputSettings:sourceFormatHint:

Returns a new writer input object initialized with the specified media type, output settings, and source format hint.

+ (AVAssetWriterInput *)assetWriterInputWithMediaType:(NSString *)mediaType outputSettings:(NSDictionary *)outputSettings sourceFormatHint:(CMFormatDescriptionRef)sourceFormatHint
Parameters
mediaType

The media type of the samples to be accepted by the input object. For a list of media types, see AV Foundation Constants Reference.

outputSettings

Specify a dictionary containing the settings used for encoding the media appended to the output. You may pass nil if you do not want the appended samples to be re-encoded.

Audio output settings keys are defined in AV Foundation Audio Settings Constants. Video output settings keys are defined in AV Foundation Constants Reference. Video output settings with keys from <CoreVideo/CVPixelBuffer.h> are not currently supported.

sourceFormatHint

This parameter contains a hint of the type of the format buffers to be appended. If you specify a value for this parameter, the writer input object may be able to fill in missing output settings or perform more upfront validation. If you specify a value for this property, you should make sure that the buffers you append are of the indicated type.

Return Value

A new writer input object that can accept samples of the specified media type and write them to the output file.

Discussion

Each new input accepts data for a new track of the asset writer’s output file. You add an input to an asset writer using the AVAssetWriter method addInput:.

Passing nil for output settings instructs the input to pass through appended samples, doing no processing before they are written to the output file.  This is useful if, for example, you are appending buffers that are already in a desirable compressed format.  However, if not writing to a QuickTime Movie file (i.e. the AVAssetWriter was initialized with a file type other than AVFileTypeQuickTimeMovie), AVAssetWriter only supports passing through a restricted set of media types and subtypes.  In order to pass through media data to files other than AVFileTypeQuickTimeMovie, a non-NULL format hint must be provided.

Availability
  • Available in iOS 6.0 and later.
Declared In
AVAssetWriterInput.h

Instance Methods

addTrackAssociationWithTrackOfInput:type:

Associates the track corresponding to the specified input with the track corresponding with the receiver.

- (void)addTrackAssociationWithTrackOfInput:(AVAssetWriterInput *)input type:(NSString *)trackAssociationType
Parameters
input

The instance of AVAssetWriterInput with a corresponding track to associate with track corresponding with the receiver.

trackAssociationType

The type of track association to add. Common track association types, such as AVTrackAssociationTypeTimecode are defined in Track Association Types.

Discussion

If the type of association requires tracks of specific media types that don't match the media types of the inputs, or if the output file type does not support track associations, an NSInvalidArgumentException is raised.

Availability
  • Available in iOS 7.0 and later.
Declared In
AVAssetWriterInput.h

appendSampleBuffer:

Appends samples to the receiver.

- (BOOL)appendSampleBuffer:(CMSampleBufferRef)sampleBuffer
Parameters
sampleBuffer

The CMSampleBuffer to be appended.

Return Value

YES if sampleBuffer as appended successfully, otherwise NO.

Discussion

The timing information in the sample buffer, considered relative to the time passed to the asset writer’s startSessionAtSourceTime: will be used to determine the timing of those samples in the output file.

If NO is returned, clients can check the value of the AVAssetWriter status property to determine whether the writing operation completed, failed, or was cancelled.  If the status is AVAssetWriterStatusFailed, The AVAssetWriter error property will contain an instance of NSErrorß that describes the failure.

Do not modify sampleBuffer or its contents after you have passed it to this method.

Availability
  • Available in iOS 4.1 and later.
Declared In
AVAssetWriterInput.h

canAddTrackAssociationWithTrackOfInput:type:

Whether an association between the tracks corresponding to a pair of inputs is valid.

- (BOOL)canAddTrackAssociationWithTrackOfInput:(AVAssetWriterInput *)input type:(NSString *)trackAssociationType
Parameters
input

The instance of AVAssetWriterInput with a corresponding track to associate with track corresponding with the receiver.

trackAssociationType

The type of track association to test. Common track association types, such as AVTrackAssociationTypeTimecode are defined in Track Association Types.

Return Value

YES if the track association can be added; otherwise NO.

Discussion

If the type of association requires tracks of specific media types that don't match the media types of the inputs, or if the output file type does not support track associations, returns NO.

Availability
  • Available in iOS 7.0 and later.
Declared In
AVAssetWriterInput.h

initWithMediaType:outputSettings:

Initialize a writer input object with the specified media type and output settings.

- (id)initWithMediaType:(NSString *)mediaType outputSettings:(NSDictionary *)outputSettings
Parameters
mediaType

The media type of the samples to be accepted by the input object. For a list of media types, see AV Foundation Constants Reference.

outputSettings

Specify a dictionary containing the settings used for encoding the media appended to the output. You may pass nil for this parameter if you do not want the appended samples to be re-encoded.

Audio output settings keys are defined in AV Foundation Audio Settings Constants. Video output settings keys are defined in AV Foundation Constants Reference. Video output settings with keys from CVPixelBufferRef are not currently supported.

Return Value

An initialized writer input object that can accept samples of the specified media type and write them to the output file.

Discussion

Each new input accepts data for a new track of the asset writer’s output file. You add an input to an asset writer using the AVAssetWriter method addInput:.

Passing nil for output settings instructs the input to pass through appended samples, doing no processing before they are written to the output file.  This is useful if, for example, you are appending buffers that are already in a desirable compressed format.  However, if not writing to a QuickTime Movie file (i.e. the AVAssetWriter was initialized with a file type other than AVFileTypeQuickTimeMovie), AVAssetWriter only supports passing through a restricted set of media types and subtypes.  In order to pass through media data to files other than AVFileTypeQuickTimeMovie, a non-NULL format hint must be provided using initWithMediaType:outputSettings:sourceFormatHint: instead of this method.

When the mediaType parameter is AVMediaTypeAudio, the outputSettings dictionary does not support the AVEncoderAudioQualityKey and AVSampleRateConverterAudioQualityKey keys. When using this method, an audio settings dictionary must be fully specified, meaning that it must contain the AVFormatIDKey, AVSampleRateKey, and AVNumberOfChannelsKey keys. If no other channel layout information is available, a value of 1 for the AVNumberOfChannelsKey key results in mono output and a value of 2 results in stereo output. If the AVNumberOfChannelsKey key specifies a value greater than 2, the dictionary must also specify a value for the AVChannelLayoutKey key. For audio using the kAudioFormatLinearPCM format, include all relevant AVLinearPCM*Key keys. For the kAudioFormatAppleLossless format, include the AVEncoderBitDepthHintKey keys. To avoid specifying values for each of those keys, use the initWithMediaType:outputSettings:sourceFormatHint: method instead.

When the mediaType parameter is AVMediaTypeVideo, the outputSettings dictionary must request a compressed video format. This means that the values specified in the dictionary must follow the rules for compressed video output, as described in AVVideoSettings.h. When using this initializer, a video settings dictionary must be fully specified, meaning that it must contain the following keys: AVVideoCodecKey, AVVideoWidthKey, and AVVideoHeightKey. To avoid specifying values for each of those keys, use the initWithMediaType:outputSettings:sourceFormatHint: method.

Availability
  • Available in iOS 4.1 and later.
Related Sample Code
Declared In
AVAssetWriterInput.h

initWithMediaType:outputSettings:sourceFormatHint:

Initialize a writer input object with the specified media type, output settings, and source hint.

- (id)initWithMediaType:(NSString *)mediaType outputSettings:(NSDictionary *)outputSettings sourceFormatHint:(CMFormatDescriptionRef)sourceFormatHint
Parameters
mediaType

The media type of the samples to be accepted by the input object. For a list of media types, see AV Foundation Constants Reference.

outputSettings

Specify a dictionary containing the settings used for encoding the media appended to the output. You may pass nil for this parameter if you do not want the appended samples to be re-encoded.

Audio output settings keys are defined in AV Foundation Audio Settings Constants. Video output settings keys are defined in AV Foundation Constants Reference. Video output settings with keys from <CoreVideo/CVPixelBuffer.h> are not currently supported.

sourceFormatHint

This parameter contains a hint of the type of the format buffers to be appended. If you specify a value for this parameter, the writer input object may be able to fill in missing output settings or perform more upfront validation. If you specify a value for this property, you should make sure that the buffers you append are of the indicated type.

Return Value

An initialized writer input object that can accept samples of the specified media type and write them to the output file.

Discussion

Each new input accepts data for a new track of the asset writer’s output file. You add an input to an asset writer using the AVAssetWriter method addInput:.

Passing nil for output settings instructs the input to pass through appended samples, doing no processing before they are written to the output file.  This is useful if, for example, you are appending buffers that are already in a desirable compressed format.  However, if not writing to a QuickTime Movie file (i.e. the AVAssetWriter was initialized with a file type other than AVFileTypeQuickTimeMovie), AVAssetWriter only supports passing through a restricted set of media types and subtypes.  In order to pass through media data to files other than AVFileTypeQuickTimeMovie, a non-NULL format hint must be provided using initWithMediaType:outputSettings:sourceFormatHint: instead of this method.

Availability
  • Available in iOS 6.0 and later.
Declared In
AVAssetWriterInput.h

markAsFinished

Tells the writer that no more buffers will be appended to this input.

- (void)markAsFinished
Discussion

If you are monitoring each input's expectsMediaDataInRealTime value to keep the output file well interleaved, it is important to call this method when you have finished adding buffers to a track. This is necessary to prevent other inputs from stalling, as they may otherwise wait forever for that input's media data, attempting to complete the ideal interleaving pattern.

Availability
  • Available in iOS 4.1 and later.
Related Sample Code
Declared In
AVAssetWriterInput.h

requestMediaDataWhenReadyOnQueue:usingBlock:

Instructs the receiver to invoke a block repeatedly, at its convenience, in order to gather media data for writing to the output.

- (void)requestMediaDataWhenReadyOnQueue:(dispatch_queue_t)queue usingBlock:(void (^)(void))block
Parameters
queue

The queue on which block should be invoked.

block

The block the input should invoke to obtain media data.

Discussion

The block should append media data to the input either until the input’s readyForMoreMediaData property becomes NO or until there is no more media data to supply (at which point it may choose to mark the input as finished using markAsFinished). The block should then exit. After the block exits, if the input has not been marked as finished, once the input has processed the media data it has received and becomes ready for more media data again, it will invoke the block again in order to obtain more.

A typical use of this method, with a block that supplies media data to an input while respecting the input’s readyForMoreMediaData property, might look like this:

[myAVAssetWriterInput requestMediaDataWhenReadyOnQueue:myInputSerialQueue usingBlock:^{
        while ([myAVAssetWriterInput isReadyForMoreMediaData])
        {
            CMSampleBufferRef nextSampleBuffer = [self copyNextSampleBufferToWrite];
            if (nextSampleBuffer)
            {
                [myAVAssetWriterInput appendSampleBuffer:nextSampleBuffer];
                CFRelease(nextSampleBuffer);
            }
            else
            {
                [myAVAssetWriterInput markAsFinished];
                break;
            }
        }
    }];

You should not use this method with a push-style buffer source, such as AVCaptureAudioDataOutput or AVCaptureVideoDataOutput, because such a combination will typically require intermediate queueing of buffers. Instead, this method is better suited to a pull-style buffer source such as an AVAssetReaderOutput object.

When using a push-style buffer source, it is generally better to immediately append each buffer to the asset writer input, directly as it is received using appendSampleBuffer:. Using this strategy, it is often possible to avoid having to queue up buffers in between the buffer source and the asset writer input. Note that many of these push-style buffer sources also produce buffers in real-time, in which case you should set expectsMediaDataInRealTime to YES.

Availability
  • Available in iOS 4.1 and later.
Declared In
AVAssetWriterInput.h