364 lines
11 KiB
Objective-C
364 lines
11 KiB
Objective-C
//
|
|
// MP42AudioDecoder.m
|
|
// MP42Foundation
|
|
//
|
|
// Created by Damiano Galassi on 23/07/2016.
|
|
// Copyright © 2016 Damiano Galassi. All rights reserved.
|
|
//
|
|
|
|
#import "MP42AudioDecoder.h"
|
|
|
|
#import "MP42AudioTrack.h"
|
|
#import "MP42Sample.h"
|
|
#import "MP42Fifo.h"
|
|
|
|
#include "FFmpegUtils.h"
|
|
|
|
#include <avcodec.h>
|
|
#include <libavresample/avresample.h>
|
|
#include <libavutil/channel_layout.h>
|
|
#include <libavutil/opt.h>
|
|
|
|
struct MP42DecodeContext {
|
|
AVCodecContext *avctx;
|
|
AVAudioResampleContext *resampler;
|
|
|
|
AudioStreamBasicDescription inputFormat;
|
|
AudioStreamBasicDescription outputFormat;
|
|
|
|
enum AVMatrixEncoding matrix_encoding;
|
|
enum AVSampleFormat out_sample_format;
|
|
};
|
|
|
|
typedef struct MP42DecodeContext MP42DecodeContext;
|
|
|
|
@interface MP42AudioDecoder ()
|
|
{
|
|
__unsafe_unretained id<MP42AudioUnit> _outputUnit;
|
|
MP42AudioUnitOutput outputType;
|
|
}
|
|
|
|
@property (nonatomic, readonly) AVCodec *codec;
|
|
@property (nonatomic, readonly) AVCodecContext *avctx;
|
|
|
|
@property (nonatomic, readonly) NSThread *decoderThread;
|
|
@property (nonatomic, readonly) MP42Fifo<MP42SampleBuffer *> *inputSamplesBuffer;
|
|
@property (nonatomic, readonly) MP42Fifo<MP42SampleBuffer *> *outputSamplesBuffer;
|
|
|
|
@property (nonatomic, readonly) MP42DecodeContext *context;
|
|
|
|
@end
|
|
|
|
@implementation MP42AudioDecoder
|
|
|
|
@synthesize outputUnit = _outputUnit;
|
|
@synthesize outputType = _outputType;
|
|
|
|
- (instancetype)initWithAudioFormat:(AudioStreamBasicDescription)asbd mixdownType:(NSString *)mixdownType magicCookie:(NSData *)magicCookie error:(NSError **)error;
|
|
{
|
|
self = [super init];
|
|
|
|
if (self) {
|
|
FFInitFFmpeg();
|
|
|
|
_inputFormat = asbd;
|
|
|
|
enum AVCodecID codecID = FourCCToCodecID(asbd.mFormatID);
|
|
_codec = avcodec_find_decoder(codecID);
|
|
|
|
if (!_codec) {
|
|
return nil;
|
|
}
|
|
|
|
_avctx = avcodec_alloc_context3(_codec);
|
|
|
|
if (!_avctx) {
|
|
return nil;
|
|
}
|
|
|
|
if (_avctx && magicCookie) {
|
|
|
|
_avctx->extradata = (uint8_t*)av_malloc(magicCookie.length + AV_INPUT_BUFFER_PADDING_SIZE);
|
|
if (!_avctx->extradata) {
|
|
NSLog(@"Could not av_malloc extradata");
|
|
av_freep(&_avctx);
|
|
return nil;
|
|
}
|
|
else {
|
|
_avctx->extradata_size = magicCookie.length;
|
|
memcpy(_avctx->extradata, magicCookie.bytes, magicCookie.length);
|
|
}
|
|
}
|
|
|
|
if (avcodec_open2(_avctx, _codec, NULL)) {
|
|
NSLog(@"Error opening audio decoder");
|
|
av_freep(&_avctx);
|
|
return nil;
|
|
}
|
|
|
|
// Check the out channel count for the current downmix
|
|
UInt32 channels = _inputFormat.mChannelsPerFrame;
|
|
enum AVMatrixEncoding matrix_encoding = AV_MATRIX_ENCODING_NONE;
|
|
if ([mixdownType isEqualToString:SBMonoMixdown]) {
|
|
channels = 1;
|
|
}
|
|
else if ([mixdownType isEqualToString:SBStereoMixdown]) {
|
|
channels = 2;
|
|
}
|
|
else if ([mixdownType isEqualToString:SBDolbyMixdown]) {
|
|
matrix_encoding = AV_MATRIX_ENCODING_DOLBY;
|
|
channels = 2;
|
|
}
|
|
else if ([mixdownType isEqualToString:SBDolbyPlIIMixdown]) {
|
|
matrix_encoding = AV_MATRIX_ENCODING_DPLII;
|
|
channels = 2;
|
|
}
|
|
|
|
// Creates the output audio stream basic description.
|
|
// It will be used to configure the next audio unit in the chain.
|
|
AudioStreamBasicDescription outputFormat;
|
|
bzero(&outputFormat, sizeof(AudioStreamBasicDescription));
|
|
outputFormat.mSampleRate = _inputFormat.mSampleRate;
|
|
outputFormat.mFormatID = kAudioFormatLinearPCM ;
|
|
outputFormat.mFormatFlags = kLinearPCMFormatFlagIsFloat | kAudioFormatFlagsNativeEndian;
|
|
outputFormat.mBytesPerPacket = 4 * channels;
|
|
outputFormat.mFramesPerPacket = 1;
|
|
outputFormat.mBytesPerFrame = outputFormat.mBytesPerPacket * outputFormat.mFramesPerPacket;
|
|
outputFormat.mChannelsPerFrame = channels;
|
|
outputFormat.mBitsPerChannel = 32;
|
|
|
|
_outputFormat = outputFormat;
|
|
|
|
// Context used by the decoder
|
|
_context = malloc(sizeof(MP42DecodeContext));
|
|
_context->avctx = _avctx;
|
|
_context->resampler = NULL;
|
|
_context->inputFormat = _inputFormat;
|
|
_context->outputFormat = _outputFormat;
|
|
_context->matrix_encoding = matrix_encoding;
|
|
_context->out_sample_format = AV_SAMPLE_FMT_FLT;
|
|
|
|
// Init the FIFOs
|
|
_inputSamplesBuffer = [[MP42Fifo alloc] initWithCapacity:100];
|
|
_outputSamplesBuffer = [[MP42Fifo alloc] initWithCapacity:100];
|
|
|
|
[self start];
|
|
}
|
|
|
|
return self;
|
|
}
|
|
|
|
- (void)dealloc
|
|
{
|
|
if (_avctx) {
|
|
avcodec_close(_avctx);
|
|
av_freep(&_avctx);
|
|
}
|
|
|
|
if (_context) {
|
|
if (_context->resampler) {
|
|
avresample_close(_context->resampler);
|
|
avresample_free(&_context->resampler);
|
|
}
|
|
}
|
|
}
|
|
|
|
- (void)start
|
|
{
|
|
_decoderThread = [[NSThread alloc] initWithTarget:self selector:@selector(threadMainRoutine) object:nil];
|
|
[_decoderThread setName:@"FFmpeg Audio Decoder"];
|
|
[_decoderThread start];
|
|
}
|
|
|
|
#pragma mark - Public methods
|
|
|
|
- (void)addSample:(MP42SampleBuffer *)sample
|
|
{
|
|
[_inputSamplesBuffer enqueue:sample];
|
|
}
|
|
|
|
- (nullable MP42SampleBuffer *)copyEncodedSample
|
|
{
|
|
return [_outputSamplesBuffer dequeue];
|
|
}
|
|
|
|
#pragma mark - Decode
|
|
|
|
static AVPacket * packetFromSampleBuffer(MP42SampleBuffer *sample)
|
|
{
|
|
AVPacket *pkt = av_packet_alloc();
|
|
pkt->data = sample->data;
|
|
pkt->size = sample->size;
|
|
pkt->pts = sample->timestamp;
|
|
pkt->dts = AV_NOPTS_VALUE;
|
|
|
|
return pkt;
|
|
}
|
|
|
|
static MP42SampleBuffer * sampleBufferFromFrame(uint8_t *output_data, int output_data_size)
|
|
{
|
|
MP42SampleBuffer *sample = [[MP42SampleBuffer alloc] init];
|
|
|
|
sample->data = output_data;
|
|
sample->size = output_data_size;
|
|
|
|
return sample;
|
|
}
|
|
|
|
static int initResampler(MP42DecodeContext *context, AVFrame *frame)
|
|
{
|
|
int ret = 0;
|
|
AVAudioResampleContext *resampler;
|
|
|
|
// We want float interleaved, FFmpeg usually prefers
|
|
// float planar, so we need to convert it.
|
|
|
|
if (context->avctx->sample_fmt != context->out_sample_format ||
|
|
context->outputFormat.mChannelsPerFrame != context->inputFormat.mChannelsPerFrame) {
|
|
|
|
resampler = avresample_alloc_context();
|
|
if (!resampler) {
|
|
return 1;
|
|
}
|
|
|
|
av_opt_set_int(resampler, "in_channel_layout", frame->channel_layout, 0);
|
|
if (context->outputFormat.mChannelsPerFrame < context->inputFormat.mChannelsPerFrame) {
|
|
if (context->outputFormat.mChannelsPerFrame == 2) {
|
|
av_opt_set_int(resampler, "out_channel_layout", AV_CH_LAYOUT_STEREO, 0);
|
|
}
|
|
else if (context->outputFormat.mChannelsPerFrame == 1) {
|
|
av_opt_set_int(resampler, "out_channel_layout", AV_CH_LAYOUT_MONO, 0);
|
|
}
|
|
}
|
|
else {
|
|
av_opt_set_int(resampler, "out_channel_layout", frame->channel_layout, 0);
|
|
}
|
|
|
|
av_opt_set_int(resampler, "in_sample_rate", context->inputFormat.mSampleRate, 0);
|
|
av_opt_set_int(resampler, "out_sample_rate", context->inputFormat.mSampleRate, 0);
|
|
|
|
av_opt_set_int(resampler, "in_sample_fmt", context->avctx->sample_fmt, 0);
|
|
av_opt_set_int(resampler, "out_sample_fmt", context->out_sample_format, 0);
|
|
|
|
if (context->matrix_encoding != AV_MATRIX_ENCODING_NONE) {
|
|
av_opt_set_int(resampler, "matrix_encoding", context->matrix_encoding, 0);
|
|
}
|
|
|
|
ret = avresample_open(resampler);
|
|
|
|
if (ret) {
|
|
avresample_free(&resampler);
|
|
}
|
|
else {
|
|
context->resampler = resampler;
|
|
}
|
|
}
|
|
|
|
return ret;
|
|
}
|
|
|
|
static int resample(MP42DecodeContext *context, AVFrame *frame, uint8_t **output_data, int *output_data_size)
|
|
{
|
|
int ret = 0;
|
|
if (!context->resampler) {
|
|
ret = initResampler(context, frame);
|
|
if (ret) {
|
|
return ret;
|
|
}
|
|
}
|
|
|
|
int out_samples = avresample_get_out_samples(context->resampler, frame->nb_samples);
|
|
int out_nb_channels = context->outputFormat.mChannelsPerFrame;
|
|
|
|
int in_plane_size, out_plane_size = 0;
|
|
|
|
*output_data_size = av_samples_get_buffer_size(&in_plane_size, out_nb_channels,
|
|
out_samples,
|
|
context->out_sample_format, 1);
|
|
|
|
*output_data = malloc(*output_data_size + AV_INPUT_BUFFER_PADDING_SIZE);
|
|
|
|
// if resampling is needed, call avresample_convert
|
|
out_samples = avresample_convert(context->resampler,
|
|
output_data, out_plane_size, out_samples,
|
|
frame->extended_data, in_plane_size, frame->nb_samples);
|
|
|
|
// Recompute output_data_size following swr_convert result (number of samples actually converted)
|
|
*output_data_size = av_samples_get_buffer_size(&out_plane_size, out_nb_channels,
|
|
out_samples,
|
|
context->out_sample_format, 1);
|
|
|
|
return ret;
|
|
}
|
|
|
|
static int decode(MP42DecodeContext *context, MP42SampleBuffer *inSample, MP42SampleBuffer **outSample)
|
|
{
|
|
int ret;
|
|
|
|
AVPacket *pkt = packetFromSampleBuffer(inSample);
|
|
ret = avcodec_send_packet(context->avctx, pkt);
|
|
av_packet_free(&pkt);
|
|
|
|
// In particular, we don't expect AVERROR(EAGAIN), because we read all
|
|
// decoded frames with avcodec_receive_frame() until done.
|
|
if (ret < 0) {
|
|
printf("%s\n", av_err2str(ret));
|
|
return ret == AVERROR_EOF ? 0 : ret;
|
|
}
|
|
|
|
AVFrame *frame = av_frame_alloc();
|
|
ret = avcodec_receive_frame(context->avctx, frame);
|
|
if (!ret) {
|
|
uint8_t *output_data = NULL;
|
|
int output_data_size = 0;
|
|
resample(context, frame, &output_data, &output_data_size);
|
|
*outSample = sampleBufferFromFrame(output_data, output_data_size);
|
|
}
|
|
av_frame_free(&frame);
|
|
|
|
if (ret < 0 && ret != AVERROR(EAGAIN) && ret != AVERROR_EOF) {
|
|
printf("%s\n", av_err2str(ret));
|
|
return ret;
|
|
}
|
|
|
|
return 0;
|
|
}
|
|
|
|
- (void)threadMainRoutine
|
|
{
|
|
@autoreleasepool {
|
|
MP42SampleBuffer *sampleBuffer = nil;
|
|
|
|
while ((sampleBuffer = [_inputSamplesBuffer dequeueAndWait])) {
|
|
@autoreleasepool {
|
|
|
|
MP42SampleBuffer *outSample = nil;
|
|
BOOL lastSample = NO;
|
|
|
|
if (sampleBuffer->flags & MP42SampleBufferFlagEndOfFile) {
|
|
outSample = sampleBuffer;
|
|
lastSample = YES;
|
|
}
|
|
else {
|
|
decode(_context, sampleBuffer, &outSample);
|
|
}
|
|
|
|
if (outSample) {
|
|
if (_outputType == MP42AudioUnitOutputPush) {
|
|
[_outputUnit addSample:outSample];
|
|
}
|
|
else {
|
|
[_outputSamplesBuffer enqueue:outSample];
|
|
}
|
|
}
|
|
|
|
if (lastSample) {
|
|
return;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
@end
|