Almost working ffmpeg audio decoder.
This commit is contained in:
1 parent
4eef942db4
commit
40de19c125
16 files changed
+1083
-1064
No files matched your search
@@ -0,0 +1,22 @@
|
||||
//
|
||||
// FFmpegUtils.h
|
||||
// MP42Foundation
|
||||
//
|
||||
// Created by Damiano Galassi on 23/07/2016.
|
||||
// Copyright © 2016 Damiano Galassi. All rights reserved.
|
||||
//
|
||||
|
||||
#ifndef FFmpegUtils_h
|
||||
#define FFmpegUtils_h
|
||||
|
||||
#include <Foundation/Foundation.h>
|
||||
#include <avcodec.h>
|
||||
|
||||
void FFInitFFmpeg();
|
||||
enum AVCodecID FourCCToCodecID(OSType formatID);
|
||||
OSType CodecIDToFourCC(enum AVCodecID codecID);
|
||||
|
||||
void hb_ff_set_sample_fmt(AVCodecContext *context, AVCodec *codec,
|
||||
enum AVSampleFormat request_sample_fmt);
|
||||
|
||||
#endif /* FFmpegUtils_h */
|
||||
@@ -0,0 +1,146 @@
|
||||
//
|
||||
// FFmpegUtils.c
|
||||
// MP42Foundation
|
||||
//
|
||||
// Created by Damiano Galassi on 23/07/2016.
|
||||
// Copyright © 2016 Damiano Galassi. All rights reserved.
|
||||
//
|
||||
|
||||
#include "FFmpegUtils.h"
|
||||
|
||||
#include <avcodec.h>
|
||||
#include <pthread.h>
|
||||
#include <AudioToolbox/AudioToolbox.h>
|
||||
|
||||
#define REGISTER_DECODER(x) { \
|
||||
extern AVCodec ff_##x##_decoder; \
|
||||
avcodec_register(&ff_##x##_decoder); }
|
||||
|
||||
static int ff_lockmgr_cb(void **mutex, enum AVLockOp op)
|
||||
{
|
||||
switch (op) {
|
||||
case AV_LOCK_CREATE:
|
||||
{
|
||||
pthread_mutex_t *ff_mutext = calloc(1, sizeof(pthread_mutex_t));
|
||||
*mutex = ff_mutext;
|
||||
pthread_mutex_init(*mutex, NULL);
|
||||
} break;
|
||||
case AV_LOCK_DESTROY:
|
||||
{
|
||||
pthread_mutex_destroy(*mutex);
|
||||
free(*mutex);
|
||||
} break;
|
||||
case AV_LOCK_OBTAIN:
|
||||
{
|
||||
pthread_mutex_lock(*mutex);
|
||||
} break;
|
||||
case AV_LOCK_RELEASE:
|
||||
{
|
||||
pthread_mutex_unlock(*mutex);
|
||||
} break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
void FFInitFFmpeg()
|
||||
{
|
||||
static dispatch_once_t once;
|
||||
|
||||
dispatch_once(&once, ^{
|
||||
av_lockmgr_register(ff_lockmgr_cb);
|
||||
REGISTER_DECODER(dvdsub);
|
||||
REGISTER_DECODER(pgssub);
|
||||
REGISTER_DECODER(aac);
|
||||
REGISTER_DECODER(ac3);
|
||||
REGISTER_DECODER(eac3);
|
||||
REGISTER_DECODER(flac);
|
||||
REGISTER_DECODER(vorbis);
|
||||
});
|
||||
}
|
||||
|
||||
// List of codec IDs we know about and that map to audio fourccs
|
||||
static const struct {
|
||||
OSType mFormatID;
|
||||
enum AVCodecID codecID;
|
||||
} kAudioCodecMap[] =
|
||||
{
|
||||
{ kAudioFormatMPEGLayer1, AV_CODEC_ID_MP1 },
|
||||
{ kAudioFormatMPEGLayer2, AV_CODEC_ID_MP2 },
|
||||
{ kAudioFormatMPEGLayer3, AV_CODEC_ID_MP3 },
|
||||
{ 'ms\0\0' + 0x50, AV_CODEC_ID_MP2 },
|
||||
|
||||
{ kAudioFormatLinearPCM, AV_CODEC_ID_PCM_S16LE },
|
||||
{ kAudioFormatLinearPCM, AV_CODEC_ID_PCM_U8 },
|
||||
{ kAudioFormatALaw, AV_CODEC_ID_PCM_ALAW },
|
||||
{ kAudioFormatULaw, AV_CODEC_ID_PCM_MULAW },
|
||||
{ kAudioFormatMPEG4AAC, AV_CODEC_ID_AAC },
|
||||
{ 'XiFL', AV_CODEC_ID_FLAC },
|
||||
{ 'XiVs', AV_CODEC_ID_VORBIS },
|
||||
{0, AV_CODEC_ID_NONE }
|
||||
};
|
||||
|
||||
enum AVCodecID FourCCToCodecID(OSType formatID)
|
||||
{
|
||||
for (int i = 0; kAudioCodecMap[i].codecID != AV_CODEC_ID_NONE; i++) {
|
||||
if (kAudioCodecMap[i].mFormatID == formatID) {
|
||||
return kAudioCodecMap[i].codecID;
|
||||
}
|
||||
}
|
||||
return AV_CODEC_ID_NONE;
|
||||
}
|
||||
|
||||
OSType OSTypeFCodecIDToFourCC(enum AVCodecID codecID)
|
||||
{
|
||||
for (int i = 0; kAudioCodecMap[i].codecID != AV_CODEC_ID_NONE; i++) {
|
||||
if (kAudioCodecMap[i].codecID == codecID) {
|
||||
return kAudioCodecMap[i].mFormatID;
|
||||
}
|
||||
}
|
||||
return AV_CODEC_ID_NONE;
|
||||
}
|
||||
|
||||
/*
|
||||
* Set sample format to the request format if supported by the codec.
|
||||
* The planar/packed variant of the requested format is the next best thing.
|
||||
*/
|
||||
void hb_ff_set_sample_fmt(AVCodecContext *context, AVCodec *codec,
|
||||
enum AVSampleFormat request_sample_fmt)
|
||||
{
|
||||
if (context != NULL && codec != NULL &&
|
||||
codec->type == AVMEDIA_TYPE_AUDIO && codec->sample_fmts != NULL)
|
||||
{
|
||||
const enum AVSampleFormat *fmt;
|
||||
enum AVSampleFormat next_best_fmt;
|
||||
|
||||
next_best_fmt = (av_sample_fmt_is_planar(request_sample_fmt) ?
|
||||
av_get_packed_sample_fmt(request_sample_fmt) :
|
||||
av_get_planar_sample_fmt(request_sample_fmt));
|
||||
|
||||
context->request_sample_fmt = AV_SAMPLE_FMT_NONE;
|
||||
|
||||
for (fmt = codec->sample_fmts; *fmt != AV_SAMPLE_FMT_NONE; fmt++)
|
||||
{
|
||||
if (*fmt == request_sample_fmt)
|
||||
{
|
||||
context->request_sample_fmt = request_sample_fmt;
|
||||
break;
|
||||
}
|
||||
else if (*fmt == next_best_fmt)
|
||||
{
|
||||
context->request_sample_fmt = next_best_fmt;
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
* When encoding and AVCodec.sample_fmts exists, avcodec_open2()
|
||||
* will error out if AVCodecContext.sample_fmt isn't set.
|
||||
*/
|
||||
if (context->request_sample_fmt == AV_SAMPLE_FMT_NONE)
|
||||
{
|
||||
context->request_sample_fmt = codec->sample_fmts[0];
|
||||
}
|
||||
context->sample_fmt = context->request_sample_fmt;
|
||||
}
|
||||
}
|
||||
@@ -6,11 +6,9 @@
|
||||
// Copyright 2010 Damiano Galassi. All rights reserved.
|
||||
//
|
||||
|
||||
#import <Cocoa/Cocoa.h>
|
||||
#include "sfifo.h"
|
||||
#import <Foundation/Foundation.h>
|
||||
#include "downmix.h"
|
||||
#import "MP42ConverterProtocol.h"
|
||||
#import "MP42Fifo.h"
|
||||
|
||||
#import <AudioToolbox/AudioToolbox.h>
|
||||
#import <CoreAudio/CoreAudio.h>
|
||||
@@ -25,57 +23,7 @@ extern NSString * const SBStereoMixdown;
|
||||
extern NSString * const SBDolbyMixdown;
|
||||
extern NSString * const SBDolbyPlIIMixdown;
|
||||
|
||||
// a struct to hold info for the data proc
|
||||
static struct AudioFileIO
|
||||
{
|
||||
AudioConverterRef converter;
|
||||
AudioStreamBasicDescription inputFormat;
|
||||
AudioStreamBasicDescription outputFormat;
|
||||
|
||||
sfifo_t *fifo;
|
||||
|
||||
SInt64 pos;
|
||||
char * srcBuffer;
|
||||
UInt32 srcBufferSize;
|
||||
UInt32 srcSizePerPacket;
|
||||
UInt32 numPacketsPerRead;
|
||||
|
||||
AudioStreamBasicDescription srcFormat;
|
||||
AudioStreamPacketDescription * _Nullable pktDescs;
|
||||
|
||||
MP42Fifo<MP42SampleBuffer *> *inputSamplesBuffer;
|
||||
|
||||
MP42SampleBuffer *sample;
|
||||
int fileReaderDone;
|
||||
} AudioFileIO;
|
||||
|
||||
@interface MP42AudioConverter : NSObject <MP42ConverterProtocol> {
|
||||
NSThread *decoderThread;
|
||||
NSThread *encoderThread;
|
||||
|
||||
sfifo_t fifo;
|
||||
|
||||
BOOL readerDone;
|
||||
BOOL encoderDone;
|
||||
|
||||
int32_t _cancelled;
|
||||
|
||||
Float64 sampleRate;
|
||||
UInt32 inputChannelsCount;
|
||||
UInt32 outputChannelCount;
|
||||
|
||||
NSUInteger downmixType;
|
||||
NSUInteger layout;
|
||||
hb_chan_map_t *ichanmap;
|
||||
|
||||
MP42Fifo<MP42SampleBuffer *> *_inputSamplesBuffer;
|
||||
MP42Fifo<MP42SampleBuffer *> *_outputSamplesBuffer;
|
||||
|
||||
NSData *outputMagicCookie;
|
||||
|
||||
struct AudioFileIO decoderData;
|
||||
struct AudioFileIO encoderData;
|
||||
}
|
||||
@interface MP42AudioConverter : NSObject <MP42ConverterProtocol>
|
||||
|
||||
- (instancetype)initWithTrack:(MP42AudioTrack *)track andMixdownType:(NSString *)mixdownType error:(NSError **)error;
|
||||
|
||||
|
||||
+82
-682
@@ -7,439 +7,25 @@
|
||||
//
|
||||
|
||||
#import "MP42AudioConverter.h"
|
||||
#import "MP42Track.h"
|
||||
#import "MP42AudioTrack.h"
|
||||
#import "MP42FileImporter.h"
|
||||
#import "MP42FileImporter+Private.h"
|
||||
#import "MP42MediaFormat.h"
|
||||
#import "MP42Fifo.h"
|
||||
#import "MP42PrivateUtilities.h"
|
||||
|
||||
#import "MP42ComponentLoader.h"
|
||||
#import "MP42AudioDecoder.h"
|
||||
#import "MP42AudioEncoder.h"
|
||||
|
||||
#import "MP42Track+Muxer.h"
|
||||
#import "MP42FileImporter+Private.h"
|
||||
|
||||
#define FIFO_DURATION (0.5f)
|
||||
@interface MP42AudioConverter ()
|
||||
|
||||
@property (nonatomic, readonly) MP42AudioDecoder *decoder;
|
||||
@property (nonatomic, readonly) MP42AudioEncoder *encoder;
|
||||
|
||||
@end
|
||||
|
||||
@implementation MP42AudioConverter
|
||||
|
||||
#pragma mark - Encoder
|
||||
|
||||
OSStatus EncoderDataProc(AudioConverterRef inAudioConverter,
|
||||
UInt32* ioNumberDataPackets,
|
||||
AudioBufferList* ioData,
|
||||
AudioStreamPacketDescription** outDataPacketDescription,
|
||||
void* inUserData)
|
||||
{
|
||||
struct AudioFileIO *afio = (struct AudioFileIO *)inUserData;
|
||||
|
||||
// figure out how much to read
|
||||
if (*ioNumberDataPackets > afio->numPacketsPerRead) {
|
||||
*ioNumberDataPackets = afio->numPacketsPerRead;
|
||||
}
|
||||
|
||||
// read from the fifo
|
||||
UInt32 outNumBytes;
|
||||
unsigned int wanted = MIN(*ioNumberDataPackets * afio->srcSizePerPacket, sfifo_used(afio->fifo));
|
||||
|
||||
outNumBytes = sfifo_read(afio->fifo, afio->srcBuffer, wanted);
|
||||
OSStatus err = noErr;
|
||||
if (outNumBytes < wanted) {
|
||||
*ioNumberDataPackets = 0;
|
||||
printf ("Input Proc Read error: %d (%4.4s)\n", (int)err, (char*)&err);
|
||||
return err;
|
||||
}
|
||||
|
||||
if (*ioNumberDataPackets == 0) {
|
||||
printf("End\n");
|
||||
}
|
||||
|
||||
// put the data pointer into the buffer list
|
||||
|
||||
ioData->mBuffers[0].mData = afio->srcBuffer;
|
||||
ioData->mBuffers[0].mDataByteSize = outNumBytes;
|
||||
ioData->mBuffers[0].mNumberChannels = afio->srcFormat.mChannelsPerFrame;
|
||||
|
||||
*ioNumberDataPackets = ioData->mBuffers[0].mDataByteSize / afio->srcSizePerPacket;
|
||||
|
||||
afio->pos += *ioNumberDataPackets;
|
||||
|
||||
if (outDataPacketDescription) {
|
||||
if (afio->pktDescs) {
|
||||
*outDataPacketDescription = afio->pktDescs;
|
||||
}
|
||||
else {
|
||||
*outDataPacketDescription = NULL;
|
||||
}
|
||||
}
|
||||
|
||||
return err;
|
||||
}
|
||||
|
||||
- (void)encoderThreadMainRoutine
|
||||
{
|
||||
@autoreleasepool {
|
||||
encoderDone = NO;
|
||||
OSStatus err;
|
||||
|
||||
// set up aac converter
|
||||
AudioConverterRef converterEnc;
|
||||
AudioStreamBasicDescription inputFormat, encoderFormat;
|
||||
|
||||
bzero( &inputFormat, sizeof( AudioStreamBasicDescription ) );
|
||||
inputFormat.mSampleRate = sampleRate;
|
||||
inputFormat.mFormatID = kAudioFormatLinearPCM ;
|
||||
inputFormat.mFormatFlags = kLinearPCMFormatFlagIsFloat | kAudioFormatFlagsNativeEndian;
|
||||
inputFormat.mBytesPerPacket = 4 * outputChannelCount;
|
||||
inputFormat.mFramesPerPacket = 1;
|
||||
inputFormat.mBytesPerFrame = inputFormat.mBytesPerPacket * inputFormat.mFramesPerPacket;
|
||||
inputFormat.mChannelsPerFrame = outputChannelCount;
|
||||
inputFormat.mBitsPerChannel = 32;
|
||||
|
||||
bzero( &encoderFormat, sizeof( AudioStreamBasicDescription ) );
|
||||
encoderFormat.mFormatID = kAudioFormatMPEG4AAC;
|
||||
encoderFormat.mSampleRate = ( Float64 ) inputFormat.mSampleRate;
|
||||
encoderFormat.mChannelsPerFrame = inputFormat.mChannelsPerFrame;
|
||||
|
||||
err = AudioConverterNew( &inputFormat, &encoderFormat, &converterEnc );
|
||||
if (err) {
|
||||
NSLog(@"Boom encoder converter init failed");
|
||||
}
|
||||
|
||||
UInt32 tmp, tmpsiz = sizeof( tmp );
|
||||
|
||||
// set encoder quality to maximum
|
||||
tmp = kAudioConverterQuality_Max;
|
||||
AudioConverterSetProperty( converterEnc, kAudioConverterCodecQuality,
|
||||
sizeof( tmp ), &tmp );
|
||||
|
||||
// set encoder bitrate control mode to constrained variable
|
||||
tmp = kAudioCodecBitRateControlMode_VariableConstrained;
|
||||
AudioConverterSetProperty( converterEnc, kAudioCodecPropertyBitRateControlMode,
|
||||
sizeof( tmp ), &tmp );
|
||||
|
||||
// set bitrate
|
||||
UInt32 bitrate = (UInt32)[[[NSUserDefaults standardUserDefaults] valueForKey:@"SBAudioBitrate"] integerValue];
|
||||
if (!bitrate) bitrate = 80;
|
||||
|
||||
// get available bitrates
|
||||
AudioValueRange *bitrates;
|
||||
ssize_t bitrateCounts;
|
||||
err = AudioConverterGetPropertyInfo( converterEnc, kAudioConverterApplicableEncodeBitRates,
|
||||
&tmpsiz, NULL);
|
||||
if (err) {
|
||||
NSLog(@"err kAudioConverterApplicableEncodeBitRates From AudioConverter");
|
||||
}
|
||||
bitrates = malloc( tmpsiz );
|
||||
err = AudioConverterGetProperty( converterEnc, kAudioConverterApplicableEncodeBitRates,
|
||||
&tmpsiz, bitrates);
|
||||
if (err) {
|
||||
NSLog(@"err kAudioConverterApplicableEncodeBitRates From AudioConverter");
|
||||
}
|
||||
bitrateCounts = tmpsiz / sizeof( AudioValueRange );
|
||||
|
||||
// set bitrate
|
||||
tmp = bitrate * outputChannelCount * 1000;
|
||||
if( tmp < bitrates[0].mMinimum ) {
|
||||
tmp = bitrates[0].mMinimum;
|
||||
}
|
||||
if( tmp > bitrates[bitrateCounts-1].mMinimum ) {
|
||||
tmp = bitrates[bitrateCounts-1].mMinimum;
|
||||
}
|
||||
free( bitrates );
|
||||
|
||||
AudioConverterSetProperty( converterEnc, kAudioConverterEncodeBitRate,
|
||||
sizeof( tmp ), &tmp );
|
||||
|
||||
// get real input
|
||||
tmpsiz = sizeof(inputFormat);
|
||||
AudioConverterGetProperty( converterEnc,
|
||||
kAudioConverterCurrentInputStreamDescription,
|
||||
&tmpsiz, &inputFormat );
|
||||
|
||||
// get real output
|
||||
tmpsiz = sizeof(encoderFormat);
|
||||
AudioConverterGetProperty( converterEnc,
|
||||
kAudioConverterCurrentOutputStreamDescription,
|
||||
&tmpsiz, &encoderFormat );
|
||||
|
||||
// set up buffers and data proc info struct
|
||||
encoderData.srcBufferSize = 32768;
|
||||
encoderData.srcBuffer = (char *) malloc(encoderData.srcBufferSize);
|
||||
encoderData.pos = 0;
|
||||
encoderData.srcFormat = inputFormat;
|
||||
encoderData.srcSizePerPacket = inputFormat.mBytesPerPacket;
|
||||
encoderData.numPacketsPerRead = encoderData.srcBufferSize / encoderData.srcSizePerPacket;
|
||||
encoderData.pktDescs = NULL;
|
||||
encoderData.fifo = &fifo;
|
||||
|
||||
// set up our output buffers
|
||||
int outputSizePerPacket = encoderFormat.mBytesPerPacket; // this will be non-zero if the format is CBR
|
||||
UInt32 size = sizeof(outputSizePerPacket);
|
||||
err = AudioConverterGetProperty(converterEnc, kAudioConverterPropertyMaximumOutputPacketSize,
|
||||
&size, &outputSizePerPacket);
|
||||
if (err) {
|
||||
NSLog(@"Boom kAudioConverterPropertyMaximumOutputPacketSize");
|
||||
}
|
||||
|
||||
UInt32 theOutputBufSize = outputSizePerPacket;
|
||||
char *outputBuffer = (char *)malloc(theOutputBufSize);
|
||||
|
||||
// grab the cookie from the converter and write it to the file
|
||||
UInt32 cookieSize = 0;
|
||||
err = AudioConverterGetPropertyInfo(converterEnc, kAudioConverterCompressionMagicCookie, &cookieSize, NULL);
|
||||
// if there is an error here, then the format doesn't have a cookie, so on we go
|
||||
if (!err && cookieSize) {
|
||||
char* cookie = (char *) malloc(cookieSize);
|
||||
UInt8* cookieBuffer;
|
||||
|
||||
err = AudioConverterGetProperty(converterEnc, kAudioConverterCompressionMagicCookie, &cookieSize, cookie);
|
||||
if (err) {
|
||||
NSLog(@"err Get Cookie From AudioConverter");
|
||||
}
|
||||
|
||||
int ESDSsize;
|
||||
ReadESDSDescExt(cookie, &cookieBuffer, &ESDSsize, 1);
|
||||
outputMagicCookie = [[NSData dataWithBytes:cookieBuffer length:ESDSsize] retain];
|
||||
|
||||
free(cookieBuffer);
|
||||
free(cookie);
|
||||
}
|
||||
|
||||
// loop to convert data
|
||||
SInt64 outputPos = 0;
|
||||
|
||||
while (1) {
|
||||
AudioStreamPacketDescription odesc = {0, 0, 0};
|
||||
|
||||
// set up output buffer list
|
||||
AudioBufferList fillBufList;
|
||||
fillBufList.mNumberBuffers = 1;
|
||||
fillBufList.mBuffers[0].mNumberChannels = inputFormat.mChannelsPerFrame;
|
||||
fillBufList.mBuffers[0].mDataByteSize = theOutputBufSize;
|
||||
fillBufList.mBuffers[0].mData = outputBuffer;
|
||||
|
||||
while ((sfifo_used(&fifo) < (inputFormat.mBytesPerPacket * encoderFormat.mFramesPerPacket * 4)) && !readerDone) {
|
||||
usleep(500);
|
||||
}
|
||||
|
||||
// convert data
|
||||
UInt32 ioOutputDataPackets = 1;
|
||||
err = AudioConverterFillComplexBuffer(converterEnc, EncoderDataProc, &encoderData, &ioOutputDataPackets,
|
||||
&fillBufList, &odesc);
|
||||
if (err) {
|
||||
//NSLog(@"Error converterEnc %ld", (long)err);
|
||||
}
|
||||
if (ioOutputDataPackets == 0) {
|
||||
// this is the EOF conditon
|
||||
break;
|
||||
}
|
||||
|
||||
MP42SampleBuffer *sample = [[MP42SampleBuffer alloc] init];
|
||||
sample->data = malloc(fillBufList.mBuffers[0].mDataByteSize);
|
||||
memcpy(sample->data, outputBuffer, fillBufList.mBuffers[0].mDataByteSize);
|
||||
|
||||
sample->size = fillBufList.mBuffers[0].mDataByteSize;
|
||||
sample->duration = 1024;
|
||||
sample->offset = 0;
|
||||
sample->timestamp = outputPos;
|
||||
sample->isSync = YES;
|
||||
|
||||
[_outputSamplesBuffer enqueue:sample];
|
||||
[sample release];
|
||||
|
||||
outputPos += ioOutputDataPackets;
|
||||
}
|
||||
|
||||
free(outputBuffer);
|
||||
|
||||
AudioConverterDispose(converterEnc);
|
||||
|
||||
[self enqueueEndOfFileSample];
|
||||
encoderDone = YES;
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
#pragma mark - Decoder
|
||||
// decoder input data proc callback
|
||||
|
||||
OSStatus DecoderDataProc(AudioConverterRef inAudioConverter,
|
||||
UInt32* ioNumberDataPackets,
|
||||
AudioBufferList* ioData,
|
||||
AudioStreamPacketDescription** outDataPacketDescription,
|
||||
void* inUserData)
|
||||
{
|
||||
OSStatus err = noErr;
|
||||
struct AudioFileIO *afio = inUserData;
|
||||
|
||||
if (afio->sample) {
|
||||
[afio->sample release];
|
||||
}
|
||||
|
||||
// figure out how much to read
|
||||
if (*ioNumberDataPackets > afio->numPacketsPerRead) *ioNumberDataPackets = afio->numPacketsPerRead;
|
||||
|
||||
// read from the buffer
|
||||
while ([afio->inputSamplesBuffer isEmpty] && !afio->fileReaderDone) {
|
||||
usleep(250);
|
||||
}
|
||||
|
||||
if ([afio->inputSamplesBuffer isEmpty] && afio->fileReaderDone) {
|
||||
*ioNumberDataPackets = 0;
|
||||
return err;
|
||||
}
|
||||
else {
|
||||
afio->sample = [afio->inputSamplesBuffer dequeue];
|
||||
}
|
||||
|
||||
// advance input file packet position
|
||||
afio->pos += *ioNumberDataPackets;
|
||||
|
||||
// put the data pointer into the buffer list
|
||||
ioData->mBuffers[0].mData = afio->sample->data;
|
||||
ioData->mBuffers[0].mDataByteSize = afio->sample->size;
|
||||
ioData->mBuffers[0].mNumberChannels = afio->srcFormat.mChannelsPerFrame;
|
||||
|
||||
if (outDataPacketDescription) {
|
||||
if (afio->pktDescs) {
|
||||
afio->pktDescs->mStartOffset = 0;
|
||||
afio->pktDescs->mVariableFramesInPacket = *ioNumberDataPackets;
|
||||
afio->pktDescs->mDataByteSize = afio->sample->size;
|
||||
*outDataPacketDescription = afio->pktDescs;
|
||||
}
|
||||
else {
|
||||
*outDataPacketDescription = NULL;
|
||||
}
|
||||
}
|
||||
|
||||
return err;
|
||||
}
|
||||
|
||||
- (void)decoderThreadMainRoutine {
|
||||
@autoreleasepool {
|
||||
OSStatus err;
|
||||
|
||||
// set up buffers and data proc info struct
|
||||
decoderData.srcBufferSize = 32768;
|
||||
decoderData.srcBuffer = (char *)malloc( decoderData.srcBufferSize );
|
||||
decoderData.pos = 0;
|
||||
decoderData.srcFormat = decoderData.inputFormat;
|
||||
decoderData.numPacketsPerRead = 1;
|
||||
decoderData.pktDescs = (AudioStreamPacketDescription *)malloc(decoderData.numPacketsPerRead * sizeof(AudioStreamPacketDescription));
|
||||
decoderData.inputSamplesBuffer = _inputSamplesBuffer;
|
||||
|
||||
// set up our output buffers
|
||||
AudioStreamPacketDescription* outputPktDescs = NULL;
|
||||
int outputSizePerPacket = decoderData.outputFormat.mBytesPerPacket; // this will be non-zero if the format is CBR
|
||||
UInt32 theOutputBufSize = 32768;
|
||||
char *outputBuffer = (char *)malloc(theOutputBufSize);
|
||||
|
||||
UInt32 numOutputPackets = theOutputBufSize / outputSizePerPacket;
|
||||
|
||||
// Launch the encoder thread
|
||||
encoderThread = [[NSThread alloc] initWithTarget:self selector:@selector(encoderThreadMainRoutine) object:nil];
|
||||
[encoderThread setName:@"AAC Encoder"];
|
||||
[encoderThread start];
|
||||
|
||||
// Set up our fifo
|
||||
int ringbuffer_len = sampleRate * FIFO_DURATION * 4 * 23;
|
||||
sfifo_init(&fifo, ringbuffer_len );
|
||||
decoderData.fifo = &fifo;
|
||||
|
||||
// Check if we need to do any downmix
|
||||
hb_downmix_t *downmix = NULL;
|
||||
hb_sample_t *downmix_buffer = NULL;
|
||||
|
||||
if (downmixType && inputChannelsCount == 6) {
|
||||
downmix = hb_downmix_init(HB_INPUT_CH_LAYOUT_3F2R | HB_INPUT_CH_LAYOUT_HAS_LFE,
|
||||
downmixType);
|
||||
}
|
||||
else if (downmixType && inputChannelsCount == 5) {
|
||||
downmix = hb_downmix_init(HB_INPUT_CH_LAYOUT_3F2R,
|
||||
downmixType);
|
||||
}
|
||||
else if (downmixType && inputChannelsCount == 4) {
|
||||
downmix = hb_downmix_init(HB_INPUT_CH_LAYOUT_3F1R,
|
||||
downmixType);
|
||||
}
|
||||
else if (downmixType && inputChannelsCount == 3) {
|
||||
downmix = hb_downmix_init(HB_INPUT_CH_LAYOUT_STEREO | HB_INPUT_CH_LAYOUT_HAS_LFE,
|
||||
downmixType);
|
||||
}
|
||||
else if (downmixType && inputChannelsCount == 2) {
|
||||
downmix = hb_downmix_init(HB_INPUT_CH_LAYOUT_STEREO,
|
||||
downmixType);
|
||||
}
|
||||
|
||||
// loop to convert data
|
||||
while (1) {
|
||||
// set up output buffer list
|
||||
AudioBufferList fillBufList;
|
||||
fillBufList.mNumberBuffers = 1;
|
||||
fillBufList.mBuffers[0].mNumberChannels = decoderData.inputFormat.mChannelsPerFrame;
|
||||
fillBufList.mBuffers[0].mDataByteSize = theOutputBufSize;
|
||||
fillBufList.mBuffers[0].mData = outputBuffer;
|
||||
|
||||
// convert data
|
||||
UInt32 ioOutputDataPackets = numOutputPackets;
|
||||
err = AudioConverterFillComplexBuffer(decoderData.converter, DecoderDataProc, &decoderData, &ioOutputDataPackets,
|
||||
&fillBufList, outputPktDescs);
|
||||
if (err)
|
||||
{
|
||||
//NSLog(@"Error converterDec %ld", (long)err);
|
||||
}
|
||||
if (ioOutputDataPackets == 0) {
|
||||
// this is the EOF conditon
|
||||
break;
|
||||
}
|
||||
|
||||
|
||||
if (ichanmap != &hb_qt_chan_map ) {
|
||||
hb_layout_remap( ichanmap, &hb_qt_chan_map, layout,
|
||||
(float *)outputBuffer,
|
||||
ioOutputDataPackets);
|
||||
}
|
||||
// Dowmnix the audio if needed
|
||||
if (downmix) {
|
||||
size_t samplesBufferSize = ioOutputDataPackets * outputChannelCount * sizeof(float);
|
||||
downmix_buffer = (float *)outputBuffer;
|
||||
|
||||
hb_sample_t *samples = (hb_sample_t *)malloc(samplesBufferSize);
|
||||
hb_downmix(downmix, samples, downmix_buffer, ioOutputDataPackets);
|
||||
|
||||
while (sfifo_space(&fifo) < (samplesBufferSize)) {
|
||||
usleep(5000);
|
||||
}
|
||||
|
||||
sfifo_write(&fifo, samples, samplesBufferSize);
|
||||
free(samples);
|
||||
}
|
||||
else {
|
||||
UInt32 inNumBytes = fillBufList.mBuffers[0].mDataByteSize;
|
||||
|
||||
while (sfifo_space(&fifo) < inNumBytes) {
|
||||
usleep(5000);
|
||||
}
|
||||
|
||||
sfifo_write(&fifo, outputBuffer, inNumBytes);
|
||||
}
|
||||
}
|
||||
readerDone = YES;
|
||||
|
||||
free(outputBuffer);
|
||||
|
||||
if (downmix) {
|
||||
hb_downmix_close(&downmix);
|
||||
}
|
||||
|
||||
AudioConverterDispose(decoderData.converter);
|
||||
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
#pragma mark - Init
|
||||
|
||||
- (instancetype)initWithTrack:(MP42AudioTrack *)track andMixdownType:(NSString *)mixdownType error:(NSError **)error {
|
||||
@@ -447,288 +33,102 @@ OSStatus DecoderDataProc(AudioConverterRef inAudioConverter,
|
||||
self = [super init];
|
||||
|
||||
if (self) {
|
||||
OSStatus err;
|
||||
NSData *magicCookie = [track.muxer_helper->importer magicCookieForTrack:track];
|
||||
UInt32 bitRate = [[[NSUserDefaults standardUserDefaults] valueForKey:@"SBAudioBitrate"] integerValue];
|
||||
AudioStreamBasicDescription asbd = [self basicDescriptorForTrack:track];
|
||||
|
||||
// Load the decoders
|
||||
[[MP42ComponentLoader sharedLoader] loadBundledComponents];
|
||||
_decoder = [[MP42AudioDecoder alloc] initWithAudioFormat:asbd mixdownType:mixdownType magicCookie:magicCookie error:error];
|
||||
|
||||
// Init the FIFO
|
||||
_outputSamplesBuffer = [[MP42Fifo alloc] init];
|
||||
_inputSamplesBuffer = [[MP42Fifo alloc] init];
|
||||
|
||||
// Set the right mixdown to use
|
||||
sampleRate = [track.muxer_helper->importer timescaleForTrack:track];
|
||||
inputChannelsCount = track.sourceChannels;
|
||||
outputChannelCount = track.channels;
|
||||
|
||||
if (inputChannelsCount == 0 || outputChannelCount == 0 || sampleRate == 0) {
|
||||
[self release];
|
||||
if (!_decoder) {
|
||||
return nil;
|
||||
}
|
||||
|
||||
if (outputChannelCount > inputChannelsCount) {
|
||||
outputChannelCount = inputChannelsCount;
|
||||
}
|
||||
_encoder = [[MP42AudioEncoder alloc] initWithInputUnit:_decoder bitRate:bitRate error:error];
|
||||
_encoder.outputUnit = self;
|
||||
_encoder.outputType = MP42AudioUnitOutputPull;
|
||||
|
||||
if ([mixdownType isEqualToString:SBMonoMixdown] && inputChannelsCount > 1) {
|
||||
downmixType = HB_AMIXDOWN_MONO;
|
||||
outputChannelCount = 1;
|
||||
}
|
||||
else if ([mixdownType isEqualToString:SBStereoMixdown] && inputChannelsCount > 2) {
|
||||
downmixType = HB_AMIXDOWN_STEREO;
|
||||
outputChannelCount = 2;
|
||||
}
|
||||
else if ([mixdownType isEqualToString:SBDolbyMixdown] && inputChannelsCount > 2) {
|
||||
downmixType = HB_AMIXDOWN_DOLBY;
|
||||
outputChannelCount = 2;
|
||||
}
|
||||
else if ([mixdownType isEqualToString:SBDolbyPlIIMixdown] && inputChannelsCount > 2) {
|
||||
downmixType = HB_AMIXDOWN_DOLBYPLII;
|
||||
outputChannelCount = 2;
|
||||
}
|
||||
|
||||
if (([track.sourceFormat isEqualToString:MP42AudioFormatTrueHD] ||
|
||||
[track.sourceFormat isEqualToString:MP42AudioFormatAC3]) && inputChannelsCount == 6 ) {
|
||||
|
||||
if (NSAppKitVersionNumber <= NSAppKitVersionNumber10_10_Max) {
|
||||
ichanmap = &hb_smpte_chan_map;
|
||||
}
|
||||
else
|
||||
{
|
||||
ichanmap = &hb_ac3_2_chan_map;
|
||||
}
|
||||
layout = HB_INPUT_CH_LAYOUT_3F2R | HB_INPUT_CH_LAYOUT_HAS_LFE;
|
||||
}
|
||||
else {
|
||||
ichanmap = &hb_qt_chan_map;
|
||||
}
|
||||
|
||||
// Decoder initialization
|
||||
CFDataRef magicCookie = NULL;
|
||||
NSData *srcMagicCookie = [track.muxer_helper->importer magicCookieForTrack:track];
|
||||
AudioStreamBasicDescription inputFormat, outputFormat;
|
||||
|
||||
bzero( &inputFormat, sizeof( AudioStreamBasicDescription ) );
|
||||
inputFormat.mSampleRate = sampleRate;
|
||||
inputFormat.mChannelsPerFrame = track.sourceChannels;
|
||||
|
||||
if (track.sourceFormat) {
|
||||
if ([track.sourceFormat isEqualToString:MP42AudioFormatAAC]) {
|
||||
inputFormat.mFormatID = kAudioFormatMPEG4AAC;
|
||||
|
||||
size_t cookieSize;
|
||||
uint8_t *cookie = CreateEsdsFromSetupData((uint8_t *)srcMagicCookie.bytes, srcMagicCookie.length, &cookieSize, 1, true, false);
|
||||
magicCookie = (CFDataRef) [[NSData dataWithBytes:cookie length:cookieSize] retain];
|
||||
}
|
||||
else if ([track.sourceFormat isEqualToString:MP42AudioFormatALAC]) {
|
||||
inputFormat.mFormatID = kAudioFormatAppleLossless;
|
||||
|
||||
magicCookie = (CFDataRef) [srcMagicCookie retain];
|
||||
}
|
||||
else if ([track.sourceFormat isEqualToString:MP42AudioFormatVorbis]) {
|
||||
inputFormat.mFormatID = 'XiVs';
|
||||
|
||||
magicCookie = createDescExt_XiphVorbis(srcMagicCookie.length, srcMagicCookie.bytes);
|
||||
}
|
||||
else if ([track.sourceFormat isEqualToString:MP42AudioFormatFLAC]) {
|
||||
inputFormat.mFormatID = 'XiFL';
|
||||
|
||||
magicCookie = createDescExt_XiphFLAC(srcMagicCookie.length, srcMagicCookie.bytes);
|
||||
}
|
||||
else if ([track.sourceFormat isEqualToString:MP42AudioFormatAC3]) {
|
||||
inputFormat.mFormatID = kAudioFormatAC3;
|
||||
inputFormat.mFramesPerPacket = 1536;
|
||||
}
|
||||
else if ([track.sourceFormat isEqualToString:MP42AudioFormatEAC3]) {
|
||||
inputFormat.mFormatID = kAudioFormatEnhancedAC3;
|
||||
inputFormat.mFramesPerPacket = 1536;
|
||||
}
|
||||
else if ([track.sourceFormat isEqualToString:MP42AudioFormatDTS]) {
|
||||
inputFormat.mFormatID = 'DTS ';
|
||||
}
|
||||
else if ([track.sourceFormat isEqualToString:MP42AudioFormatMP3]) {
|
||||
inputFormat.mFormatID = kAudioFormatMPEGLayer3;
|
||||
inputFormat.mFramesPerPacket = 1152;
|
||||
}
|
||||
else if ([track.sourceFormat isEqualToString:MP42AudioFormatTrueHD]) {
|
||||
inputFormat.mFormatID = 'trhd';
|
||||
}
|
||||
else if ([track.sourceFormat isEqualToString:MP42AudioFormatPCM]) {
|
||||
AudioStreamBasicDescription temp = [track.muxer_helper->importer audioDescriptionForTrack:track];
|
||||
if (temp.mFormatID) {
|
||||
inputFormat = temp;
|
||||
}
|
||||
else {
|
||||
inputFormat.mFormatID = kAudioFormatLinearPCM;
|
||||
}
|
||||
}
|
||||
else {
|
||||
if (error) {
|
||||
*error = MP42Error(@"Audio Converter Error.",
|
||||
@"Unsupported input format.",
|
||||
130);
|
||||
}
|
||||
[self release];
|
||||
return nil;
|
||||
}
|
||||
}
|
||||
|
||||
bzero(&outputFormat, sizeof(AudioStreamBasicDescription));
|
||||
outputFormat.mSampleRate = sampleRate;
|
||||
outputFormat.mFormatID = kAudioFormatLinearPCM ;
|
||||
outputFormat.mFormatFlags = kLinearPCMFormatFlagIsFloat | kAudioFormatFlagsNativeEndian | kAudioFormatFlagIsPacked;
|
||||
outputFormat.mBytesPerPacket = 4 * track.sourceChannels;
|
||||
outputFormat.mFramesPerPacket = 1;
|
||||
outputFormat.mBytesPerFrame = outputFormat.mBytesPerPacket * outputFormat.mFramesPerPacket;
|
||||
outputFormat.mChannelsPerFrame = track.sourceChannels;
|
||||
outputFormat.mBitsPerChannel = 32;
|
||||
|
||||
// Initialize the decoder.
|
||||
err = AudioConverterNew( &inputFormat, &outputFormat, &decoderData.converter );
|
||||
if (err != noErr) {
|
||||
if (error) {
|
||||
*error = MP42Error(@"Audio Converter Error.",
|
||||
@"The Audio Converter can not be initialized",
|
||||
130);
|
||||
}
|
||||
if (magicCookie) {
|
||||
CFRelease(magicCookie);
|
||||
}
|
||||
[self release];
|
||||
if (!_encoder) {
|
||||
return nil;
|
||||
}
|
||||
|
||||
// set the decoder magic cookie
|
||||
if (magicCookie) {
|
||||
err = AudioConverterSetProperty(decoderData.converter, kAudioConverterDecompressionMagicCookie,
|
||||
CFDataGetLength(magicCookie) , CFDataGetBytePtr(magicCookie) );
|
||||
if( err != noErr) {
|
||||
NSLog(@"Boom Magic Cookie %ld",(long)err);
|
||||
}
|
||||
CFRelease(magicCookie);
|
||||
}
|
||||
|
||||
// Try to set the input channel layout
|
||||
/*UInt32 propertySize = 0;
|
||||
AudioChannelLayout * layout = NULL;
|
||||
err = AudioConverterGetPropertyInfo(decoderData.converter, kAudioConverterInputChannelLayout, &propertySize, NULL);
|
||||
|
||||
if (err == noErr && propertySize > 0) {
|
||||
layout = malloc(sizeof(propertySize));
|
||||
err = AudioConverterGetProperty(decoderData.converter, kAudioConverterInputChannelLayout, &propertySize, layout);
|
||||
if (err) {
|
||||
NSLog(@"Unable to read the channel layout %ld",(long)err);
|
||||
}
|
||||
if (layout->mChannelLayoutTag != kAudioChannelLayoutTag_MPEG_5_1_D && inputChannelsCount > 2) {
|
||||
AudioChannelLayout * newLayout = malloc(sizeof(AudioChannelLayout));
|
||||
bzero( newLayout, sizeof( AudioChannelLayout ) );
|
||||
newLayout->mChannelLayoutTag = kAudioChannelLayoutTag_MPEG_5_1_D;
|
||||
err = AudioConverterSetProperty(decoderData.converter, kAudioConverterInputChannelLayout, sizeof(AudioChannelLayout), newLayout);
|
||||
if (err) {
|
||||
NSLog(@"Unable to set the new channel layout %ld",(long)err);
|
||||
}
|
||||
free(newLayout);
|
||||
}
|
||||
free(layout);
|
||||
}*/
|
||||
|
||||
/*if (([track.sourceFormat isEqualToString:@"True HD"] || [track.sourceFormat isEqualToString:MP42AudioFormatAC3]) && inputChannelsCount == 6 ) {
|
||||
SInt32 channelMap[6] = { 2, 0, 1, 4, 5, 3 };
|
||||
AudioConverterSetProperty( decoderData.converter, kAudioConverterChannelMap,
|
||||
sizeof( channelMap ), channelMap );
|
||||
}*/
|
||||
|
||||
// Read the complete inputStreamDescription from the audio converter.
|
||||
UInt32 size = sizeof(inputFormat);
|
||||
err = AudioConverterGetProperty( decoderData.converter, kAudioConverterCurrentInputStreamDescription,
|
||||
&size, &inputFormat);
|
||||
if (err != noErr) {
|
||||
NSLog(@"Boom kAudioConverterCurrentInputStreamDescription %ld",(long)err);
|
||||
}
|
||||
|
||||
// Read the complete outputStreamDescription from the audio converter.
|
||||
size = sizeof(outputFormat);
|
||||
err = AudioConverterGetProperty(decoderData.converter, kAudioConverterCurrentOutputStreamDescription,
|
||||
&size, &outputFormat);
|
||||
if (err != noErr) {
|
||||
NSLog(@"Boom kAudioConverterCurrentOutputStreamDescription %ld",(long)err);
|
||||
}
|
||||
|
||||
decoderData.inputFormat = inputFormat;
|
||||
decoderData.outputFormat = outputFormat;
|
||||
|
||||
// Launch the decoder thread.
|
||||
decoderThread = [[NSThread alloc] initWithTarget:self selector:@selector(decoderThreadMainRoutine) object:nil];
|
||||
[decoderThread setName:[NSString stringWithFormat:@"%@ Decoder", track.sourceFormat]];
|
||||
[decoderThread start];
|
||||
}
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
- (void)addSample:(MP42SampleBuffer *)sample {
|
||||
if (sample->flags & MP42SampleBufferFlagEndOfFile) {
|
||||
[self setInputDone];
|
||||
}
|
||||
else {
|
||||
[_inputSamplesBuffer enqueue:sample];
|
||||
}
|
||||
}
|
||||
|
||||
- (MP42SampleBuffer *)copyEncodedSample {
|
||||
return [_outputSamplesBuffer dequeue];
|
||||
}
|
||||
|
||||
- (void)setInputDone {
|
||||
decoderData.fileReaderDone = YES;
|
||||
encoderData.fileReaderDone = YES;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends the EOF flag down the muxer chain.
|
||||
*/
|
||||
- (void)enqueueEndOfFileSample
|
||||
- (AudioStreamBasicDescription)basicDescriptorForTrack:(MP42AudioTrack *)track
|
||||
{
|
||||
MP42SampleBuffer *sample = [[MP42SampleBuffer alloc] init];
|
||||
sample->flags |= MP42SampleBufferFlagEndOfFile;
|
||||
[_outputSamplesBuffer enqueue:sample];
|
||||
[sample release];
|
||||
AudioStreamBasicDescription asbd;
|
||||
bzero(&asbd, sizeof(AudioStreamBasicDescription));
|
||||
asbd.mSampleRate = [track.muxer_helper->importer timescaleForTrack:track];;
|
||||
asbd.mChannelsPerFrame = track.sourceChannels;
|
||||
|
||||
NSString *format = track.sourceFormat;
|
||||
|
||||
if ([format isEqualToString:MP42AudioFormatAAC]) {
|
||||
asbd.mFormatID = kAudioFormatMPEG4AAC;
|
||||
}
|
||||
else if ([format isEqualToString:MP42AudioFormatALAC]) {
|
||||
asbd.mFormatID = kAudioFormatAppleLossless;
|
||||
}
|
||||
else if ([format isEqualToString:MP42AudioFormatVorbis]) {
|
||||
asbd.mFormatID = 'XiVs';
|
||||
}
|
||||
else if ([format isEqualToString:MP42AudioFormatFLAC]) {
|
||||
asbd.mFormatID = 'XiFL';
|
||||
}
|
||||
else if ([format isEqualToString:MP42AudioFormatAC3]) {
|
||||
asbd.mFormatID = kAudioFormatAC3;
|
||||
asbd.mFramesPerPacket = 1536;
|
||||
}
|
||||
else if ([format isEqualToString:MP42AudioFormatEAC3]) {
|
||||
asbd.mFormatID = kAudioFormatEnhancedAC3;
|
||||
asbd.mFramesPerPacket = 1536;
|
||||
}
|
||||
else if ([format isEqualToString:MP42AudioFormatDTS]) {
|
||||
asbd.mFormatID = 'DTS ';
|
||||
}
|
||||
else if ([format isEqualToString:MP42AudioFormatMP3]) {
|
||||
asbd.mFormatID = kAudioFormatMPEGLayer3;
|
||||
asbd.mFramesPerPacket = 1152;
|
||||
}
|
||||
else if ([format isEqualToString:MP42AudioFormatTrueHD]) {
|
||||
asbd.mFormatID = 'trhd';
|
||||
}
|
||||
else if ([format isEqualToString:MP42AudioFormatPCM]) {
|
||||
AudioStreamBasicDescription temp = [track.muxer_helper->importer audioDescriptionForTrack:track];
|
||||
if (temp.mFormatID) {
|
||||
asbd = temp;
|
||||
}
|
||||
else {
|
||||
asbd.mFormatID = kAudioFormatLinearPCM;
|
||||
}
|
||||
}
|
||||
|
||||
return asbd;
|
||||
}
|
||||
|
||||
- (void)addSample:(MP42SampleBuffer *)sample
|
||||
{
|
||||
[_decoder addSample:sample];
|
||||
}
|
||||
|
||||
- (MP42SampleBuffer *)copyEncodedSample
|
||||
{
|
||||
return [_encoder copyEncodedSample];
|
||||
}
|
||||
|
||||
- (void)cancel {
|
||||
OSAtomicIncrement32(&_cancelled);
|
||||
|
||||
decoderData.fileReaderDone = YES;
|
||||
encoderData.fileReaderDone = YES;
|
||||
|
||||
[_inputSamplesBuffer cancel];
|
||||
[_outputSamplesBuffer cancel];
|
||||
|
||||
while (!(readerDone && encoderDone)) {
|
||||
usleep(500);
|
||||
}
|
||||
[_decoder cancel];
|
||||
[_encoder cancel];
|
||||
}
|
||||
|
||||
- (NSData *)magicCookie {
|
||||
return [[outputMagicCookie retain] autorelease];
|
||||
return _encoder.magicCookie;
|
||||
}
|
||||
|
||||
- (void)dealloc {
|
||||
sfifo_close(&fifo);
|
||||
|
||||
free(decoderData.srcBuffer);
|
||||
free(decoderData.pktDescs);
|
||||
|
||||
free(encoderData.srcBuffer);
|
||||
free(encoderData.pktDescs);
|
||||
|
||||
[outputMagicCookie release];
|
||||
|
||||
[decoderThread release];
|
||||
[encoderThread release];
|
||||
|
||||
[_outputSamplesBuffer release];
|
||||
[_inputSamplesBuffer release];
|
||||
[_decoder release];
|
||||
[_encoder release];
|
||||
|
||||
[super dealloc];
|
||||
}
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
//
|
||||
// MP42AudioDecoder.h
|
||||
// MP42Foundation
|
||||
//
|
||||
// Created by Damiano Galassi on 23/07/2016.
|
||||
// Copyright © 2016 Damiano Galassi. All rights reserved.
|
||||
//
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
|
||||
#import "MP42AudioUnit.h"
|
||||
|
||||
@class MP42SampleBuffer;
|
||||
@class MP42AudioTrack;
|
||||
|
||||
NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
@interface MP42AudioDecoder : NSObject<MP42AudioUnit>
|
||||
|
||||
- (instancetype)initWithAudioFormat:(AudioStreamBasicDescription)asbd mixdownType:(NSString *)mixdownType magicCookie:(NSData *)magicCookie error:(NSError **)error;
|
||||
|
||||
@property (nonatomic, readonly) AudioStreamBasicDescription inputFormat;
|
||||
@property (nonatomic, readonly) AudioStreamBasicDescription outputFormat;
|
||||
|
||||
- (void)addSample:(MP42SampleBuffer *)sample;
|
||||
- (void)cancel;
|
||||
|
||||
@end
|
||||
|
||||
NS_ASSUME_NONNULL_END
|
||||
@@ -0,0 +1,300 @@
|
||||
//
|
||||
// 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 <libswresample/swresample.h>
|
||||
#include <libavutil/channel_layout.h>
|
||||
#include <libavutil/opt.h>
|
||||
|
||||
@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) SwrContext *swr;
|
||||
|
||||
@property (nonatomic, readwrite) int32_t readerDone;
|
||||
@property (nonatomic, readwrite) int32_t decoderDone;
|
||||
|
||||
@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;
|
||||
}
|
||||
|
||||
hb_ff_set_sample_fmt(_avctx, _codec, AV_SAMPLE_FMT_FLT);
|
||||
|
||||
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");
|
||||
}
|
||||
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;
|
||||
}
|
||||
|
||||
// We want float interleaved, FFmpeg usually prefers
|
||||
// float planar, so we need to convert it.
|
||||
if (_avctx->sample_fmt != AV_SAMPLE_FMT_FLT) {
|
||||
// Set up SWR context once you've got codec information
|
||||
_swr = swr_alloc();
|
||||
av_opt_set_int(_swr, "in_channel_layout", AV_CH_LAYOUT_STEREO, 0);
|
||||
av_opt_set_int(_swr, "out_channel_layout", AV_CH_LAYOUT_STEREO, 0);
|
||||
av_opt_set_int(_swr, "in_sample_rate", _inputFormat.mSampleRate, 0);
|
||||
av_opt_set_int(_swr, "out_sample_rate", _inputFormat.mSampleRate, 0);
|
||||
av_opt_set_sample_fmt(_swr, "in_sample_fmt", _avctx->sample_fmt, 0);
|
||||
av_opt_set_sample_fmt(_swr, "out_sample_fmt", AV_SAMPLE_FMT_FLT, 0);
|
||||
swr_init(_swr);
|
||||
}
|
||||
|
||||
// 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 * _inputFormat.mChannelsPerFrame;
|
||||
outputFormat.mFramesPerPacket = 1;
|
||||
outputFormat.mBytesPerFrame = outputFormat.mBytesPerPacket * outputFormat.mFramesPerPacket;
|
||||
outputFormat.mChannelsPerFrame = _inputFormat.mChannelsPerFrame;
|
||||
outputFormat.mBitsPerChannel = 32;
|
||||
|
||||
_outputFormat = outputFormat;
|
||||
|
||||
_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 (_swr) {
|
||||
swr_free(&_swr);
|
||||
}
|
||||
}
|
||||
|
||||
- (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];
|
||||
}
|
||||
|
||||
- (void)cancel
|
||||
{
|
||||
[_inputSamplesBuffer cancel];
|
||||
}
|
||||
|
||||
#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(AVFrame *frame, SwrContext *swr)
|
||||
{
|
||||
MP42SampleBuffer *sample = [[MP42SampleBuffer alloc] init];
|
||||
|
||||
int out_samples;
|
||||
int out_sample_rate = 44100;
|
||||
int out_nb_channels = 2;
|
||||
enum AVSampleFormat out_sample_format = AV_SAMPLE_FMT_FLT;
|
||||
|
||||
// if sample rate changes, number of samples is different
|
||||
if (out_sample_rate != frame->sample_rate) {
|
||||
//int delay = swr_get_delay(swr, frame->sample_rate);
|
||||
// out_samples = av_rescale_rnd(swr_get_delay(swr_context, avctx->sample_rate) +
|
||||
// frame->nb_samples, out_sample_rate, avctx->sample_rate, AV_ROUND_UP);
|
||||
out_samples = av_rescale_rnd(frame->nb_samples, out_sample_rate, frame->sample_rate, AV_ROUND_UP);
|
||||
}
|
||||
else {
|
||||
out_samples = frame->nb_samples;
|
||||
}
|
||||
|
||||
int plane_size;
|
||||
int planar = av_sample_fmt_is_planar(frame->format);
|
||||
|
||||
int output_data_size = av_samples_get_buffer_size(&plane_size, 2,
|
||||
out_samples,
|
||||
out_sample_format, 1);
|
||||
|
||||
uint8_t *outputBuffer = malloc(output_data_size + AV_INPUT_BUFFER_PADDING_SIZE);
|
||||
|
||||
// if resampling is needed, call swr_convert
|
||||
if (swr) {
|
||||
|
||||
out_samples = swr_convert(swr, &outputBuffer, out_samples,
|
||||
(const uint8_t **)frame->extended_data, frame->nb_samples);
|
||||
|
||||
// recompute output_data_size following swr_convert result (number of samples actually converted)
|
||||
output_data_size = av_samples_get_buffer_size(&plane_size, out_nb_channels,
|
||||
out_samples,
|
||||
out_sample_format, 1);
|
||||
}
|
||||
else {
|
||||
memcpy(outputBuffer, frame->extended_data[0], plane_size);
|
||||
|
||||
if (planar && frame->channels > 1) {
|
||||
uint8_t *out = outputBuffer + plane_size;
|
||||
for (int ch = 1; ch < frame->channels; ch++) {
|
||||
memcpy(out, frame->extended_data[ch], plane_size);
|
||||
out += plane_size;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
sample->data = outputBuffer;
|
||||
sample->size = output_data_size;
|
||||
|
||||
return sample;
|
||||
}
|
||||
|
||||
static int decode(AVCodecContext *avctx, SwrContext *swr, MP42SampleBuffer *inSample, MP42SampleBuffer **outSample)
|
||||
{
|
||||
int ret;
|
||||
|
||||
AVPacket *pkt = packetFromSampleBuffer(inSample);
|
||||
ret = avcodec_send_packet(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(avctx, frame);
|
||||
if (!ret) {
|
||||
*outSample = sampleBufferFromFrame(frame, swr);
|
||||
}
|
||||
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(_avctx, _swr, sampleBuffer, &outSample);
|
||||
}
|
||||
|
||||
if (outSample) {
|
||||
if (_outputType == MP42AudioUnitOutputPush) {
|
||||
[_outputUnit addSample:outSample];
|
||||
}
|
||||
else {
|
||||
[_outputSamplesBuffer enqueue:outSample];
|
||||
}
|
||||
}
|
||||
|
||||
if (lastSample) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@end
|
||||
@@ -0,0 +1,30 @@
|
||||
//
|
||||
// MP42AudioEncoder.h
|
||||
// MP42Foundation
|
||||
//
|
||||
// Created by Damiano Galassi on 23/07/2016.
|
||||
// Copyright © 2016 Damiano Galassi. All rights reserved.
|
||||
//
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
|
||||
#import "MP42AudioUnit.h"
|
||||
|
||||
@class MP42SampleBuffer;
|
||||
|
||||
NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
@interface MP42AudioEncoder : NSObject<MP42AudioUnit>
|
||||
|
||||
- (instancetype)initWithInputUnit:(id<MP42AudioUnit>)unit bitRate:(NSUInteger)bitRate error:(NSError **)error;
|
||||
|
||||
@property (nonatomic, readonly) AudioStreamBasicDescription inputFormat;
|
||||
@property (nonatomic, readonly) AudioStreamBasicDescription outputFormat;
|
||||
@property (nonatomic, readonly) NSData *magicCookie;
|
||||
|
||||
- (void)addSample:(MP42SampleBuffer *)sample;
|
||||
- (void)cancel;
|
||||
|
||||
@end
|
||||
|
||||
NS_ASSUME_NONNULL_END
|
||||
@@ -0,0 +1,395 @@
|
||||
//
|
||||
// MP42AudioEncoder.m
|
||||
// MP42Foundation
|
||||
//
|
||||
// Created by Damiano Galassi on 23/07/2016.
|
||||
// Copyright © 2016 Damiano Galassi. All rights reserved.
|
||||
//
|
||||
|
||||
#import "MP42AudioEncoder.h"
|
||||
#import "MP42Fifo.h"
|
||||
#import "MP42Sample.h"
|
||||
#import "MP42PrivateUtilities.h"
|
||||
|
||||
#include "sfifo.h"
|
||||
|
||||
#define FIFO_DURATION (2.5f)
|
||||
|
||||
// A struct to hold info for the data proc
|
||||
typedef struct AudioFileIO
|
||||
{
|
||||
sfifo_t *ringBuffer;
|
||||
|
||||
char *srcBuffer;
|
||||
UInt32 srcBufferSize;
|
||||
|
||||
UInt32 outputMaxSize;
|
||||
|
||||
UInt32 srcSizePerPacket;
|
||||
UInt32 channelsPerFrame;
|
||||
UInt32 numPacketsPerRead;
|
||||
|
||||
AudioStreamPacketDescription * _Nullable pktDescs;
|
||||
} AudioFileIO;
|
||||
|
||||
@interface MP42AudioEncoder ()
|
||||
{
|
||||
__unsafe_unretained id<MP42AudioUnit> _outputUnit;
|
||||
MP42AudioUnitOutput _outputType;
|
||||
|
||||
NSData *_magicCookie;
|
||||
}
|
||||
|
||||
@property (nonatomic, readonly) AudioConverterRef encoder;
|
||||
|
||||
@property (nonatomic, readonly) NSThread *decoderThread;
|
||||
@property (nonatomic, readonly) MP42Fifo<MP42SampleBuffer *> *inputSamplesBuffer;
|
||||
@property (nonatomic, readonly) MP42Fifo<MP42SampleBuffer *> *outputSamplesBuffer;
|
||||
|
||||
@property (nonatomic, readonly) sfifo_t *ringBuffer;
|
||||
@property (nonatomic, readonly) AudioFileIO afio;
|
||||
|
||||
@property (nonatomic, readonly, unsafe_unretained) id<MP42AudioUnit> inputUnit;
|
||||
|
||||
@property (nonatomic, readwrite) int32_t readerDone;
|
||||
@property (nonatomic, readwrite) int32_t decoderDone;
|
||||
|
||||
@end
|
||||
|
||||
@implementation MP42AudioEncoder
|
||||
|
||||
@synthesize outputUnit = _outputUnit;
|
||||
@synthesize outputType = _outputType;
|
||||
|
||||
@synthesize magicCookie = _magicCookie;
|
||||
|
||||
- (instancetype)initWithInputUnit:(id<MP42AudioUnit>)unit bitRate:(NSUInteger)bitRate error:(NSError **)error
|
||||
{
|
||||
self = [super init];
|
||||
if (self) {
|
||||
_inputUnit = unit;
|
||||
_inputUnit.outputUnit = self;
|
||||
_inputFormat = unit.outputFormat;
|
||||
|
||||
if (![self initConverterWithBitRate:bitRate]) {
|
||||
return nil;
|
||||
}
|
||||
|
||||
if (![self createMagicCookie]) {
|
||||
return nil;
|
||||
}
|
||||
|
||||
_inputSamplesBuffer = [[MP42Fifo alloc] initWithCapacity:100];
|
||||
_outputSamplesBuffer = [[MP42Fifo alloc] initWithCapacity:100];
|
||||
|
||||
[self start];
|
||||
}
|
||||
return self;
|
||||
}
|
||||
|
||||
- (void)dealloc
|
||||
{
|
||||
if (_encoder) {
|
||||
AudioConverterDispose(_encoder);
|
||||
}
|
||||
if (_ringBuffer) {
|
||||
sfifo_close(_ringBuffer);
|
||||
free(_ringBuffer);
|
||||
}
|
||||
}
|
||||
|
||||
#pragma mark - Encoder Init
|
||||
|
||||
- (BOOL)initConverterWithBitRate:(NSUInteger)bitrate
|
||||
{
|
||||
OSStatus err;
|
||||
AudioStreamBasicDescription outputFormat;
|
||||
|
||||
bzero(&outputFormat, sizeof(AudioStreamBasicDescription));
|
||||
outputFormat.mFormatID = kAudioFormatMPEG4AAC;
|
||||
outputFormat.mSampleRate = (Float64) _inputFormat.mSampleRate;
|
||||
outputFormat.mChannelsPerFrame = _inputFormat.mChannelsPerFrame;
|
||||
|
||||
_outputFormat = outputFormat;
|
||||
|
||||
err = AudioConverterNew(&_inputFormat, &_outputFormat, &_encoder);
|
||||
if (err) {
|
||||
NSLog(@"err: encoder converter init failed");
|
||||
return NO;
|
||||
}
|
||||
|
||||
UInt32 tmp, tmpsiz = sizeof(tmp);
|
||||
|
||||
// Set encoder quality to maximum.
|
||||
tmp = kAudioConverterQuality_Max;
|
||||
AudioConverterSetProperty(_encoder, kAudioConverterCodecQuality,
|
||||
sizeof(tmp), &tmp);
|
||||
|
||||
// Set encoder bitrate control mode to constrained variable.
|
||||
tmp = kAudioCodecBitRateControlMode_VariableConstrained;
|
||||
AudioConverterSetProperty(_encoder, kAudioCodecPropertyBitRateControlMode,
|
||||
sizeof(tmp), &tmp);
|
||||
|
||||
// Set bitrate.
|
||||
if (!bitrate) bitrate = 80;
|
||||
|
||||
// Get available bitrates.
|
||||
AudioValueRange *bitrates;
|
||||
ssize_t bitrateCounts;
|
||||
err = AudioConverterGetPropertyInfo(_encoder, kAudioConverterApplicableEncodeBitRates,
|
||||
&tmpsiz, NULL);
|
||||
if (err) {
|
||||
NSLog(@"err: kAudioConverterApplicableEncodeBitRates From AudioConverter");
|
||||
}
|
||||
bitrates = malloc(tmpsiz);
|
||||
err = AudioConverterGetProperty(_encoder, kAudioConverterApplicableEncodeBitRates,
|
||||
&tmpsiz, bitrates);
|
||||
if (err) {
|
||||
NSLog(@"err: kAudioConverterApplicableEncodeBitRates From AudioConverter");
|
||||
}
|
||||
bitrateCounts = tmpsiz / sizeof( AudioValueRange );
|
||||
|
||||
// Set bitrate.
|
||||
tmp = bitrate * outputFormat.mChannelsPerFrame * 1000;
|
||||
if (tmp < bitrates[0].mMinimum) {
|
||||
tmp = bitrates[0].mMinimum;
|
||||
}
|
||||
if (tmp > bitrates[bitrateCounts-1].mMinimum) {
|
||||
tmp = bitrates[bitrateCounts-1].mMinimum;
|
||||
}
|
||||
free(bitrates);
|
||||
|
||||
AudioConverterSetProperty(_encoder, kAudioConverterEncodeBitRate,
|
||||
sizeof( tmp ), &tmp);
|
||||
|
||||
// Get real input.
|
||||
tmpsiz = sizeof(_inputFormat);
|
||||
AudioConverterGetProperty(_encoder,
|
||||
kAudioConverterCurrentInputStreamDescription,
|
||||
&tmpsiz, &_inputFormat);
|
||||
|
||||
// Get real output.
|
||||
tmpsiz = sizeof(_outputFormat);
|
||||
AudioConverterGetProperty(_encoder,
|
||||
kAudioConverterCurrentOutputStreamDescription,
|
||||
&tmpsiz, &_outputFormat);
|
||||
|
||||
// Get the output max size
|
||||
int outputSizePerPacket = _outputFormat.mBytesPerPacket;
|
||||
UInt32 size = sizeof(outputSizePerPacket);
|
||||
err = AudioConverterGetProperty(_encoder, kAudioConverterPropertyMaximumOutputPacketSize,
|
||||
&size, &outputSizePerPacket);
|
||||
if (err) {
|
||||
NSLog(@"err: kAudioConverterPropertyMaximumOutputPacketSize");
|
||||
}
|
||||
|
||||
// Set up our fifo
|
||||
_ringBuffer = (sfifo_t *) malloc(sizeof(sfifo_t));
|
||||
int ringbuffer_len = _inputFormat.mSampleRate * FIFO_DURATION * 4 * 23;
|
||||
sfifo_init(_ringBuffer, ringbuffer_len);
|
||||
|
||||
// Set up buffers and data proc info struct
|
||||
struct AudioFileIO encoderData;
|
||||
encoderData.srcBufferSize = 32768;
|
||||
encoderData.srcBuffer = (char *) malloc(encoderData.srcBufferSize);
|
||||
|
||||
encoderData.outputMaxSize = outputSizePerPacket;
|
||||
|
||||
encoderData.srcSizePerPacket = _inputFormat.mBytesPerPacket;
|
||||
encoderData.channelsPerFrame = _inputFormat.mChannelsPerFrame;
|
||||
encoderData.numPacketsPerRead = encoderData.srcBufferSize / encoderData.srcSizePerPacket;
|
||||
|
||||
encoderData.pktDescs = NULL;
|
||||
encoderData.ringBuffer = _ringBuffer;
|
||||
|
||||
_afio = encoderData;
|
||||
|
||||
return YES;
|
||||
}
|
||||
|
||||
- (BOOL)createMagicCookie
|
||||
{
|
||||
OSStatus err;
|
||||
|
||||
// Grab the cookie from the converter.
|
||||
UInt32 cookieSize = 0;
|
||||
err = AudioConverterGetPropertyInfo(_encoder, kAudioConverterCompressionMagicCookie, &cookieSize, NULL);
|
||||
|
||||
// If there is an error here, then the format doesn't have a cookie, so on we go
|
||||
if (!err && cookieSize) {
|
||||
char *cookie = (char *) malloc(cookieSize);
|
||||
UInt8 *cookieBuffer;
|
||||
|
||||
err = AudioConverterGetProperty(_encoder, kAudioConverterCompressionMagicCookie, &cookieSize, cookie);
|
||||
if (err) {
|
||||
NSLog(@"err: Get Cookie From AudioConverter");
|
||||
}
|
||||
else {
|
||||
int ESDSsize;
|
||||
ReadESDSDescExt(cookie, &cookieBuffer, &ESDSsize, 1);
|
||||
_magicCookie = [NSData dataWithBytes:cookieBuffer length:ESDSsize];
|
||||
|
||||
free(cookieBuffer);
|
||||
free(cookie);
|
||||
|
||||
return YES;
|
||||
}
|
||||
}
|
||||
return NO;
|
||||
}
|
||||
|
||||
- (void)start
|
||||
{
|
||||
_decoderThread = [[NSThread alloc] initWithTarget:self selector:@selector(threadMainRoutine) object:nil];
|
||||
[_decoderThread setName:@"AudioToolbox Audio Encoder"];
|
||||
[_decoderThread start];
|
||||
}
|
||||
|
||||
#pragma mark - Public methods
|
||||
|
||||
- (NSData *)magicCookie
|
||||
{
|
||||
return _magicCookie;
|
||||
}
|
||||
|
||||
- (void)addSample:(MP42SampleBuffer *)sample
|
||||
{
|
||||
[_inputSamplesBuffer enqueue:sample];
|
||||
}
|
||||
|
||||
- (nullable MP42SampleBuffer *)copyEncodedSample
|
||||
{
|
||||
return [_outputSamplesBuffer dequeue];
|
||||
}
|
||||
|
||||
- (void)cancel
|
||||
{
|
||||
[_inputSamplesBuffer cancel];
|
||||
}
|
||||
|
||||
#pragma mark - Encoder
|
||||
|
||||
OSStatus EncoderDataProc(AudioConverterRef inAudioConverter,
|
||||
UInt32 * ioNumberDataPackets,
|
||||
AudioBufferList * ioData,
|
||||
AudioStreamPacketDescription * __nullable * __nullable outDataPacketDescription,
|
||||
void * __nullable inUserData)
|
||||
{
|
||||
AudioFileIO *afio = inUserData;
|
||||
UInt32 availableBytes = sfifo_used(afio->ringBuffer);
|
||||
|
||||
if (!availableBytes) {
|
||||
*ioNumberDataPackets = 0;
|
||||
return 1;
|
||||
}
|
||||
|
||||
// Figure out how much to read
|
||||
if (*ioNumberDataPackets > afio->numPacketsPerRead) {
|
||||
*ioNumberDataPackets = afio->numPacketsPerRead;
|
||||
}
|
||||
|
||||
// Read from the fifo
|
||||
UInt32 wanted = MIN(*ioNumberDataPackets * afio->srcSizePerPacket, availableBytes);
|
||||
UInt32 outNumBytes = sfifo_read(afio->ringBuffer, afio->srcBuffer, wanted);
|
||||
|
||||
// Put the data pointer into the buffer list
|
||||
ioData->mBuffers[0].mData = afio->srcBuffer;
|
||||
ioData->mBuffers[0].mDataByteSize = outNumBytes;
|
||||
ioData->mBuffers[0].mNumberChannels = afio->channelsPerFrame;
|
||||
|
||||
*ioNumberDataPackets = ioData->mBuffers[0].mDataByteSize / afio->srcSizePerPacket;
|
||||
|
||||
if (outDataPacketDescription) {
|
||||
if (afio->pktDescs) {
|
||||
*outDataPacketDescription = afio->pktDescs;
|
||||
}
|
||||
else {
|
||||
*outDataPacketDescription = NULL;
|
||||
}
|
||||
}
|
||||
|
||||
return noErr;
|
||||
}
|
||||
|
||||
static MP42SampleBuffer *encode(AudioConverterRef encoder, AudioFileIO *afio)
|
||||
{
|
||||
OSStatus err = noErr;
|
||||
AudioStreamPacketDescription odesc = {0, 0, 0};
|
||||
UInt32 ioOutputDataPackets = 1;
|
||||
|
||||
MP42SampleBuffer *sample = [[MP42SampleBuffer alloc] init];
|
||||
sample->size = afio->outputMaxSize;
|
||||
sample->data = malloc(afio->outputMaxSize);
|
||||
|
||||
// Set up output buffer list
|
||||
AudioBufferList fillBufList;
|
||||
fillBufList.mNumberBuffers = 1;
|
||||
fillBufList.mBuffers[0].mNumberChannels = afio->channelsPerFrame;
|
||||
fillBufList.mBuffers[0].mDataByteSize = sample->size;
|
||||
fillBufList.mBuffers[0].mData = sample->data;
|
||||
|
||||
// Convert data
|
||||
err = AudioConverterFillComplexBuffer(encoder, EncoderDataProc,
|
||||
afio, &ioOutputDataPackets,
|
||||
&fillBufList, &odesc);
|
||||
if (err != noErr && err != 1) {
|
||||
NSLog(@"err: unexpected error in AudioConverterFillComplexBuffer(): %ld", (long)err);
|
||||
}
|
||||
|
||||
if (ioOutputDataPackets == 0) {
|
||||
return nil;
|
||||
}
|
||||
|
||||
sample->size = fillBufList.mBuffers[0].mDataByteSize;
|
||||
sample->duration = 1024;
|
||||
sample->offset = 0;
|
||||
//sample->timestamp = outputPos;
|
||||
sample->isSync = YES;
|
||||
|
||||
return sample;
|
||||
//outputPos += ioOutputDataPackets;
|
||||
}
|
||||
|
||||
- (void)threadMainRoutine
|
||||
{
|
||||
@autoreleasepool {
|
||||
MP42SampleBuffer *sampleBuffer = nil;
|
||||
|
||||
while ((sampleBuffer = [_inputSamplesBuffer dequeueAndWait])) {
|
||||
@autoreleasepool {
|
||||
|
||||
MP42SampleBuffer *outSample = nil;
|
||||
BOOL lastSample = NO;
|
||||
|
||||
if (sampleBuffer->flags & MP42SampleBufferFlagEndOfFile) {
|
||||
lastSample = YES;
|
||||
}
|
||||
else {
|
||||
sfifo_write(_ringBuffer, sampleBuffer->data, sampleBuffer->size);
|
||||
}
|
||||
|
||||
while ((outSample = encode(_encoder, &_afio))) {
|
||||
if (_outputType == MP42AudioUnitOutputPush) {
|
||||
[_outputUnit addSample:outSample];
|
||||
}
|
||||
else {
|
||||
[_outputSamplesBuffer enqueue:outSample];
|
||||
}
|
||||
}
|
||||
|
||||
if (lastSample) {
|
||||
if (_outputType == MP42AudioUnitOutputPush) {
|
||||
[_outputUnit addSample:sampleBuffer];
|
||||
}
|
||||
else {
|
||||
[_outputSamplesBuffer enqueue:sampleBuffer];
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@end
|
||||
@@ -0,0 +1,28 @@
|
||||
//
|
||||
// MP42AudioUnit.h
|
||||
// MP42Foundation
|
||||
//
|
||||
// Created by Damiano Galassi on 24/07/2016.
|
||||
// Copyright © 2016 Damiano Galassi. All rights reserved.
|
||||
//
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
#import <AudioToolbox/AudioToolbox.h>
|
||||
|
||||
#import "MP42ConverterProtocol.h"
|
||||
|
||||
typedef NS_ENUM(NSUInteger, MP42AudioUnitOutput) {
|
||||
MP42AudioUnitOutputPush,
|
||||
MP42AudioUnitOutputPull,
|
||||
};
|
||||
|
||||
@protocol MP42AudioUnit <MP42ConverterProtocol>
|
||||
|
||||
@property (nonatomic, readwrite) MP42AudioUnitOutput outputType;
|
||||
|
||||
@property (nonatomic, readwrite, unsafe_unretained) id<MP42ConverterProtocol> outputUnit;
|
||||
|
||||
@property (nonatomic, readonly) AudioStreamBasicDescription inputFormat;
|
||||
@property (nonatomic, readonly) AudioStreamBasicDescription outputFormat;
|
||||
|
||||
@end
|
||||
@@ -8,38 +8,13 @@
|
||||
|
||||
#import <Cocoa/Cocoa.h>
|
||||
#import "MP42ConverterProtocol.h"
|
||||
#import "MP42Fifo.h"
|
||||
|
||||
#include <avcodec.h>
|
||||
|
||||
NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
@class MP42SampleBuffer;
|
||||
@class MP42SubtitleTrack;
|
||||
@class MP42OCRWrapper;
|
||||
|
||||
@interface MP42BitmapSubConverter : NSObject <MP42ConverterProtocol> {
|
||||
NSThread *decoderThread;
|
||||
NSThread *encoderThread;
|
||||
|
||||
MP42OCRWrapper *_ocr;
|
||||
CIContext *_imgContext;
|
||||
AVCodec *avCodec;
|
||||
AVCodecContext *avContext;
|
||||
|
||||
MP42Fifo<MP42SampleBuffer *> *_inputSamplesBuffer;
|
||||
MP42Fifo<MP42SampleBuffer *> *_outputSamplesBuffer;
|
||||
|
||||
UInt32 paletteG[16];
|
||||
NSData *srcMagicCookie;
|
||||
|
||||
uint8_t *codecData;
|
||||
unsigned int bufferSize;
|
||||
|
||||
int32_t _readerDone;
|
||||
int32_t _encoderDone;
|
||||
dispatch_semaphore_t _done;
|
||||
}
|
||||
@interface MP42BitmapSubConverter : NSObject <MP42ConverterProtocol>
|
||||
|
||||
- (instancetype)initWithTrack:(MP42SubtitleTrack *)track error:(NSError **)outError;
|
||||
|
||||
|
||||
@@ -26,6 +26,25 @@
|
||||
#import <QuartzCore/QuartzCore.h>
|
||||
|
||||
@interface MP42BitmapSubConverter ()
|
||||
{
|
||||
NSThread *decoderThread;
|
||||
|
||||
MP42OCRWrapper *_ocr;
|
||||
CIContext *_imgContext;
|
||||
AVCodec *avCodec;
|
||||
AVCodecContext *avContext;
|
||||
|
||||
MP42Fifo<MP42SampleBuffer *> *_inputSamplesBuffer;
|
||||
MP42Fifo<MP42SampleBuffer *> *_outputSamplesBuffer;
|
||||
|
||||
UInt32 paletteG[16];
|
||||
NSData *srcMagicCookie;
|
||||
|
||||
uint8_t *codecData;
|
||||
unsigned int bufferSize;
|
||||
|
||||
dispatch_semaphore_t _done;
|
||||
}
|
||||
|
||||
@property (nonatomic, readonly) CIContext *imgContext;
|
||||
|
||||
@@ -80,13 +99,14 @@
|
||||
- (void)VobSubDecoderThreadMainRoutine
|
||||
{
|
||||
@autoreleasepool {
|
||||
while(1) {
|
||||
MP42SampleBuffer *sampleBuffer = nil;
|
||||
|
||||
while ((sampleBuffer = [_inputSamplesBuffer dequeueAndWait])) {
|
||||
@autoreleasepool {
|
||||
MP42SampleBuffer *sampleBuffer = nil;
|
||||
|
||||
while (!(sampleBuffer = [_inputSamplesBuffer dequeueAndWait]) && !_readerDone);
|
||||
|
||||
if (!sampleBuffer) {
|
||||
if (sampleBuffer->flags & MP42SampleBufferFlagEndOfFile) {
|
||||
[_outputSamplesBuffer enqueue:sampleBuffer];
|
||||
[sampleBuffer release];
|
||||
break;
|
||||
}
|
||||
|
||||
@@ -221,26 +241,24 @@
|
||||
else {
|
||||
subSample = copyEmptySubtitleSample(sampleBuffer->trackId, sampleBuffer->duration, forced);
|
||||
}
|
||||
|
||||
|
||||
[_outputSamplesBuffer enqueue:subSample];
|
||||
[subSample release];
|
||||
|
||||
|
||||
CGImageRelease(cgImage);
|
||||
CGImageRelease(filteredCGImage);
|
||||
CGDataProviderRelease(provider);
|
||||
CFRelease(imgData);
|
||||
|
||||
|
||||
free(imageData);
|
||||
}
|
||||
|
||||
|
||||
avsubtitle_free(&subtitle);
|
||||
av_packet_unref(&pkt);
|
||||
|
||||
|
||||
[sampleBuffer release];
|
||||
}
|
||||
}
|
||||
|
||||
[self enqueueEndOfFileSample];
|
||||
dispatch_semaphore_signal(_done);
|
||||
}
|
||||
}
|
||||
@@ -248,13 +266,15 @@
|
||||
- (void)PGSDecoderThreadMainRoutine
|
||||
{
|
||||
@autoreleasepool {
|
||||
while(1) {
|
||||
MP42SampleBuffer *sampleBuffer = nil;
|
||||
|
||||
while ((sampleBuffer = [_inputSamplesBuffer dequeueAndWait])) {
|
||||
@autoreleasepool {
|
||||
MP42SampleBuffer *sampleBuffer = nil;
|
||||
|
||||
while (!(sampleBuffer = [_inputSamplesBuffer dequeueAndWait]) && !_readerDone);
|
||||
if (sampleBuffer->flags & MP42SampleBufferFlagEndOfFile) {
|
||||
[_outputSamplesBuffer enqueue:sampleBuffer];
|
||||
[sampleBuffer release];
|
||||
|
||||
if (!sampleBuffer) {
|
||||
break;
|
||||
}
|
||||
|
||||
@@ -356,10 +376,7 @@
|
||||
|
||||
[sampleBuffer release];
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
[self enqueueEndOfFileSample];
|
||||
dispatch_semaphore_signal(_done);
|
||||
}
|
||||
}
|
||||
@@ -368,11 +385,12 @@
|
||||
{
|
||||
if ((self = [super init])) {
|
||||
FFInitFFmpeg();
|
||||
NSString *format = track.sourceFormat;
|
||||
|
||||
if (([track.sourceFormat isEqualToString:MP42SubtitleFormatVobSub])) {
|
||||
if ([format isEqualToString:MP42SubtitleFormatVobSub]) {
|
||||
avCodec = avcodec_find_decoder(AV_CODEC_ID_DVD_SUBTITLE);
|
||||
}
|
||||
else if (([track.sourceFormat isEqualToString:MP42SubtitleFormatPGS])) {
|
||||
else if ([format isEqualToString:MP42SubtitleFormatPGS]) {
|
||||
avCodec = avcodec_find_decoder(AV_CODEC_ID_HDMV_PGS_SUBTITLE);
|
||||
}
|
||||
|
||||
@@ -392,26 +410,25 @@
|
||||
|
||||
_outputSamplesBuffer = [[MP42Fifo alloc] initWithCapacity:20];
|
||||
_inputSamplesBuffer = [[MP42Fifo alloc] initWithCapacity:20];
|
||||
_done = dispatch_semaphore_create(0);
|
||||
|
||||
srcMagicCookie = [[track.muxer_helper->importer magicCookieForTrack:track] retain];
|
||||
|
||||
_ocr = [[MP42OCRWrapper alloc] initWithLanguage:track.language extendedLanguageTag:track.extendedLanguageTag];
|
||||
|
||||
_done = dispatch_semaphore_create(0);
|
||||
|
||||
if (([track.sourceFormat isEqualToString:MP42SubtitleFormatVobSub])) {
|
||||
if ([format isEqualToString:MP42SubtitleFormatVobSub]) {
|
||||
// Launch the vobsub decoder thread.
|
||||
decoderThread = [[NSThread alloc] initWithTarget:self selector:@selector(VobSubDecoderThreadMainRoutine) object:nil];
|
||||
[decoderThread setName:@"VobSub Decoder"];
|
||||
[decoderThread start];
|
||||
}
|
||||
else if (([track.sourceFormat isEqualToString:MP42SubtitleFormatPGS])) {
|
||||
else if ([format isEqualToString:MP42SubtitleFormatPGS]) {
|
||||
// Launch the pgs decoder thread.
|
||||
decoderThread = [[NSThread alloc] initWithTarget:self selector:@selector(PGSDecoderThreadMainRoutine) object:nil];
|
||||
[decoderThread setName:@"PGS Decoder"];
|
||||
[decoderThread start];
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
return self;
|
||||
@@ -419,12 +436,7 @@
|
||||
|
||||
- (void)addSample:(MP42SampleBuffer *)sample
|
||||
{
|
||||
if (sample->flags & MP42SampleBufferFlagEndOfFile) {
|
||||
[self setInputDone];
|
||||
}
|
||||
else {
|
||||
[_inputSamplesBuffer enqueue:sample];
|
||||
}
|
||||
[_inputSamplesBuffer enqueue:sample];
|
||||
}
|
||||
|
||||
- (nullable MP42SampleBuffer *)copyEncodedSample
|
||||
@@ -434,30 +446,12 @@
|
||||
|
||||
- (void)cancel
|
||||
{
|
||||
_readerDone = YES;
|
||||
|
||||
[_inputSamplesBuffer cancel];
|
||||
[_outputSamplesBuffer cancel];
|
||||
|
||||
dispatch_semaphore_wait(_done, DISPATCH_TIME_FOREVER);
|
||||
}
|
||||
|
||||
- (void)setInputDone
|
||||
{
|
||||
_readerDone = YES;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends the EOF flag down the muxer chain.
|
||||
*/
|
||||
- (void)enqueueEndOfFileSample
|
||||
{
|
||||
MP42SampleBuffer *sample = [[MP42SampleBuffer alloc] init];
|
||||
sample->flags |= MP42SampleBufferFlagEndOfFile;
|
||||
[_outputSamplesBuffer enqueue:sample];
|
||||
[sample release];
|
||||
}
|
||||
|
||||
- (void)dealloc
|
||||
{
|
||||
if (avContext) {
|
||||
|
||||
@@ -1,39 +0,0 @@
|
||||
//
|
||||
// MP42ComponentLoader.h
|
||||
// MP42Foundation
|
||||
//
|
||||
// Created by Damiano Galassi on 24/07/14.
|
||||
// Copyright (c) 2014 Damiano Galassi. All rights reserved.
|
||||
//
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
|
||||
@interface MP42ComponentLoader : NSObject
|
||||
|
||||
+ (MP42ComponentLoader *)sharedLoader;
|
||||
|
||||
/**
|
||||
* Load the built-in components
|
||||
* located in Resources/Decoders .
|
||||
*/
|
||||
- (void)loadBundledComponents;
|
||||
|
||||
/**
|
||||
* Load an old style audio component.
|
||||
*/
|
||||
- (OSStatus)loadComponent:(OSType)type
|
||||
format:(OSType)format
|
||||
manufacturer:(OSType)manufactorer
|
||||
url:(NSURL *)url
|
||||
entry:(const char *)entry;
|
||||
|
||||
/**
|
||||
* Load an audio component in the 10.7+ format.
|
||||
*/
|
||||
- (OSStatus)loadAudioComponent:(OSType)type
|
||||
format:(OSType)format
|
||||
manufacturer:(OSType)manufactorer
|
||||
url:(NSURL *)url
|
||||
entry:(const char *)entry;
|
||||
|
||||
@end
|
||||
@@ -1,209 +0,0 @@
|
||||
//
|
||||
// MP42ComponentLoader.m
|
||||
// MP42Foundation
|
||||
//
|
||||
// Created by Damiano Galassi on 24/07/14.
|
||||
// Copyright (c) 2014 Damiano Galassi. All rights reserved.
|
||||
//
|
||||
|
||||
#import "MP42ComponentLoader.h"
|
||||
#import <AudioToolbox/AudioToolbox.h>
|
||||
#import <CoreAudio/CoreAudio.h>
|
||||
|
||||
#include <dlfcn.h>
|
||||
|
||||
#include <TargetConditionals.h>
|
||||
#if TARGET_RT_BIG_ENDIAN
|
||||
# define FourCC2Str(fourcc) (const char[]){*((char*)&fourcc), *(((char*)&fourcc)+1), *(((char*)&fourcc)+2), *(((char*)&fourcc)+3),0}
|
||||
#else
|
||||
# define FourCC2Str(fourcc) (const char[]){*(((char*)&fourcc)+3), *(((char*)&fourcc)+2), *(((char*)&fourcc)+1), *(((char*)&fourcc)+0),0}
|
||||
#endif
|
||||
|
||||
static NSMutableDictionary *_loadedComponents;
|
||||
|
||||
@implementation MP42ComponentLoader
|
||||
|
||||
+ (MP42ComponentLoader *)sharedLoader {
|
||||
static dispatch_once_t pred;
|
||||
static MP42ComponentLoader *sharedManager = nil;
|
||||
|
||||
dispatch_once(&pred, ^{ sharedManager = [[self alloc] init]; });
|
||||
return sharedManager;
|
||||
}
|
||||
|
||||
- (instancetype)init
|
||||
{
|
||||
self = [super init];
|
||||
if (self) {
|
||||
_loadedComponents = [[NSMutableDictionary alloc] init];
|
||||
}
|
||||
return self;
|
||||
}
|
||||
|
||||
- (void)loadBundledComponents {
|
||||
@synchronized(self) {
|
||||
NSURL *url = [[[NSBundle mainBundle] resourceURL] URLByAppendingPathComponent:@"Decoders"];
|
||||
|
||||
if (![[NSFileManager defaultManager] fileExistsAtPath:[url path] isDirectory:NULL]) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (![self componentLoadedForFormat:kAudioFormatAC3]) {
|
||||
OSStatus err = [self loadComponent:kAudioDecoderComponentType
|
||||
format:kAudioFormatAC3
|
||||
manufacturer:'cd3r'
|
||||
url:[url URLByAppendingPathComponent:@"A52Codec.component/Contents/MacOS/A52Codec"]
|
||||
entry:"ACShepA52DecoderEntry"];
|
||||
if (err) {
|
||||
NSLog(@"AC-3 Decoder not loaded");
|
||||
}
|
||||
}
|
||||
|
||||
if (![self componentLoadedForFormat:'XiVs']) {
|
||||
OSStatus err = [self loadComponent:kAudioDecoderComponentType
|
||||
format:'XiVs'
|
||||
manufacturer:'Xiph'
|
||||
url:[url URLByAppendingPathComponent:@"Perian.component/Contents/MacOS/Perian"]
|
||||
entry:"FFissionVBRDecoderEntry"];
|
||||
if (err) {
|
||||
NSLog(@"Vorbis Decoder not loaded");
|
||||
}
|
||||
}
|
||||
|
||||
if (![self componentLoadedForFormat:'XiFL']) {
|
||||
OSStatus err = [self loadComponent:kAudioDecoderComponentType
|
||||
format:'XiFL'
|
||||
manufacturer:'Xiph'
|
||||
url:[url URLByAppendingPathComponent:@"XiphQT (decoders).component/Contents/MacOS/XiphQT (decoders)"]
|
||||
entry:"CAFLACDecoderEntry"];
|
||||
if (err) {
|
||||
NSLog(@"FLAC Decoder not loaded");
|
||||
}
|
||||
}
|
||||
|
||||
if (![self componentLoadedForFormat:'DTS ']) {
|
||||
OSStatus err = [self loadComponent:kAudioDecoderComponentType
|
||||
format:'DTS '
|
||||
manufacturer:'Peri'
|
||||
url:[url URLByAppendingPathComponent:@"Perian.component/Contents/MacOS/Perian"]
|
||||
entry:"FFissionVBRDecoderEntry"];
|
||||
if (err) {
|
||||
NSLog(@"DTS Decoder not loaded");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
- (BOOL)componentLoadedForFormat:(OSType)format {
|
||||
BOOL loaded = NO;
|
||||
|
||||
if (_loadedComponents[@(FourCC2Str(format))]) {
|
||||
loaded = YES;
|
||||
} else {
|
||||
AudioComponentDescription acd = { 0 };
|
||||
acd.componentType = kAudioDecoderComponentType;
|
||||
acd.componentSubType = format;
|
||||
AudioComponent comp = NULL;
|
||||
|
||||
while((comp = AudioComponentFindNext(comp, &acd))) {
|
||||
AudioComponentDescription outDesc = { 0 };
|
||||
AudioComponentGetDescription(comp, &outDesc);
|
||||
if (outDesc.componentSubType == format) {
|
||||
loaded = YES;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return loaded;
|
||||
}
|
||||
|
||||
- (void)loadedComponents {
|
||||
AudioComponentDescription acd = { 0 };
|
||||
AudioComponent comp = NULL;
|
||||
while((comp = AudioComponentFindNext(comp, &acd))) {
|
||||
AudioComponentDescription outDesc = { 0 };
|
||||
AudioComponentGetDescription(comp, &outDesc);
|
||||
if (outDesc.componentType == kAudioDecoderComponentType) {
|
||||
NSLog(@"%s -> %s", FourCC2Str(outDesc.componentManufacturer), FourCC2Str(outDesc.componentSubType));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
- (OSStatus)loadComponent:(OSType)type
|
||||
format:(OSType)format
|
||||
manufacturer:(OSType)manufactorer
|
||||
url:(NSURL *)url
|
||||
entry:(const char *)entry
|
||||
{
|
||||
OSType err = 1;
|
||||
|
||||
if (_loadedComponents[@(FourCC2Str(format))]) {
|
||||
return noErr;
|
||||
}
|
||||
|
||||
ComponentDescription cd;
|
||||
cd.componentType = type;
|
||||
cd.componentSubType = format;
|
||||
cd.componentManufacturer = manufactorer;
|
||||
cd.componentFlags = 0;
|
||||
cd.componentFlagsMask = 0;
|
||||
ComponentResult (*ComponentRoutine) (ComponentParameters *cp, Handle componentStorage);
|
||||
void *handle = dlopen([[url path] UTF8String], RTLD_LAZY|RTLD_LOCAL);
|
||||
if (handle)
|
||||
{
|
||||
ComponentRoutine = dlsym(handle, entry);
|
||||
if (ComponentRoutine)
|
||||
{
|
||||
if (RegisterComponent(&cd, ComponentRoutine, 0, NULL, NULL, NULL)) {
|
||||
err = noErr;
|
||||
[_loadedComponents setValue:@YES forKey:@(FourCC2Str(format))];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return err;
|
||||
}
|
||||
|
||||
- (OSStatus)loadAudioComponent:(OSType)type
|
||||
format:(OSType)format
|
||||
manufacturer:(OSType)manufactorer
|
||||
url:(NSURL *)url
|
||||
entry:(const char *)entry
|
||||
{
|
||||
OSType err = 1;
|
||||
|
||||
if (_loadedComponents[@(FourCC2Str(format))]) {
|
||||
return noErr;
|
||||
}
|
||||
|
||||
// fill out the version number for the AU
|
||||
UInt32 theVersion = 0x00010000;
|
||||
|
||||
// fill out the AudioComponentDescription
|
||||
AudioComponentDescription theDescription;
|
||||
theDescription.componentType = type;
|
||||
theDescription.componentSubType = format;
|
||||
theDescription.componentManufacturer = manufactorer;
|
||||
theDescription.componentFlagsMask = 0;
|
||||
|
||||
AudioComponentPlugInInterface * (*AudioComponentFactoryFunction)(const AudioComponentDescription *inDesc);
|
||||
void *handle = dlopen([[url path] UTF8String], RTLD_LAZY|RTLD_LOCAL);
|
||||
if (handle)
|
||||
{
|
||||
AudioComponentFactoryFunction = dlsym(handle, entry);
|
||||
if (AudioComponentFactoryFunction)
|
||||
{
|
||||
if (AudioComponentRegister(&theDescription, CFSTR("My Decoder"),
|
||||
theVersion, AudioComponentFactoryFunction))
|
||||
{
|
||||
err = noErr;
|
||||
[_loadedComponents setValue:@YES forKey:@(FourCC2Str(format))];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
return err;
|
||||
}
|
||||
|
||||
@end
|
||||
+3
-3
@@ -76,9 +76,9 @@
|
||||
- (nullable id)dequeueAndWait {
|
||||
id item = [self dequeue];
|
||||
|
||||
if (!item) {
|
||||
dispatch_time_t time = dispatch_time(DISPATCH_TIME_NOW, NSEC_PER_SEC / 1000);
|
||||
dispatch_semaphore_wait(_empty, time);
|
||||
while (!item) {
|
||||
dispatch_semaphore_wait(_empty, DISPATCH_TIME_FOREVER);
|
||||
item = [self dequeue];
|
||||
}
|
||||
|
||||
return item;
|
||||
|
||||
@@ -27,7 +27,7 @@ typedef struct muxer_helper {
|
||||
|
||||
@interface MP42Track (MP42TrackMuxerExtentions)
|
||||
|
||||
@property(nonatomic, readonly, nullable) muxer_helper *muxer_helper;
|
||||
@property (nonatomic, readonly, nullable) muxer_helper *muxer_helper;
|
||||
|
||||
- (MP42SampleBuffer *)copyNextSample;
|
||||
|
||||
|
||||
@@ -31,5 +31,4 @@
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@end
|
||||
Reference in new issue
Block a user