+static int get_audio_config(AVFormatContext *s)
+{
+ AVFContext *ctx = (AVFContext*)s->priv_data;
+
+ // Take stream info from the first frame.
+ while (ctx->audio_frames_captured < 1) {
+ CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.1, YES);
+ }
+
+ lock_frames(ctx);
+
+ AVStream* stream = avformat_new_stream(s, NULL);
+
+ if (!stream) {
+ return 1;
+ }
+
+ ctx->audio_stream_index = stream->index;
+
+ avpriv_set_pts_info(stream, 64, 1, avf_time_base);
+
+ CMFormatDescriptionRef format_desc = CMSampleBufferGetFormatDescription(ctx->current_audio_frame);
+ const AudioStreamBasicDescription *basic_desc = CMAudioFormatDescriptionGetStreamBasicDescription(format_desc);
+
+ if (!basic_desc) {
+ av_log(s, AV_LOG_ERROR, "audio format not available\n");
+ return 1;
+ }
+
+ stream->codec->codec_type = AVMEDIA_TYPE_AUDIO;
+ stream->codec->sample_rate = basic_desc->mSampleRate;
+ stream->codec->channels = basic_desc->mChannelsPerFrame;
+ stream->codec->channel_layout = av_get_default_channel_layout(stream->codec->channels);
+
+ ctx->audio_channels = basic_desc->mChannelsPerFrame;
+ ctx->audio_bits_per_sample = basic_desc->mBitsPerChannel;
+ ctx->audio_float = basic_desc->mFormatFlags & kAudioFormatFlagIsFloat;
+ ctx->audio_be = basic_desc->mFormatFlags & kAudioFormatFlagIsBigEndian;
+ ctx->audio_signed_integer = basic_desc->mFormatFlags & kAudioFormatFlagIsSignedInteger;
+ ctx->audio_packed = basic_desc->mFormatFlags & kAudioFormatFlagIsPacked;
+ ctx->audio_non_interleaved = basic_desc->mFormatFlags & kAudioFormatFlagIsNonInterleaved;
+
+ if (basic_desc->mFormatID == kAudioFormatLinearPCM &&
+ ctx->audio_float &&
+ ctx->audio_packed) {
+ stream->codec->codec_id = ctx->audio_be ? AV_CODEC_ID_PCM_F32BE : AV_CODEC_ID_PCM_F32LE;
+ } else {
+ av_log(s, AV_LOG_ERROR, "audio format is not supported\n");
+ return 1;
+ }
+
+ if (ctx->audio_non_interleaved) {
+ CMBlockBufferRef block_buffer = CMSampleBufferGetDataBuffer(ctx->current_audio_frame);
+ ctx->audio_buffer_size = CMBlockBufferGetDataLength(block_buffer);
+ ctx->audio_buffer = av_malloc(ctx->audio_buffer_size);
+ if (!ctx->audio_buffer) {
+ av_log(s, AV_LOG_ERROR, "error allocating audio buffer\n");
+ return 1;
+ }
+ }
+
+ CFRelease(ctx->current_audio_frame);
+ ctx->current_audio_frame = nil;
+
+ unlock_frames(ctx);
+
+ return 0;
+}
+