More cosmetics

This commit is contained in:
galad87 committed 2015-08-27 18:28:54 +02:00
1 parent a074653ec1
commit f6b23874f6
27 files changed
+1018 -933

No files matched your search

+13 -5
View File
@@ -9,6 +9,7 @@
#import "MP42AACImporter.h"
#import "MP42Languages.h"
#import "MP42File.h"
#import "MP42PrivateUtilities.h"
@implementation MP42AACImporter
@@ -731,7 +732,9 @@ static bool GetFirstHeader(FILE* inFile)
u_int8_t channelConfig;
if (!GetFirstHeader(inFile)) {
//*outError = MP42Error(@"The audio could not be opened.", @"Data in file doesn't appear to be valid audio.", 100);
if (outError) {
*outError = MP42Error(@"The audio could not be opened.", @"Data in file doesn't appear to be valid audio.", 100);
}
[newTrack release];
return nil;
}
@@ -741,7 +744,9 @@ static bool GetFirstHeader(FILE* inFile)
profile = MP4AV_AdtsGetProfile(firstHeader);
if (aacProfileLevel == 2) {
if (profile > MP4_MPEG4_AAC_SSR_AUDIO_TYPE) {
//*outError = MP42Error(@"The audio could not be opened.", @"Can't convert profile to mpeg2", 100);
if (outError) {
*outError = MP42Error(@"The audio could not be opened.", @"Can't convert profile to mpeg2", 100);
}
[newTrack release];
return nil;
}
@@ -768,7 +773,9 @@ static bool GetFirstHeader(FILE* inFile)
//audioType = MP4_MPEG2_AAC_SSR_AUDIO_TYPE;
break;
case 3:
//*outError = MP42Error(@"The audio could not be opened.", @"Data in file doesn't appear to be valid audio.", 100);
if (outError) {
*outError = MP42Error(@"The audio could not be opened.", @"Data in file doesn't appear to be valid audio.", 100);
}
[newTrack release];
return nil;
default:
@@ -821,8 +828,9 @@ static bool GetFirstHeader(FILE* inFile)
- (void)demux:(id)sender
{
@autoreleasepool {
if (!inFile)
inFile = fopen([[_fileURL path] fileSystemRepresentation], "rb");
if (!inFile) {
inFile = fopen(_fileURL.path.fileSystemRepresentation, "rb");
}
MP4TrackId trackId = [[_inputTracks lastObject] sourceId];
+3 -2
View File
@@ -339,8 +339,9 @@ static bool GetFirstHeader(FILE* inFile)
- (void)demux:(id)sender
{
@autoreleasepool {
if (!inFile)
inFile = fopen([[_fileURL path] fileSystemRepresentation], "rb");
if (!inFile) {
inFile = fopen(_fileURL.path.fileSystemRepresentation, "rb");
}
MP4TrackId trackId = [[_inputTracks lastObject] sourceId];
+10 -6
View File
@@ -10,12 +10,14 @@
#include "sfifo.h"
#include "downmix.h"
#import "MP42ConverterProtocol.h"
#import "MP42Fifo.h"
#import <AudioToolbox/AudioToolbox.h>
#import <CoreAudio/CoreAudio.h>
NS_ASSUME_NONNULL_BEGIN
@class MP42SampleBuffer;
@class MP42Fifo;
@class MP42AudioTrack;
extern NSString * const SBMonoMixdown;
@@ -41,7 +43,7 @@ struct AudioFileIO
AudioStreamBasicDescription srcFormat;
AudioStreamPacketDescription *pktDescs;
MP42Fifo *inputSamplesBuffer;
MP42Fifo<MP42SampleBuffer *> *inputSamplesBuffer;
MP42SampleBuffer *sample;
int fileReaderDone;
@@ -67,8 +69,8 @@ struct AudioFileIO
NSUInteger layout;
hb_chan_map_t *ichanmap;
MP42Fifo *_inputSamplesBuffer;
MP42Fifo *_outputSamplesBuffer;
MP42Fifo<MP42SampleBuffer *> *_inputSamplesBuffer;
MP42Fifo<MP42SampleBuffer *> *_outputSamplesBuffer;
NSData * outputMagicCookie;
@@ -76,10 +78,10 @@ struct AudioFileIO
struct AudioFileIO encoderData;
}
- (instancetype)initWithTrack:(MP42AudioTrack*)track andMixdownType:(NSString *)mixdownType error:(NSError **)outError;
- (instancetype)initWithTrack:(MP42AudioTrack *)track andMixdownType:(NSString *)mixdownType error:(NSError **)outError;
- (void)addSample:(MP42SampleBuffer *)sample;
- (MP42SampleBuffer *)copyEncodedSample;
- (nullable MP42SampleBuffer *)copyEncodedSample;
- (NSData *)magicCookie;
@@ -88,4 +90,6 @@ struct AudioFileIO
- (void)setInputDone;
NS_ASSUME_NONNULL_END
@end
+197 -189
View File
@@ -31,7 +31,8 @@ OSStatus EncoderDataProc(AudioConverterRef inAudioConverter,
struct AudioFileIO *afio = (struct AudioFileIO *)inUserData;
// figure out how much to read
if (*ioNumberDataPackets > afio->numPacketsPerRead) *ioNumberDataPackets = afio->numPacketsPerRead;
if (*ioNumberDataPackets > afio->numPacketsPerRead) {
*ioNumberDataPackets = afio->numPacketsPerRead;}
// read from the fifo
UInt32 outNumBytes;
@@ -45,8 +46,9 @@ OSStatus EncoderDataProc(AudioConverterRef inAudioConverter,
return err;
}
if (*ioNumberDataPackets == 0)
printf ("End\n");
if (*ioNumberDataPackets == 0) {
printf("End\n");
}
// put the data pointer into the buffer list
@@ -59,10 +61,12 @@ OSStatus EncoderDataProc(AudioConverterRef inAudioConverter,
afio->pos += *ioNumberDataPackets;
if (outDataPacketDescription) {
if (afio->pktDescs)
if (afio->pktDescs) {
*outDataPacketDescription = afio->pktDescs;
else
}
else {
*outDataPacketDescription = NULL;
}
}
return err;
@@ -70,189 +74,186 @@ OSStatus EncoderDataProc(AudioConverterRef inAudioConverter,
- (void)EncoderThreadMainRoutine:(id)sender
{
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
@autoreleasepool {
encoderDone = NO;
OSStatus err;
encoderDone = NO;
OSStatus err;
// set up aac converter
AudioConverterRef converterEnc;
AudioStreamBasicDescription inputFormat, encoderFormat;
// 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( &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;
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");
err = AudioConverterNew( &inputFormat, &encoderFormat, &converterEnc );
if (err) {
NSLog(@"Boom encoder converter init failed");
}
int ESDSsize;
ReadESDSDescExt(cookie, &cookieBuffer, &ESDSsize, 1);
outputMagicCookie = [[NSData dataWithBytes:cookieBuffer length:ESDSsize] retain];
UInt32 tmp, tmpsiz = sizeof( tmp );
free(cookieBuffer);
free(cookie);
}
// set encoder quality to maximum
tmp = kAudioConverterQuality_Max;
AudioConverterSetProperty( converterEnc, kAudioConverterCodecQuality,
sizeof( tmp ), &tmp );
// 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);
// 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;
}
// 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;
}
free(outputBuffer);
MP42SampleBuffer *sample = [[MP42SampleBuffer alloc] init];
sample->data = malloc(fillBufList.mBuffers[0].mDataByteSize);
memcpy(sample->data, outputBuffer, fillBufList.mBuffers[0].mDataByteSize);
AudioConverterDispose(converterEnc);
sample->size = fillBufList.mBuffers[0].mDataByteSize;
sample->duration = 1024;
sample->offset = 0;
sample->timestamp = outputPos;
sample->isSync = YES;
while ([_outputSamplesBuffer isFull] && !_cancelled)
usleep(500);
[_outputSamplesBuffer enqueue:sample];
[sample release];
outputPos += ioOutputDataPackets;
encoderDone = YES;
}
free(outputBuffer);
AudioConverterDispose(converterEnc);
[pool release];
encoderDone = YES;
return;
}
@@ -267,17 +268,19 @@ OSStatus DecoderDataProc(AudioConverterRef inAudioConverter,
OSStatus err = noErr;
struct AudioFileIO *afio = inUserData;
if (afio->sample)
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 count] && !afio->fileReaderDone)
while ([afio->inputSamplesBuffer isEmpty] && !afio->fileReaderDone) {
usleep(250);
}
if (![afio->inputSamplesBuffer count] && afio->fileReaderDone) {
if ([afio->inputSamplesBuffer isEmpty] && afio->fileReaderDone) {
*ioNumberDataPackets = 0;
return err;
}
@@ -300,8 +303,9 @@ OSStatus DecoderDataProc(AudioConverterRef inAudioConverter,
afio->pktDescs->mDataByteSize = afio->sample->size;
*outDataPacketDescription = afio->pktDescs;
}
else
else {
*outDataPacketDescription = NULL;
}
}
return err;
@@ -424,8 +428,9 @@ OSStatus DecoderDataProc(AudioConverterRef inAudioConverter,
free(outputBuffer);
if (downmix)
if (downmix) {
hb_downmix_close(&downmix);
}
AudioConverterDispose(decoderData.converter);
@@ -433,7 +438,7 @@ OSStatus DecoderDataProc(AudioConverterRef inAudioConverter,
return;
}
- (instancetype)initWithTrack:(MP42AudioTrack *)track andMixdownType:(NSString *) mixdownType error:(NSError **)outError
- (instancetype)initWithTrack:(MP42AudioTrack *)track andMixdownType:(NSString *)mixdownType error:(NSError **)outError
{
if ((self = [super init])) {
OSStatus err;
@@ -451,8 +456,9 @@ OSStatus DecoderDataProc(AudioConverterRef inAudioConverter,
return nil;
}
if (outputChannelCount > inputChannelsCount)
if (outputChannelCount > inputChannelsCount) {
outputChannelCount = inputChannelsCount;
}
if ([mixdownType isEqualToString:SBMonoMixdown] && inputChannelsCount > 1) {
downmixType = HB_AMIXDOWN_MONO;
@@ -530,10 +536,12 @@ OSStatus DecoderDataProc(AudioConverterRef inAudioConverter,
}
else if ([track.sourceFormat isEqualToString:MP42AudioFormatPCM]) {
AudioStreamBasicDescription temp = [track.muxer_helper->importer audioDescriptionForTrack:track];
if (temp.mFormatID)
if (temp.mFormatID) {
inputFormat = temp;
else
}
else {
inputFormat.mFormatID = kAudioFormatLinearPCM;
}
}
}
@@ -604,15 +612,17 @@ OSStatus DecoderDataProc(AudioConverterRef inAudioConverter,
UInt32 size = sizeof(inputFormat);
err = AudioConverterGetProperty( decoderData.converter, kAudioConverterCurrentInputStreamDescription,
&size, &inputFormat);
if (err != noErr)
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)
if (err != noErr) {
NSLog(@"Boom kAudioConverterCurrentOutputStreamDescription %ld",(long)err);
}
decoderData.inputFormat = inputFormat;
decoderData.outputFormat = outputFormat;
@@ -633,9 +643,6 @@ OSStatus DecoderDataProc(AudioConverterRef inAudioConverter,
- (MP42SampleBuffer *)copyEncodedSample
{
if (![_outputSamplesBuffer count])
return nil;
return [_outputSamplesBuffer deque];
}
@@ -655,8 +662,9 @@ OSStatus DecoderDataProc(AudioConverterRef inAudioConverter,
[_inputSamplesBuffer cancel];
[_outputSamplesBuffer cancel];
while (!(readerDone && encoderDone))
while (!(readerDone && encoderDone)) {
usleep(500);
}
}
- (BOOL)encoderDone
+7 -3
View File
@@ -12,6 +12,8 @@
#include <avcodec.h>
NS_ASSUME_NONNULL_BEGIN
@class MP42SampleBuffer;
@class MP42SubtitleTrack;
@class MP42OCRWrapper;
@@ -26,8 +28,8 @@
AVCodecContext *avContext;
AVSubtitle subtitle;
MP42Fifo *_inputSamplesBuffer;
MP42Fifo *_outputSamplesBuffer;
MP42Fifo<MP42SampleBuffer *> *_inputSamplesBuffer;
MP42Fifo<MP42SampleBuffer *> *_outputSamplesBuffer;
UInt32 paletteG[16];
NSData *srcMagicCookie;
@@ -43,7 +45,7 @@
- (instancetype)initWithTrack:(MP42SubtitleTrack *)track error:(NSError **)outError;
- (void)addSample:(MP42SampleBuffer *)sample;
- (MP42SampleBuffer *)copyEncodedSample;
- (nullable MP42SampleBuffer *)copyEncodedSample;
- (void)cancel;
@@ -51,3 +53,5 @@
- (void)setInputDone;
@end
NS_ASSUME_NONNULL_END
+2 -6
View File
@@ -453,12 +453,8 @@ void FFInitFFmpeg() {
[_inputSamplesBuffer enqueue:sample];
}
- (MP42SampleBuffer *)copyEncodedSample
- (nullable MP42SampleBuffer *)copyEncodedSample
{
if (![_outputSamplesBuffer count]) {
return nil;
}
return [_outputSamplesBuffer deque];
}
@@ -479,7 +475,7 @@ void FFInitFFmpeg() {
- (BOOL)encoderDone
{
return _encoderDone;
return _encoderDone && [_outputSamplesBuffer isEmpty];
}
- (void)dealloc
+108 -109
View File
@@ -106,138 +106,137 @@ static int ParseByte(const char *string, UInt8 *byte, Boolean hex)
- (void)demux:(id)sender
{
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
MP4TrackId trackId = [[_inputTracks lastObject] sourceId];
@autoreleasepool {
MP4TrackId trackId = [[_inputTracks lastObject] sourceId];
NSString *scc = STStandardizeStringNewlines(STLoadFileWithUnknownEncoding([_fileURL path]));
if (!scc) return;
NSString *scc = STStandardizeStringNewlines(STLoadFileWithUnknownEncoding([_fileURL path]));
if (!scc) return;
NSScanner *sc = [NSScanner scannerWithString:scc];
NSString *res=nil;
[sc setCharactersToBeSkipped:nil];
NSScanner *sc = [NSScanner scannerWithString:scc];
NSString *res=nil;
[sc setCharactersToBeSkipped:nil];
[sc scanUpToString:@"\n" intoString:&res];
if (![res isEqualToString:@"Scenarist_SCC V1.0"])
return;
[sc scanUpToString:@"\n" intoString:&res];
if (![res isEqualToString:@"Scenarist_SCC V1.0"])
return;
unsigned startTime=0;
BOOL firstSample = YES;
NSString *splitLine = @"\\n+";
NSString *splitTimestamp = @"\\t+";
NSString *splitBytes = @"\\s+";
NSArray *fileArray = nil;
NSUInteger i = 0;
unsigned startTime=0;
BOOL firstSample = YES;
NSString *splitLine = @"\\n+";
NSString *splitTimestamp = @"\\t+";
NSString *splitBytes = @"\\s+";
NSArray *fileArray = nil;
NSUInteger i = 0;
fileArray = [scc componentsSeparatedByRegex:splitLine];
fileArray = [scc componentsSeparatedByRegex:splitLine];
NSMutableArray *sampleArray = [[NSMutableArray alloc] initWithCapacity:[fileArray count]];
NSMutableArray *sampleArray = [[NSMutableArray alloc] initWithCapacity:[fileArray count]];
uint64_t dropFrame = 0;
uint64_t frameDrop = 0;
uint64_t minutesDrop = 0;
uint64_t dropFrame = 0;
uint64_t frameDrop = 0;
uint64_t minutesDrop = 0;
for (NSString *line in fileArray) {
NSArray *lineArray = [line componentsSeparatedByRegex:splitTimestamp];
for (NSString *line in fileArray) {
NSArray *lineArray = [line componentsSeparatedByRegex:splitTimestamp];
if ([lineArray count] < 2)
continue;
if ([lineArray count] < 2)
continue;
startTime = ParseTimeCode([[lineArray objectAtIndex:0] UTF8String], 30000, NO, &dropFrame);
MP42TextSample *sample = [[MP42TextSample alloc] init];
sample.timestamp = startTime;
sample.title = [lineArray lastObject];
[sampleArray addObject:[sample autorelease]];
}
startTime = ParseTimeCode([[lineArray objectAtIndex:0] UTF8String], 30000, NO, &dropFrame);
MP42TextSample *sample = [[MP42TextSample alloc] init];
sample.timestamp = startTime;
sample.title = [lineArray lastObject];
for (MP42TextSample *ccSample in sampleArray) {
if (_cancelled)
break;
NSArray *bytesArray = nil;
MP4Duration sampleDuration = 0;
bytesArray = [ccSample.title componentsSeparatedByRegex:splitBytes];
NSUInteger byteCount = [bytesArray count] *2;
UInt8 *bytes = malloc(sizeof(UInt8)*byteCount*2 + (sizeof(UInt8)*8));
UInt8 *bytesPos = bytes;
// Write out the size of the atom
*(long*)bytesPos = EndianS32_NtoB(8 + byteCount);
bytesPos += sizeof(long);
// Write out the atom type
*(OSType*)bytesPos = EndianU32_NtoB('cdat');
bytesPos += sizeof(OSType);
for (NSString *hexByte in bytesArray) {
ParseByte([hexByte UTF8String], bytesPos , 1);
ParseByte([hexByte UTF8String] + 2, bytesPos + 1, 1);
bytesPos +=2;
[sampleArray addObject:[sample autorelease]];
}
if (firstSample && ccSample.timestamp != 0 && i == 0) {
MP42TextSample *boh = [sampleArray objectAtIndex:1];
sampleDuration = boh.timestamp - ccSample.timestamp;
firstSample = NO;
u_int8_t *emptyBuffer = malloc(sizeof(u_int8_t)*8);
u_int8_t empty[8] = {0,0,0,8,'c','d','a','t'};
memcpy(emptyBuffer, empty, sizeof(u_int8_t)*8);
for (MP42TextSample *ccSample in sampleArray) {
if (_cancelled)
break;
NSArray *bytesArray = nil;
MP4Duration sampleDuration = 0;
bytesArray = [ccSample.title componentsSeparatedByRegex:splitBytes];
NSUInteger byteCount = [bytesArray count] *2;
UInt8 *bytes = malloc(sizeof(UInt8)*byteCount*2 + (sizeof(UInt8)*8));
UInt8 *bytesPos = bytes;
// Write out the size of the atom
*(long*)bytesPos = EndianS32_NtoB(8 + byteCount);
bytesPos += sizeof(long);
// Write out the atom type
*(OSType*)bytesPos = EndianU32_NtoB('cdat');
bytesPos += sizeof(OSType);
for (NSString *hexByte in bytesArray) {
ParseByte([hexByte UTF8String], bytesPos , 1);
ParseByte([hexByte UTF8String] + 2, bytesPos + 1, 1);
bytesPos +=2;
}
if (firstSample && ccSample.timestamp != 0 && i == 0) {
MP42TextSample *boh = [sampleArray objectAtIndex:1];
sampleDuration = boh.timestamp - ccSample.timestamp;
firstSample = NO;
u_int8_t *emptyBuffer = malloc(sizeof(u_int8_t)*8);
u_int8_t empty[8] = {0,0,0,8,'c','d','a','t'};
memcpy(emptyBuffer, empty, sizeof(u_int8_t)*8);
MP42SampleBuffer *sample = [[MP42SampleBuffer alloc] init];
sample->data = emptyBuffer;
sample->size = 8;
sample->duration = ccSample.timestamp *= 1001;
sample->offset = 0;
sample->timestamp = 0;
sample->isSync = 1;
sample->trackId = trackId;
[self enqueue:sample];
[sample release];
frameDrop += ccSample.timestamp;
minutesDrop += frameDrop;
}
else if (i+1 < [sampleArray count]) {
MP42TextSample *boh = [sampleArray objectAtIndex:i+1];
sampleDuration = boh.timestamp - ccSample.timestamp;
frameDrop += sampleDuration;
minutesDrop += sampleDuration;
if (frameDrop >= 1800 && dropFrame) {
if (minutesDrop > 18000)
minutesDrop -= 16200;
else {
sampleDuration -= 2;
}
frameDrop -= 1800;
}
}
else
sampleDuration = 6;
MP42SampleBuffer *sample = [[MP42SampleBuffer alloc] init];
sample->data = emptyBuffer;
sample->size = 8;
sample->duration = ccSample.timestamp *= 1001;
sample->data = bytes;
sample->size = byteCount + 8;
sample->duration = sampleDuration * 1001;
sample->offset = 0;
sample->timestamp = 0;
sample->isSync = 1;
sample->trackId = trackId;
[self enqueue:sample];
[sample release];
frameDrop += ccSample.timestamp;
minutesDrop += frameDrop;
i++;
_progress = ((CGFloat)i / [sampleArray count]) * 100;
}
else if (i+1 < [sampleArray count]) {
MP42TextSample *boh = [sampleArray objectAtIndex:i+1];
sampleDuration = boh.timestamp - ccSample.timestamp;
frameDrop += sampleDuration;
minutesDrop += sampleDuration;
if (frameDrop >= 1800 && dropFrame) {
if (minutesDrop > 18000)
minutesDrop -= 16200;
else {
sampleDuration -= 2;
}
frameDrop -= 1800;
}
}
else
sampleDuration = 6;
MP42SampleBuffer *sample = [[MP42SampleBuffer alloc] init];
sample->data = bytes;
sample->size = byteCount + 8;
sample->duration = sampleDuration * 1001;
sample->offset = 0;
sample->timestamp = 0;
sample->isSync = 1;
sample->trackId = trackId;
[self enqueue:sample];
[sample release];
i++;
_progress = ((CGFloat)i / [sampleArray count]) * 100;
[sampleArray release];
[self setDone:YES];
}
[sampleArray release];
[self setDone:YES];
[pool release];
}
- (void)startReading
+1 -1
View File
@@ -18,7 +18,7 @@ NS_ASSUME_NONNULL_BEGIN
@required
- (void)addSample:(MP42SampleBuffer *)sample;
- (MP42SampleBuffer *)copyEncodedSample;
- (nullable MP42SampleBuffer *)copyEncodedSample;
- (void)cancel;
- (BOOL)encoderDone;
+1 -3
View File
@@ -27,14 +27,12 @@ NS_ASSUME_NONNULL_BEGIN
}
- (instancetype)init;
- (instancetype)initWithCapacity:(NSUInteger)numItems;
- (instancetype)initWithCapacity:(NSUInteger)numItems NS_DESIGNATED_INITIALIZER;
- (void)enqueue:(ObjectType)item;
- (nullable ObjectType)deque NS_RETURNS_RETAINED;
- (nullable ObjectType)dequeAndWait NS_RETURNS_RETAINED;
- (NSUInteger)count;
- (BOOL)isFull;
- (BOOL)isEmpty;
+9 -5
View File
@@ -20,7 +20,7 @@
if (self) {
_size = (int32_t)numItems;
_array = (id *) malloc(sizeof(id) * _size);
_full = dispatch_semaphore_create(_size);
_full = dispatch_semaphore_create(_size - 1);
_empty = dispatch_semaphore_create(0);
}
@@ -36,8 +36,9 @@
_array[_tail++] = item;
if (_tail == _size)
if (_tail == _size) {
_tail = 0;
}
OSAtomicIncrement32(&_count);
dispatch_semaphore_signal(_empty);
@@ -48,8 +49,9 @@
id item = _array[_head++];
if (_head == _size)
if (_head == _size) {
_head = 0;
}
OSAtomicDecrement32(&_count);
dispatch_semaphore_signal(_full);
@@ -81,8 +83,10 @@
}
- (void)drain {
while (![self isEmpty])
[[self deque] release];
id item;
while ((item = [self deque])) {
[item release];
}
}
- (void)cancel {
+1 -1
View File
@@ -117,7 +117,7 @@ typedef NS_ENUM(NSUInteger, MP42Status) {
*
* @return An instance of MP42File
*/
- (instancetype)initWithExistingFile:(NSURL *)URL andDelegate:(nullable id <MP42FileDelegate>)del;
- (instancetype)initWithURL:(NSURL *)URL delegate:(nullable id <MP42FileDelegate>)del;
/**
* Provides the array of MP42Tracks contained by the mp4 file
+26 -14
View File
@@ -110,7 +110,7 @@ static void logCallback(MP4LogLevel loglevel, const char *fmt, va_list ap) {
- (BOOL)startReading {
NSAssert(self.fileHandle == MP4_INVALID_FILE_HANDLE, @"File Handle already open");
_fileHandle = MP4Read([[self.URL path] fileSystemRepresentation]);
_fileHandle = MP4Read(self.URL.path.fileSystemRepresentation);
if (self.fileHandle != MP4_INVALID_FILE_HANDLE) {
self.status = MP42StatusReading;
@@ -129,7 +129,7 @@ static void logCallback(MP4LogLevel loglevel, const char *fmt, va_list ap) {
- (BOOL)startWriting {
NSAssert(self.fileHandle == MP4_INVALID_FILE_HANDLE, @"File Handle already open");
_fileHandle = MP4Modify([[self.URL path] fileSystemRepresentation], 0);
_fileHandle = MP4Modify(self.URL.path.fileSystemRepresentation, 0);
if (self.fileHandle != MP4_INVALID_FILE_HANDLE) {
self.status = MP42StatusWriting;
@@ -165,7 +165,7 @@ static void logCallback(MP4LogLevel loglevel, const char *fmt, va_list ap) {
return self;
}
- (instancetype)initWithExistingFile:(NSURL *)URL andDelegate:(id <MP42FileDelegate>)del {
- (instancetype)initWithURL:(NSURL *)URL delegate:(nullable id <MP42FileDelegate>)del {
self = [super init];
if (self) {
_delegate = del;
@@ -557,37 +557,47 @@ static void logCallback(MP4LogLevel loglevel, const char *fmt, va_list ap) {
@autoreleasepool {
NSError *error = nil;
NSFileManager *fileManager = [[NSFileManager alloc] init];
NSURL *tempURL = [self tempURL];
NSFileManager *fileManager = [[NSFileManager alloc] init];
if (tempURL) {
unsigned long long originalFileSize = [[[fileManager attributesOfItemAtPath:[self.URL path] error:nil] valueForKey:NSFileSize] unsignedLongLongValue];
NSNumber *tempValue;
[self.URL getResourceValue:&tempValue forKey:NSURLFileSizeKey error:NULL];
unsigned long long originalFileSize = tempValue.longLongValue;
dispatch_async(dispatch_get_global_queue(0, 0), ^{
noErr = MP4Optimize([[self.URL path] fileSystemRepresentation], [[tempURL path] fileSystemRepresentation]);
noErr = MP4Optimize(self.URL.path.fileSystemRepresentation, tempURL.path.fileSystemRepresentation);
done = YES;
});
// Loop to check the progress
while (!done) {
unsigned long long fileSize = [[[fileManager attributesOfItemAtPath:[tempURL path] error:nil] valueForKey:NSFileSize] unsignedLongLongValue];
[tempURL getResourceValue:&tempValue forKey:NSURLFileSizeKey error:NULL];
unsigned long long fileSize = tempValue.longLongValue;
[self progressStatus:((CGFloat)fileSize / originalFileSize) * 100];
usleep(450000);
}
// Additional check to see if we can open the optimized file
if (noErr && [[[MP42File alloc] initWithExistingFile:tempURL andDelegate:nil] autorelease]) {
if (noErr && [[[MP42File alloc] initWithURL:tempURL delegate:nil] autorelease]) {
// Replace the original file
NSURL *result = nil;
noErr = [fileManager replaceItemAtURL:self.URL withItemAtURL:tempURL backupItemName:nil options:NSFileManagerItemReplacementWithoutDeletingBackupItem resultingItemURL:&result error:&error];
noErr = [fileManager replaceItemAtURL:self.URL
withItemAtURL:tempURL
backupItemName:nil
options:NSFileManagerItemReplacementWithoutDeletingBackupItem
resultingItemURL:&result error:&error];
if (noErr) {
self.URL = result;
} else {
[_logger writeErrorToLog:error];
}
}
if (!noErr) {
// Remove the temp file if the optimization didn't complete
[fileManager removeItemAtPath:[tempURL path] error:NULL];
[fileManager removeItemAtURL:tempURL error:NULL];
}
}
@@ -613,6 +623,7 @@ static void logCallback(MP4LogLevel loglevel, const char *fmt, va_list ap) {
if (!url) {
if (outError) {
*outError = MP42Error(@"Invalid path.", @"The destination path cannot be empty.", 100);
[_logger writeErrorToLog:*outError];
}
return NO;
}
@@ -697,6 +708,7 @@ static void logCallback(MP4LogLevel loglevel, const char *fmt, va_list ap) {
success = NO;
if (outError) {
*outError = MP42Error(@"The file could not be saved.", @"You do not have sufficient permissions for this operation.", 101);
[_logger writeErrorToLog:*outError];
}
}
}
@@ -810,7 +822,7 @@ static void logCallback(MP4LogLevel loglevel, const char *fmt, va_list ap) {
// Close the mp4 file handle
if (![self stopWriting]) {
if (*outError == nil) {
if (outError) {
*outError = MP42Error(@"File excedes 4 GB.",
@"The file is bigger than 4 GB, but it was created with 32bit data chunk offset.\nSelect 64bit data chunk offset in the save panel.",
102);
@@ -820,9 +832,9 @@ static void logCallback(MP4LogLevel loglevel, const char *fmt, va_list ap) {
}
// Generate previews images for chapters
if ([[attributes valueForKey:MP42GenerateChaptersPreviewTrack] boolValue] && [self.itracks count]) {
if ([attributes[MP42GenerateChaptersPreviewTrack] boolValue] && [self.itracks count]) {
[self createChaptersPreview];
} else if ([[attributes valueForKey:MP42CustomChaptersPreviewTrack] boolValue] && [self.itracks count]) {
} else if ([attributes[MP42CustomChaptersPreviewTrack] boolValue] && [self.itracks count]) {
[self customChaptersPreview];
}
+39 -34
View File
@@ -93,6 +93,35 @@
return self;
}
- (void)dealloc
{
for (MP42Track *track in _inputTracks) {
[track.muxer_helper->demuxer_context release];
}
for (MP42Track *track in _outputsTracks) {
[track.muxer_helper->fifo release];
[track.muxer_helper->converter release];
}
[_metadata release], _metadata = nil;
[_tracksArray release], _tracksArray = nil;
[_inputTracks release], _inputTracks = nil;
[_outputsTracks release], _outputsTracks = nil;
[_fileURL release], _fileURL = nil;
[_demuxerThread release], _demuxerThread = nil;
if (_doneSem) {
dispatch_release(_doneSem);
}
[super dealloc];
}
@synthesize metadata = _metadata;
@synthesize tracks = _tracksArray;
- (NSUInteger)timescaleForTrack:(MP42Track *)track
{
return 0;
@@ -103,7 +132,7 @@
return NSMakeSize(0,0);
}
- (NSData *)magicCookieForTrack:(MP42Track *)track
- (nullable NSData *)magicCookieForTrack:(MP42Track *)track
{
return nil;
}
@@ -121,20 +150,24 @@
}
BOOL alreadyAdded = NO;
for (MP42Track *inputTrack in _inputTracks)
if (inputTrack.sourceId == track.sourceId)
for (MP42Track *inputTrack in _inputTracks) {
if (inputTrack.sourceId == track.sourceId) {
alreadyAdded = YES;
}
}
if (!alreadyAdded)
if (!alreadyAdded) {
[_inputTracks addObject:track];
}
[_outputsTracks addObject:track];
}
- (void)startReading
{
for (MP42Track *track in _outputsTracks)
for (MP42Track *track in _outputsTracks) {
track.muxer_helper->fifo = [[MP42Fifo alloc] init];
}
_doneSem = dispatch_semaphore_create(0);
}
@@ -185,7 +218,7 @@
- (BOOL)cleanUp:(MP4FileHandle)fileHandle
{
return NO;
return YES;
}
- (BOOL)containsTrack:(MP42Track *)track
@@ -204,32 +237,4 @@
return nil;
}
- (void)dealloc
{
for (MP42Track *track in _inputTracks) {
[track.muxer_helper->demuxer_context release];
}
for (MP42Track *track in _outputsTracks) {
[track.muxer_helper->fifo release];
[track.muxer_helper->converter release];
}
[_metadata release], _metadata = nil;
[_tracksArray release], _tracksArray = nil;
[_inputTracks release], _inputTracks = nil;
[_outputsTracks release], _outputsTracks = nil;
[_fileURL release], _fileURL = nil;
[_demuxerThread release], _demuxerThread = nil;
if (_doneSem)
dispatch_release(_doneSem);
[super dealloc];
}
@synthesize metadata = _metadata;
@synthesize tracks = _tracksArray;
@end
+179 -178
View File
@@ -1414,192 +1414,193 @@ NSData* H264Info(const char *filePath, uint32_t *pic_width, uint32_t *pic_height
- (void)demux:(id)sender
{
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
if (!inFile)
inFile = fopen([[_fileURL path] fileSystemRepresentation], "rb");
MP42Track *track = [_inputTracks lastObject];
MP4TrackId trackId = [track sourceId];
framerate_t * framerate;
int64_t currentSize = 0;
for (framerate = (framerate_t*) framerates; framerate->code; framerate++)
if([track sourceId] == framerate->code)
break;
timescale = framerate->timescale;
mp4FrameDuration = framerate->duration;
// the current syntactical object
// typically 1:1 with a sample
// but not always, i.e. non-VOP's
// the current sample
MP4SampleId sampleId = 1;
// track configuration info
nal_reader_t nal;
h264_decode_t h264_dec;
memset(&nal, 0, sizeof(nal));
nal.ifile = inFile;
if (timescale == 0) {
fprintf(stderr, "%s: Must specify a timescale when reading H.264 files",
ProgName);
timescale = 30000;
mp4FrameDuration = 1001;
}
rewind(nal.ifile);
nal.buffer_size = 0;
nal.buffer_on = 0;
nal.buffer_size_max = 0;
free(nal.buffer);
nal.buffer = NULL;
uint8_t *nal_buffer;
uint32_t nal_buffer_size, nal_buffer_size_max;
nal_buffer = NULL;
nal_buffer_size = 0;
nal_buffer_size_max = 0;
bool first = true;
bool nal_is_sync = false;
bool slice_is_idr = false;
int32_t poc = 0;
uint32_t dflags = 0;
// now process the rest of the video stream
memset(&h264_dec, 0, sizeof(h264_dec));
DpbInit(&h264_dpb);
while ( (LoadNal(&nal) != false) && !_cancelled) {
uint32_t header_size;
header_size = nal.buffer[2] == 1 ? 3 : 4;
bool boundary = h264_detect_boundary(nal.buffer,
nal.buffer_on,
&h264_dec);
if (boundary && first == false) {
// write the previous sample
if (nal_buffer_size != 0) {
samplesWritten++;
void* sampleData = malloc(nal_buffer_size);
memcpy(sampleData, nal_buffer, nal_buffer_size);
MP42SampleBuffer *sample = [[MP42SampleBuffer alloc] init];
sample->data = sampleData;
sample->size = nal_buffer_size;
sample->duration = mp4FrameDuration;
sample->offset = 0;
sample->timestamp = 0;
sample->isSync = nal_is_sync;
sample->trackId = trackId;
[self enqueue:sample];
[sample release];
currentSize += nal_buffer_size;
_progress = (currentSize / (CGFloat) _size) * 100;
sampleId++;
DpbAdd( &h264_dpb, poc, slice_is_idr );
nal_is_sync = false;
nal_buffer_size = 0;
}
@autoreleasepool {
if (!inFile) {
inFile = fopen([[_fileURL path] fileSystemRepresentation], "rb");
}
bool copy_nal_to_buffer = false;
if (Verbosity) {
printf("H264 type %x size %u\n",
h264_dec.nal_unit_type, nal.buffer_on);
MP42Track *track = [_inputTracks lastObject];
MP4TrackId trackId = [track sourceId];
framerate_t * framerate;
int64_t currentSize = 0;
for (framerate = (framerate_t*) framerates; framerate->code; framerate++)
if([track sourceId] == framerate->code)
break;
timescale = framerate->timescale;
mp4FrameDuration = framerate->duration;
// the current syntactical object
// typically 1:1 with a sample
// but not always, i.e. non-VOP's
// the current sample
MP4SampleId sampleId = 1;
// track configuration info
nal_reader_t nal;
h264_decode_t h264_dec;
memset(&nal, 0, sizeof(nal));
nal.ifile = inFile;
if (timescale == 0) {
fprintf(stderr, "%s: Must specify a timescale when reading H.264 files",
ProgName);
timescale = 30000;
mp4FrameDuration = 1001;
}
if (h264_nal_unit_type_is_slice(h264_dec.nal_unit_type)) {
dflags = h264_get_frame_dependency(&h264_dec);
// copy all seis, etc before indicating first
first = false;
copy_nal_to_buffer = true;
slice_is_idr = h264_dec.nal_unit_type == H264_NAL_TYPE_IDR_SLICE;
poc = h264_dec.pic_order_cnt;
nal_is_sync = h264_slice_is_idr(&h264_dec);
} else {
switch (h264_dec.nal_unit_type) {
case H264_NAL_TYPE_SEQ_PARAM:
// doesn't get added to sample buffer
// remove header
//MP4AddH264SequenceParameterSet(mp4File, trackId,
// nal.buffer + header_size,
// nal.buffer_on - header_size);
//break;
case H264_NAL_TYPE_PIC_PARAM:
// doesn't get added to sample buffer
//MP4AddH264PictureParameterSet(mp4File, trackId,
// nal.buffer + header_size,
// nal.buffer_on - header_size);
//break;
case H264_NAL_TYPE_FILLER_DATA:
// doesn't get copied
//break;
case H264_NAL_TYPE_SEI:
//copy_nal_to_buffer = remove_unused_sei_messages(&nal, header_size);
//break;
case H264_NAL_TYPE_ACCESS_UNIT:
// note - may not want to copy this - not needed
default:
copy_nal_to_buffer = true;
break;
rewind(nal.ifile);
nal.buffer_size = 0;
nal.buffer_on = 0;
nal.buffer_size_max = 0;
free(nal.buffer);
nal.buffer = NULL;
uint8_t *nal_buffer;
uint32_t nal_buffer_size, nal_buffer_size_max;
nal_buffer = NULL;
nal_buffer_size = 0;
nal_buffer_size_max = 0;
bool first = true;
bool nal_is_sync = false;
bool slice_is_idr = false;
int32_t poc = 0;
uint32_t dflags = 0;
// now process the rest of the video stream
memset(&h264_dec, 0, sizeof(h264_dec));
DpbInit(&h264_dpb);
while ( (LoadNal(&nal) != false) && !_cancelled) {
uint32_t header_size;
header_size = nal.buffer[2] == 1 ? 3 : 4;
bool boundary = h264_detect_boundary(nal.buffer,
nal.buffer_on,
&h264_dec);
if (boundary && first == false) {
// write the previous sample
if (nal_buffer_size != 0) {
samplesWritten++;
void* sampleData = malloc(nal_buffer_size);
memcpy(sampleData, nal_buffer, nal_buffer_size);
MP42SampleBuffer *sample = [[MP42SampleBuffer alloc] init];
sample->data = sampleData;
sample->size = nal_buffer_size;
sample->duration = mp4FrameDuration;
sample->offset = 0;
sample->timestamp = 0;
sample->isSync = nal_is_sync;
sample->trackId = trackId;
[self enqueue:sample];
[sample release];
currentSize += nal_buffer_size;
_progress = (currentSize / (CGFloat) _size) * 100;
sampleId++;
DpbAdd( &h264_dpb, poc, slice_is_idr );
nal_is_sync = false;
nal_buffer_size = 0;
}
}
bool copy_nal_to_buffer = false;
if (Verbosity) {
printf("H264 type %x size %u\n",
h264_dec.nal_unit_type, nal.buffer_on);
}
if (h264_nal_unit_type_is_slice(h264_dec.nal_unit_type)) {
dflags = h264_get_frame_dependency(&h264_dec);
// copy all seis, etc before indicating first
first = false;
copy_nal_to_buffer = true;
slice_is_idr = h264_dec.nal_unit_type == H264_NAL_TYPE_IDR_SLICE;
poc = h264_dec.pic_order_cnt;
nal_is_sync = h264_slice_is_idr(&h264_dec);
} else {
switch (h264_dec.nal_unit_type) {
case H264_NAL_TYPE_SEQ_PARAM:
// doesn't get added to sample buffer
// remove header
//MP4AddH264SequenceParameterSet(mp4File, trackId,
// nal.buffer + header_size,
// nal.buffer_on - header_size);
//break;
case H264_NAL_TYPE_PIC_PARAM:
// doesn't get added to sample buffer
//MP4AddH264PictureParameterSet(mp4File, trackId,
// nal.buffer + header_size,
// nal.buffer_on - header_size);
//break;
case H264_NAL_TYPE_FILLER_DATA:
// doesn't get copied
//break;
case H264_NAL_TYPE_SEI:
//copy_nal_to_buffer = remove_unused_sei_messages(&nal, header_size);
//break;
case H264_NAL_TYPE_ACCESS_UNIT:
// note - may not want to copy this - not needed
default:
copy_nal_to_buffer = true;
break;
}
}
if (copy_nal_to_buffer) {
uint32_t to_write;
to_write = nal.buffer_on - header_size;
if (to_write + 4 + nal_buffer_size > nal_buffer_size_max) {
nal_buffer_size_max += nal.buffer_on + 4;
nal_buffer = (uint8_t *)realloc(nal_buffer, nal_buffer_size_max);
}
nal_buffer[nal_buffer_size] = (to_write >> 24) & 0xff;
nal_buffer[nal_buffer_size + 1] = (to_write >> 16) & 0xff;
nal_buffer[nal_buffer_size + 2] = (to_write >> 8) & 0xff;
nal_buffer[nal_buffer_size + 3] = to_write & 0xff;
memcpy(nal_buffer + nal_buffer_size + 4,
nal.buffer + header_size,
to_write);
nal_buffer_size += to_write + 4;
}
}
if (copy_nal_to_buffer) {
uint32_t to_write;
to_write = nal.buffer_on - header_size;
if (to_write + 4 + nal_buffer_size > nal_buffer_size_max) {
nal_buffer_size_max += nal.buffer_on + 4;
nal_buffer = (uint8_t *)realloc(nal_buffer, nal_buffer_size_max);
}
nal_buffer[nal_buffer_size] = (to_write >> 24) & 0xff;
nal_buffer[nal_buffer_size + 1] = (to_write >> 16) & 0xff;
nal_buffer[nal_buffer_size + 2] = (to_write >> 8) & 0xff;
nal_buffer[nal_buffer_size + 3] = to_write & 0xff;
memcpy(nal_buffer + nal_buffer_size + 4,
nal.buffer + header_size,
to_write);
nal_buffer_size += to_write + 4;
if (nal_buffer_size != 0) {
samplesWritten++;
void *sampleData = malloc(nal_buffer_size);
memcpy(sampleData, nal_buffer, nal_buffer_size);
MP42SampleBuffer *sample = [[MP42SampleBuffer alloc] init];
sample->data = sampleData;
sample->size = nal_buffer_size;
sample->duration = mp4FrameDuration;
sample->offset = 0;
sample->timestamp = 0;
sample->isSync = nal_is_sync;
sample->trackId = trackId;
[self enqueue:sample];
[sample release];
currentSize += nal_buffer_size;
_progress = (currentSize / (CGFloat) _size) * 100;
DpbAdd(&h264_dpb, h264_dec.pic_order_cnt, slice_is_idr);
}
}
if (nal_buffer_size != 0) {
samplesWritten++;
void *sampleData = malloc(nal_buffer_size);
memcpy(sampleData, nal_buffer, nal_buffer_size);
MP42SampleBuffer *sample = [[MP42SampleBuffer alloc] init];
sample->data = sampleData;
sample->size = nal_buffer_size;
sample->duration = mp4FrameDuration;
sample->offset = 0;
sample->timestamp = 0;
sample->isSync = nal_is_sync;
sample->trackId = trackId;
[self enqueue:sample];
[sample release];
currentSize += nal_buffer_size;
_progress = (currentSize / (CGFloat) _size) * 100;
DpbAdd(&h264_dpb, h264_dec.pic_order_cnt, slice_is_idr);
DpbFlush(&h264_dpb);
free(nal_buffer);
[self setDone:YES];
}
DpbFlush(&h264_dpb);
free(nal_buffer);
[self setDone:YES];
[pool release];
}
- (BOOL)cleanUp:(MP4FileHandle)fileHandle
+3 -3
View File
@@ -14,7 +14,7 @@ NS_ASSUME_NONNULL_BEGIN
* A simple heap/priority queue implementations with a static size.
* It takes a NSComparator in input.
*/
@interface MP42Heap : NSObject {
@interface MP42Heap<ObjectType> : NSObject {
@private
id *_array;
uint64 _size;
@@ -25,8 +25,8 @@ NS_ASSUME_NONNULL_BEGIN
- (instancetype)initWithCapacity:(NSUInteger)numItems andComparator:(NSComparator)cmptr;
- (void)insert:(id)item;
- (nullable id)extract NS_RETURNS_RETAINED;
- (void)insert:(ObjectType)item;
- (nullable ObjectType)extract NS_RETURNS_RETAINED;
- (NSInteger)count;
+14 -13
View File
@@ -159,11 +159,12 @@ int readMkvPacket(struct StdIoStream *ioStream, TrackInfo *trackInfo, uint64_t
_fileURL = [fileURL retain];
_ioStream = calloc(1, sizeof(StdIoStream));
_matroskaFile= openMatroskaFile((char *)[[_fileURL path] UTF8String], _ioStream);
_matroskaFile = openMatroskaFile((char *)[[_fileURL path] UTF8String], _ioStream);
if(!_matroskaFile) {
if (outError)
if (!_matroskaFile) {
if (outError) {
*outError = MP42Error(@"The movie could not be opened.", @"The file is not a matroska file.", 100);
}
[self release];
return nil;
@@ -574,14 +575,15 @@ int readMkvPacket(struct StdIoStream *ioStream, TrackInfo *trackInfo, uint64_t
NSData *magicCookie = [NSData dataWithBytes:trackInfo->CodecPrivate length:trackInfo->CodecPrivateSize];
if (magicCookie)
if (magicCookie) {
return magicCookie;
else
}
else {
return nil;
}
}
// Methods to extract all the samples from the active tracks at the same time
- (void)demux:(id)sender
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
@@ -923,12 +925,15 @@ int readMkvPacket(struct StdIoStream *ioStream, TrackInfo *trackInfo, uint64_t
}
}
if (demuxHelper->previousSample && [track.mediaType isEqualToString:MP42MediaTypeAudio]) {
if (demuxHelper->previousSample) {
if ([track.mediaType isEqualToString:MP42MediaTypeSubtitle]) {
demuxHelper->previousSample->duration = 100;
}
[self enqueue:demuxHelper->previousSample];
[demuxHelper->previousSample release];
demuxHelper->previousSample = nil;
}
}
[self setDone:YES];
@@ -939,9 +944,6 @@ int readMkvPacket(struct StdIoStream *ioStream, TrackInfo *trackInfo, uint64_t
{
[super startReading];
if (!_matroskaFile)
return;
if (!_demuxerThread && !_done) {
_demuxerThread = [[NSThread alloc] initWithTarget:self selector:@selector(demux:) object:self];
[_demuxerThread setName:@"Matroska Demuxer"];
@@ -976,9 +978,8 @@ int readMkvPacket(struct StdIoStream *ioStream, TrackInfo *trackInfo, uint64_t
return YES;
}
- (void) dealloc
- (void)dealloc
{
/* close matroska parser */
closeMatroskaFile(_matroskaFile, _ioStream);
[super dealloc];
+105 -87
View File
@@ -35,7 +35,7 @@
if ((self = [super init])) {
_fileURL = [fileURL retain];
MP42File *sourceFile = [[MP42File alloc] initWithExistingFile:_fileURL andDelegate:self];
MP42File *sourceFile = [[MP42File alloc] initWithURL:_fileURL delegate:self];
if(!sourceFile) {
if (outError) {
@@ -46,8 +46,8 @@
return nil;
}
_tracksArray = [[sourceFile tracks] mutableCopy];
_metadata = [[sourceFile metadata] retain];
_tracksArray = [sourceFile.tracks mutableCopy];
_metadata = [sourceFile.metadata retain];
[sourceFile release];
}
@@ -57,30 +57,32 @@
- (NSUInteger)timescaleForTrack:(MP42Track *)track
{
return MP4GetTrackTimeScale(_fileHandle, [track sourceId]);
return MP4GetTrackTimeScale(_fileHandle, track.sourceId);
}
- (NSSize)sizeForTrack:(MP42Track *)track
{
MP42VideoTrack* currentTrack = (MP42VideoTrack*) track;
MP42VideoTrack *currentTrack = (MP42VideoTrack *) track;
return NSMakeSize([currentTrack width], [currentTrack height]);
}
- (NSData *)magicCookieForTrack:(MP42Track *)track
{
if (!_fileHandle)
_fileHandle = MP4Read([[_fileURL path] UTF8String]);
if (!_fileHandle) {
_fileHandle = MP4Read(_fileURL.path.fileSystemRepresentation);
}
NSData *magicCookie = nil;
MP4TrackId srcTrackId = [track sourceId];
MP4TrackId srcTrackId = track.sourceId;
const char *trackType = MP4GetTrackType(_fileHandle, srcTrackId);
const char *media_data_name = MP4GetTrackMediaDataName(_fileHandle, srcTrackId);
if (MP4_IS_AUDIO_TRACK_TYPE(trackType))
{
if (MP4_IS_AUDIO_TRACK_TYPE(trackType)){
if (!strcmp(media_data_name, "ac-3")) {
uint64_t fscod, bsid, bsmod, acmod, lfeon, bit_rate_code;
MP4GetTrackIntegerProperty(_fileHandle, srcTrackId, "mdia.minf.stbl.stsd.ac-3.dac3.fscod", &fscod);
MP4GetTrackIntegerProperty(_fileHandle, srcTrackId, "mdia.minf.stbl.stsd.ac-3.dac3.bsid", &bsid);
@@ -99,7 +101,8 @@
return [ac3Info autorelease];
} else if (!strcmp(media_data_name, "alac")) {
}
else if (!strcmp(media_data_name, "alac")) {
if (MP4HaveTrackAtom(_fileHandle, srcTrackId, "mdia.minf.stbl.stsd.alac.alac")) {
uint8_t* ppValue;
uint32_t pValueSize;
@@ -132,9 +135,10 @@
return magicCookie;
}
else if (MP4_IS_VIDEO_TRACK_TYPE(trackType))
{
else if (MP4_IS_VIDEO_TRACK_TYPE(trackType)) {
if (!strcmp(media_data_name, "avc1")) {
// Extract and rewrite some kind of avcC extradata from the mp4 file.
NSMutableData *avcCData = [[[NSMutableData alloc] init] autorelease];
@@ -214,86 +218,96 @@
- (void)demux:(id)sender
{
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
NSInteger tracksNumber = [_inputTracks count];
NSInteger tracksDone = 0;
MP4DemuxHelper *demuxHelper;
@autoreleasepool {
NSInteger tracksNumber = _inputTracks.count;
NSInteger tracksDone = 0;
MP4DemuxHelper *demuxHelper;
if (!_fileHandle)
return;
for (MP42Track *track in _inputTracks) {
track.muxer_helper->demuxer_context = [[MP4DemuxHelper alloc] init];
demuxHelper = track.muxer_helper->demuxer_context;
demuxHelper->totalSampleNumber = MP4GetTrackNumberOfSamples(_fileHandle, track.sourceId);
demuxHelper->timeScale = MP4GetTrackTimeScale(_fileHandle, track.sourceId);
demuxHelper->done = 0;
}
MP4Timestamp currentTime = 1;
MP4Duration totalDuration = MP4GetDuration(_fileHandle);
MP4Duration timescale = MP4GetTimeScale(_fileHandle);
while (tracksDone != tracksNumber) {
for (MP42Track *track in _inputTracks) {
muxer_helper *helper = track.muxer_helper;
demuxHelper = helper->demuxer_context;
while (!_cancelled && demuxHelper->currentTime < demuxHelper->timeScale * currentTime && !demuxHelper->done) {
MP4TrackId srcTrackId = [track sourceId];
uint8_t *pBytes = NULL;
uint32_t numBytes = 0;
MP4Duration duration;
MP4Duration renderingOffset;
MP4Timestamp pStartTime;
bool isSyncSample;
demuxHelper->currentSampleId = demuxHelper->currentSampleId + 1;
if (demuxHelper->currentSampleId > demuxHelper->totalSampleNumber) {
demuxHelper->done++;
tracksDone++;
break;
}
if (!MP4ReadSample(_fileHandle,
srcTrackId,
demuxHelper->currentSampleId,
&pBytes, &numBytes,
&pStartTime, &duration, &renderingOffset,
&isSyncSample)) {
demuxHelper->done++;
tracksDone++;
break;
}
MP42SampleBuffer *sample = [[MP42SampleBuffer alloc] init];
sample->data = pBytes;
sample->size = numBytes;
sample->duration = duration;
sample->offset = renderingOffset;
sample->timestamp = pStartTime;
sample->isSync = isSyncSample;
sample->trackId = track.sourceId;
[self enqueue:sample];
[sample release];
demuxHelper->currentTime = pStartTime;
}
if (!_fileHandle) {
return;
}
_progress = ((CGFloat)currentTime * timescale / totalDuration) * 100;
currentTime += 3;
}
for (MP42Track *track in _inputTracks) {
track.muxer_helper->demuxer_context = [[MP4DemuxHelper alloc] init];
demuxHelper = track.muxer_helper->demuxer_context;
demuxHelper->totalSampleNumber = MP4GetTrackNumberOfSamples(_fileHandle, track.sourceId);
demuxHelper->timeScale = MP4GetTrackTimeScale(_fileHandle, track.sourceId);
demuxHelper->done = 0;
}
[self setDone:YES];
[pool release];
MP4Timestamp currentTime = 1;
MP4Duration totalDuration = MP4GetDuration(_fileHandle);
MP4Duration timescale = MP4GetTimeScale(_fileHandle);
while (tracksDone != tracksNumber) {
if (_cancelled) {
break;
}
for (MP42Track *track in _inputTracks) {
muxer_helper *helper = track.muxer_helper;
demuxHelper = helper->demuxer_context;
if (_cancelled) {
break;
}
while (demuxHelper->currentTime < demuxHelper->timeScale * currentTime && !demuxHelper->done) {
MP4TrackId srcTrackId = [track sourceId];
uint8_t *pBytes = NULL;
uint32_t numBytes = 0;
MP4Duration duration;
MP4Duration renderingOffset;
MP4Timestamp pStartTime;
bool isSyncSample;
demuxHelper->currentSampleId = demuxHelper->currentSampleId + 1;
if (demuxHelper->currentSampleId > demuxHelper->totalSampleNumber) {
demuxHelper->done++;
tracksDone++;
break;
}
if (!MP4ReadSample(_fileHandle,
srcTrackId,
demuxHelper->currentSampleId,
&pBytes, &numBytes,
&pStartTime, &duration, &renderingOffset,
&isSyncSample)) {
demuxHelper->done++;
tracksDone++;
break;
}
MP42SampleBuffer *sample = [[MP42SampleBuffer alloc] init];
sample->data = pBytes;
sample->size = numBytes;
sample->duration = duration;
sample->offset = renderingOffset;
sample->timestamp = pStartTime;
sample->isSync = isSyncSample;
sample->trackId = track.sourceId;
[self enqueue:sample];
[sample release];
demuxHelper->currentTime = pStartTime;
}
}
_progress = ((CGFloat)currentTime * timescale / totalDuration) * 100;
currentTime += 3;
}
[self setDone:YES];
}
}
- (void)startReading
{
if (!_fileHandle)
_fileHandle = MP4Read([[_fileURL path] UTF8String]);
if (!_fileHandle) {
_fileHandle = MP4Read(_fileURL.path.fileSystemRepresentation);
}
[super startReading];
@@ -323,14 +337,17 @@
MP4AddTrackEdit(dstFileHandle, dstTrackId, i, editMediaStart, editDuration, editDwell);
i++;
}
if (trackEditCount)
if (trackEditCount) {
MP4SetTrackIntegerProperty(dstFileHandle, dstTrackId, "tkhd.duration", trackDuration);
}
else if (MP4GetSampleRenderingOffset(dstFileHandle, dstTrackId, 1)) {
uint32_t firstFrameOffset = MP4GetSampleRenderingOffset(dstFileHandle, dstTrackId, 1);
MP4Duration editDuration = MP4ConvertFromTrackDuration(_fileHandle,
srcTrackId,
MP4GetTrackDuration(_fileHandle, srcTrackId),
MP4GetTimeScale(dstFileHandle));
MP4AddTrackEdit(dstFileHandle, dstTrackId, MP4_INVALID_EDIT_ID, firstFrameOffset,
editDuration, 0);
}
@@ -341,8 +358,9 @@
- (void)dealloc
{
if (_fileHandle)
if (_fileHandle) {
MP4Close(_fileHandle, 0);
}
[super dealloc];
}
+40 -36
View File
@@ -402,29 +402,30 @@
- (void)work
{
if (![_workingTracks count]) {
if (!_workingTracks.count) {
return;
}
@autoreleasepool {
NSMutableArray<MP42FileImporter *> *trackImportersArray = [[NSMutableArray alloc] init];
NSUInteger done = 0, update = 0;
CGFloat progress = 0;
NSMutableArray<MP42FileImporter *> *trackImportersArray = [[NSMutableArray alloc] init];
NSUInteger done = 0, update = 0;
CGFloat progress = 0;
for (MP42Track *track in _workingTracks) {
if (![trackImportersArray containsObject:track.muxer_helper->importer]) {
[trackImportersArray addObject:track.muxer_helper->importer];
}
for (MP42Track *track in _workingTracks) {
if (![trackImportersArray containsObject:track.muxer_helper->importer]) {
[trackImportersArray addObject:track.muxer_helper->importer];
}
}
for (MP42FileImporter *importerHelper in trackImportersArray) {
[importerHelper startReading];
}
for (MP42FileImporter *importerHelper in trackImportersArray) {
[importerHelper startReading];
}
NSUInteger tracksImportersCount = [trackImportersArray count];
NSUInteger tracksCount = [_workingTracks count];
NSUInteger tracksImportersCount = trackImportersArray.count;
NSUInteger tracksCount = _workingTracks.count;
for (;;) {
@autoreleasepool {
for (;;) {
usleep(1000);
// Iterate the tracks array and mux the samples
@@ -435,8 +436,9 @@
if (!MP4WriteSample(_fileHandle, track.Id,
sampleBuffer->data, sampleBuffer->size,
sampleBuffer->duration, sampleBuffer->offset,
sampleBuffer->isSync))
sampleBuffer->isSync)) {
_cancelled = YES;
}
[sampleBuffer release];
}
@@ -467,27 +469,29 @@
}
update++;
}
// Write the converted audio track magic cookie
for (MP42Track *track in _workingTracks) {
if(track.muxer_helper->converter && track.needConversion && [track isMemberOfClass:[MP42AudioTrack class]]) {
NSData *magicCookie = [track.muxer_helper->converter magicCookie];
MP4SetTrackESConfiguration(_fileHandle, track.Id,
[magicCookie bytes],
[magicCookie length]);
}
}
// Stop the importers and clean ups
for (MP42FileImporter *importerHelper in trackImportersArray) {
if (_cancelled)
[importerHelper cancelReading];
else
[importerHelper cleanUp:_fileHandle];
}
[trackImportersArray release];
}
// Write the converted audio track magic cookie
for (MP42Track *track in _workingTracks) {
if(track.muxer_helper->converter && track.needConversion && [track isMemberOfClass:[MP42AudioTrack class]]) {
NSData *magicCookie = [track.muxer_helper->converter magicCookie];
MP4SetTrackESConfiguration(_fileHandle, track.Id,
[magicCookie bytes],
[magicCookie length]);
}
}
// Stop the importers and clean ups
for (MP42FileImporter *importerHelper in trackImportersArray) {
if (_cancelled) {
[importerHelper cancelReading];
}
else {
[importerHelper cleanUp:_fileHandle];
}
}
[trackImportersArray release];
}
- (void)cancel
+8
View File
@@ -11,6 +11,10 @@
#import "MP42Utilities.h"
#include "mp4v2.h"
#ifdef __cplusplus
extern "C" {
#endif
typedef enum { TRACK_DISABLED = 0x0,
TRACK_ENABLED = 0x1,
TRACK_IN_MOVIE = 0x2,
@@ -59,3 +63,7 @@ int rgb2yuv(int rgb);
void *fast_realloc_with_padding(void *ptr, unsigned int *size, unsigned int min_size);
int DecompressZlib(uint8_t **sampleData, uint32_t *sampleSize);
int DecompressBzlib(uint8_t **sampleData, uint32_t *sampleSize);
#ifdef __cplusplus
}
#endif
+116 -115
View File
@@ -24,8 +24,8 @@
@interface MP42QTImporter(Private)
-(void) movieLoaded;
-(NSString*)formatForTrack: (QTTrack *)track;
-(NSString*)langForTrack: (QTTrack *)track;
-(NSString *)formatForTrack: (QTTrack *)track;
-(NSString *)langForTrack: (QTTrack *)track;
@end
@interface MovDemuxHelper : NSObject {
@@ -47,27 +47,25 @@
if ((self = [super init])) {
_fileURL = [fileURL retain];
NSDictionary * dict = [NSDictionary dictionaryWithObjectsAndKeys:
_fileURL, QTMovieURLAttribute,
@NO, @"QTMovieOpenAsyncRequiredAttribute",
@NO, @"QTMovieOpenAsyncOKAttribute",
nil];
NSDictionary *attrs = @{@"QTMovieOpenAsyncRequiredAttribute": @NO,
@"QTMovieOpenAsyncOKAttribute": @NO};
if (dispatch_get_current_queue() != dispatch_get_main_queue()) {
dispatch_sync(dispatch_get_main_queue(), ^{
_sourceFile = [[QTMovie alloc] initWithAttributes:dict
_sourceFile = [[QTMovie alloc] initWithAttributes:attrs
error:outError];
});
}
else
_sourceFile = [[QTMovie alloc] initWithAttributes:dict
else {
_sourceFile = [[QTMovie alloc] initWithAttributes:attrs
error:outError];
}
if (_sourceFile)
if (_sourceFile) {
[self movieLoaded];
}
else {
[self release];
return nil;
}
}
@@ -75,16 +73,17 @@
return self;
}
-(void) movieLoaded
- (void)movieLoaded
{
for (QTTrack *track in [_sourceFile tracks])
if ([[track attributeForKey:QTTrackIsChapterTrackAttribute] boolValue])
for (QTTrack *track in _sourceFile.tracks) {
if ([[track attributeForKey:QTTrackIsChapterTrackAttribute] boolValue]) {
_chapterId = [[track attributeForKey:QTTrackIDAttribute] integerValue];
}
}
_tracksArray = [[NSMutableArray alloc] init];
if (NSClassFromString(@"QTMetadataItem")) //QTMetadataItem is only 10.7+
[self convertMetadata];
[self convertMetadata];
for (QTTrack *track in [_sourceFile tracks]) {
NSString* mediaType = [track attributeForKey:QTTrackMediaTypeAttribute];
@@ -828,111 +827,111 @@
- (void)demux:(id)sender
{
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
OSStatus err = noErr;
@autoreleasepool {
OSStatus err = noErr;
NSInteger tracksNumber = [_inputTracks count];
NSInteger tracksDone = 0;
NSInteger tracksNumber = [_inputTracks count];
NSInteger tracksDone = 0;
MovDemuxHelper *demuxHelper = nil;
MovDemuxHelper *demuxHelper = nil;
for (MP42Track *track in _inputTracks) {
track.muxer_helper->demuxer_context = [[MovDemuxHelper alloc] init];
for (MP42Track *track in _inputTracks) {
track.muxer_helper->demuxer_context = [[MovDemuxHelper alloc] init];
Track qtcTrack = [[_sourceFile trackWithTrackID:[track sourceId]] quickTimeTrack];
Media media = GetTrackMedia(qtcTrack);
Track qtcTrack = [[_sourceFile trackWithTrackID:[track sourceId]] quickTimeTrack];
Media media = GetTrackMedia(qtcTrack);
demuxHelper = track.muxer_helper->demuxer_context;
demuxHelper->totalSampleNumber = GetMediaSampleCount(media);
}
for (MP42Track * track in _inputTracks) {
if (_cancelled)
break;
muxer_helper *helper = track.muxer_helper;
Track qtcTrack = [[_sourceFile trackWithTrackID:[track sourceId]] quickTimeTrack];
Media media = GetTrackMedia(qtcTrack);
demuxHelper = helper->demuxer_context;
// Create a QTSampleTable which contains all the informatio of the track samples.
TimeValue64 sampleTableStartDecodeTime = 0;
QTMutableSampleTableRef sampleTable = NULL;
err = CopyMediaMutableSampleTable(media,
0,
&sampleTableStartDecodeTime,
0,
0,
&sampleTable);
require_noerr(err, bail);
TimeValue64 minDisplayOffset = 0;
err = QTSampleTableGetProperty(sampleTable,
kQTPropertyClass_SampleTable,
kQTSampleTablePropertyID_MinDisplayOffset,
sizeof(TimeValue64),
&minDisplayOffset,
NULL);
require_noerr(err, bail);
demuxHelper->minDisplayOffset = minDisplayOffset;
SInt64 sampleIndex, sampleCount;
sampleCount = QTSampleTableGetNumberOfSamples(sampleTable);
for (sampleIndex = 1; sampleIndex <= sampleCount && !_cancelled; sampleIndex++) {
TimeValue64 sampleDecodeTime = 0;
ByteCount sampleDataSize = 0;
MediaSampleFlags sampleFlags = 0;
UInt8 *sampleData = NULL;
TimeValue64 decodeDuration = QTSampleTableGetDecodeDuration(sampleTable, sampleIndex);
TimeValue64 displayOffset = QTSampleTableGetDisplayOffset(sampleTable, sampleIndex);
//uint32_t dflags = 0;
// Get the frame's data size and sample flags.
SampleNumToMediaDecodeTime( media, sampleIndex, &sampleDecodeTime, NULL);
sampleDataSize = QTSampleTableGetDataSizePerSample(sampleTable, sampleIndex);
sampleFlags = QTSampleTableGetSampleFlags(sampleTable, sampleIndex);
/*dflags |= (sampleFlags & mediaSampleHasRedundantCoding) ? MP4_SDT_HAS_REDUNDANT_CODING : 0;
dflags |= (sampleFlags & mediaSampleHasNoRedundantCoding) ? MP4_SDT_HAS_NO_REDUNDANT_CODING : 0;
dflags |= (sampleFlags & mediaSampleIsDependedOnByOthers) ? MP4_SDT_HAS_DEPENDENTS : 0;
dflags |= (sampleFlags & mediaSampleIsNotDependedOnByOthers) ? MP4_SDT_HAS_NO_DEPENDENTS : 0;
dflags |= (sampleFlags & mediaSampleDependsOnOthers) ? MP4_SDT_IS_DEPENDENT : 0;
dflags |= (sampleFlags & mediaSampleDoesNotDependOnOthers) ? MP4_SDT_IS_INDEPENDENT : 0;
dflags |= (sampleFlags & mediaSampleEarlierDisplayTimesAllowed) ? MP4_SDT_EARLIER_DISPLAY_TIMES_ALLOWED : 0;*/
// Load the frame.
sampleData = malloc(sampleDataSize);
GetMediaSample2(media, sampleData, sampleDataSize, NULL, sampleDecodeTime,
NULL, NULL, NULL, NULL, NULL, 1, NULL, NULL);
demuxHelper->currentSampleId = demuxHelper->currentSampleId + 1;
demuxHelper->currentTime = demuxHelper->currentTime + decodeDuration;
MP42SampleBuffer *sample = [[MP42SampleBuffer alloc] init];
sample->data = sampleData;
sample->size = sampleDataSize;
sample->duration = decodeDuration;
sample->offset = displayOffset -minDisplayOffset;
sample->timestamp = demuxHelper->currentTime;
sample->isSync = !(sampleFlags & mediaSampleNotSync);
sample->trackId = track.sourceId;
[self enqueue:sample];
[sample release];
_progress = ((demuxHelper->currentSampleId / (CGFloat) demuxHelper->totalSampleNumber ) * 100 / tracksNumber) +
(tracksDone / (CGFloat) tracksNumber * 100);
demuxHelper = track.muxer_helper->demuxer_context;
demuxHelper->totalSampleNumber = GetMediaSampleCount(media);
}
tracksDone++;
for (MP42Track * track in _inputTracks) {
if (_cancelled)
break;
muxer_helper *helper = track.muxer_helper;
Track qtcTrack = [[_sourceFile trackWithTrackID:[track sourceId]] quickTimeTrack];
Media media = GetTrackMedia(qtcTrack);
demuxHelper = helper->demuxer_context;
// Create a QTSampleTable which contains all the informatio of the track samples.
TimeValue64 sampleTableStartDecodeTime = 0;
QTMutableSampleTableRef sampleTable = NULL;
err = CopyMediaMutableSampleTable(media,
0,
&sampleTableStartDecodeTime,
0,
0,
&sampleTable);
require_noerr(err, bail);
TimeValue64 minDisplayOffset = 0;
err = QTSampleTableGetProperty(sampleTable,
kQTPropertyClass_SampleTable,
kQTSampleTablePropertyID_MinDisplayOffset,
sizeof(TimeValue64),
&minDisplayOffset,
NULL);
require_noerr(err, bail);
demuxHelper->minDisplayOffset = minDisplayOffset;
SInt64 sampleIndex, sampleCount;
sampleCount = QTSampleTableGetNumberOfSamples(sampleTable);
for (sampleIndex = 1; sampleIndex <= sampleCount && !_cancelled; sampleIndex++) {
TimeValue64 sampleDecodeTime = 0;
ByteCount sampleDataSize = 0;
MediaSampleFlags sampleFlags = 0;
UInt8 *sampleData = NULL;
TimeValue64 decodeDuration = QTSampleTableGetDecodeDuration(sampleTable, sampleIndex);
TimeValue64 displayOffset = QTSampleTableGetDisplayOffset(sampleTable, sampleIndex);
//uint32_t dflags = 0;
// Get the frame's data size and sample flags.
SampleNumToMediaDecodeTime( media, sampleIndex, &sampleDecodeTime, NULL);
sampleDataSize = QTSampleTableGetDataSizePerSample(sampleTable, sampleIndex);
sampleFlags = QTSampleTableGetSampleFlags(sampleTable, sampleIndex);
/*dflags |= (sampleFlags & mediaSampleHasRedundantCoding) ? MP4_SDT_HAS_REDUNDANT_CODING : 0;
dflags |= (sampleFlags & mediaSampleHasNoRedundantCoding) ? MP4_SDT_HAS_NO_REDUNDANT_CODING : 0;
dflags |= (sampleFlags & mediaSampleIsDependedOnByOthers) ? MP4_SDT_HAS_DEPENDENTS : 0;
dflags |= (sampleFlags & mediaSampleIsNotDependedOnByOthers) ? MP4_SDT_HAS_NO_DEPENDENTS : 0;
dflags |= (sampleFlags & mediaSampleDependsOnOthers) ? MP4_SDT_IS_DEPENDENT : 0;
dflags |= (sampleFlags & mediaSampleDoesNotDependOnOthers) ? MP4_SDT_IS_INDEPENDENT : 0;
dflags |= (sampleFlags & mediaSampleEarlierDisplayTimesAllowed) ? MP4_SDT_EARLIER_DISPLAY_TIMES_ALLOWED : 0;*/
// Load the frame.
sampleData = malloc(sampleDataSize);
GetMediaSample2(media, sampleData, sampleDataSize, NULL, sampleDecodeTime,
NULL, NULL, NULL, NULL, NULL, 1, NULL, NULL);
demuxHelper->currentSampleId = demuxHelper->currentSampleId + 1;
demuxHelper->currentTime = demuxHelper->currentTime + decodeDuration;
MP42SampleBuffer *sample = [[MP42SampleBuffer alloc] init];
sample->data = sampleData;
sample->size = sampleDataSize;
sample->duration = decodeDuration;
sample->offset = displayOffset -minDisplayOffset;
sample->timestamp = demuxHelper->currentTime;
sample->isSync = !(sampleFlags & mediaSampleNotSync);
sample->trackId = track.sourceId;
[self enqueue:sample];
[sample release];
_progress = ((demuxHelper->currentSampleId / (CGFloat) demuxHelper->totalSampleNumber ) * 100 / tracksNumber) +
(tracksDone / (CGFloat) tracksNumber * 100);
}
tracksDone++;
bail:
QTSampleTableRelease(sampleTable);
QTSampleTableRelease(sampleTable);
}
[self setDone:YES];
}
[self setDone:YES];
[pool release];
}
- (void)startReading
@@ -973,12 +972,14 @@
editTrackDuration = (editTrackDuration / (double)GetMovieTimeScale([_sourceFile quickTimeMovie])) * MP4GetTimeScale(fileHandle);
editDwell = GetTrackEditRate64(qtcTrack, editTrackStart);
if (demuxHelper->minDisplayOffset < 0 && editDisplayStart != -1)
if (demuxHelper->minDisplayOffset < 0 && editDisplayStart != -1) {
MP4AddTrackEdit(fileHandle, track.Id, MP4_INVALID_EDIT_ID, editDisplayStart - demuxHelper->minDisplayOffset,
editTrackDuration, !Fix2X(editDwell));
else
}
else {
MP4AddTrackEdit(fileHandle, track.Id, MP4_INVALID_EDIT_ID, editDisplayStart,
editTrackDuration, !Fix2X(editDwell));
}
trackDuration += editTrackDuration;
// Find the next edit
@@ -996,7 +997,7 @@
return YES;
}
- (void) dealloc
- (void)dealloc
{
[_sourceFile release];
+5
View File
@@ -10,6 +10,10 @@
@class MP42Track;
typedef NS_OPTIONS(NSUInteger, MP42SampleBufferFlag) {
MP42SampleBufferFlagEndOfFile = 1 << 0,
};
@interface MP42SampleBuffer : NSObject {
@public
void *data;
@@ -28,6 +32,7 @@
BOOL isForced;
void *attachments;
uint16_t flags;
}
@end
+26 -24
View File
@@ -91,8 +91,9 @@
[newTrack setDuration:duration];
if (!success) {
if (outError)
if (outError) {
*outError = MP42Error(@"The file could not be opened.", @"The file is not a srt file, or it does not contain any subtitles.", 100);
}
[newTrack release];
[self release];
@@ -106,8 +107,9 @@
newTrack.verticalPlacement = YES;
_verticalPlacement = YES;
}
if ([_ss forced])
if ([_ss forced]) {
newTrack.someSamplesAreForced = YES;
}
[_tracksArray addObject:newTrack];
[newTrack release];
@@ -128,34 +130,34 @@
- (void)demux:(id)sender
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
MP42SampleBuffer *sample;
@autoreleasepool {
MP42SampleBuffer *sample;
for (MP42SubtitleTrack *track in _inputTracks) {
CGSize trackSize;
trackSize.width = track.trackWidth;
trackSize.height = track.trackHeight;
for (MP42SubtitleTrack *track in _inputTracks) {
CGSize trackSize;
trackSize.width = track.trackWidth;
trackSize.height = track.trackHeight;
while (![_ss isEmpty] && !_cancelled) {
SBSubLine *sl = [_ss getSerializedPacket];
while (![_ss isEmpty] && !_cancelled) {
SBSubLine *sl = [_ss getSerializedPacket];
if ([sl->line isEqualToString:@"\n"]) {
sample = copyEmptySubtitleSample(track.sourceId, sl->end_time - sl->begin_time, NO);
if ([sl->line isEqualToString:@"\n"]) {
sample = copyEmptySubtitleSample(track.sourceId, sl->end_time - sl->begin_time, NO);
}
else {
int top = (sl->top == INT_MAX) ? trackSize.height : sl->top;
sample = copySubtitleSample(track.sourceId, sl->line, sl->end_time - sl->begin_time, sl->forced, _verticalPlacement, YES, trackSize, top);
}
[self enqueue:sample];
[sample release];
}
else {
int top = (sl->top == INT_MAX) ? trackSize.height : sl->top;
sample = copySubtitleSample(track.sourceId, sl->line, sl->end_time - sl->begin_time, sl->forced, _verticalPlacement, YES, trackSize, top);
}
[self enqueue:sample];
[sample release];
}
_progress = 100.0;
[self setDone:YES];
}
_progress = 100.0;
[self setDone:YES];
[pool release];
}
- (void)startReading
+1 -1
View File
@@ -386,7 +386,7 @@ static int ParseForced(NSString *str)
int LoadSRTFromPath(NSString *path, SBSubSerializer *ss, MP4Duration *duration)
{
NSMutableString *srt = STStandardizeStringNewlines(STLoadFileWithUnknownEncoding(path));
if (!srt) return 0;
if (!srt.length) return 0;
if ([srt characterAtIndex:0] == 0xFEFF) [srt deleteCharactersInRange:NSMakeRange(0,1)];
if ([srt characterAtIndex:[srt length]-1] != '\n') [srt appendFormat:@"%c",'\n'];
+1 -1
View File
@@ -222,7 +222,7 @@ static void insertTagsFromStyleRecord(style_record record, NSMutableString *samp
- (BOOL)exportToURL:(NSURL *)url error:(NSError **)error
{
MP4FileHandle fileHandle = MP4Read([[_sourceURL path] UTF8String]);
MP4FileHandle fileHandle = MP4Read(_sourceURL.path.fileSystemRepresentation);
if (!fileHandle)
return NO;
+1 -1
View File
@@ -20,7 +20,7 @@ typedef struct muxer_helper {
// Output helpers
id <MP42ConverterProtocol> converter;
MP42Fifo *fifo;
MP42Fifo<MP42SampleBuffer *> *fifo;
BOOL done;
} muxer_helper;
+14 -10
View File
@@ -12,8 +12,9 @@
- (muxer_helper *)muxer_helper
{
if (_helper == NULL)
if (_helper == NULL) {
_helper = calloc(1, sizeof(muxer_helper));
}
return _helper;
}
@@ -23,21 +24,24 @@
muxer_helper *helper = (muxer_helper *)_helper;
if (helper->converter) {
if ([helper->importer done])
if ([helper->importer done]) {
[helper->converter setInputDone];
}
if ([helper->converter encoderDone])
if ([helper->converter encoderDone]) {
helper->done = YES;
}
sample = [helper->converter copyEncodedSample];
} else {
if ([helper->fifo isEmpty] && [helper->importer done])
helper->done = YES;
if ([helper->fifo count])
sample = [helper->fifo deque];
}
else {
if ([helper->fifo isEmpty] && [helper->importer done]) {
helper->done = YES;
}
sample = [helper->fifo deque];
}
return sample;
}
+88 -86
View File
@@ -119,7 +119,7 @@ static NSString *getNextVobSubLine(NSEnumerator *lineEnum)
return line;
}
static NSArray* LoadVobSubSubtitles(NSURL *theDirectory, NSString *filename)
static NSArray<SBVobSubTrack *> * LoadVobSubSubtitles(NSURL *theDirectory, NSString *filename)
{
@autoreleasepool {
NSString *nsPath = [[theDirectory path] stringByAppendingPathComponent:filename];
@@ -144,7 +144,7 @@ static NSArray* LoadVobSubSubtitles(NSURL *theDirectory, NSString *filename)
NSEnumerator *lineEnum = [lines objectEnumerator];
NSString *line;
NSMutableArray *tracks = [NSMutableArray array];
NSMutableArray<SBVobSubTrack *> *tracks = [NSMutableArray array];
while((line = getNextVobSubLine(lineEnum)) != NULL)
{
@@ -225,8 +225,8 @@ static NSArray* LoadVobSubSubtitles(NSURL *theDirectory, NSString *filename)
NSInteger count = 0;
_fileURL = [fileURL retain];
_VobSubTracks = LoadVobSubSubtitles([_fileURL URLByDeletingLastPathComponent], [_fileURL lastPathComponent]);
_tracksArray = [[NSMutableArray alloc] initWithCapacity:[_VobSubTracks count]];
_VobSubTracks = LoadVobSubSubtitles(_fileURL.URLByDeletingLastPathComponent, _fileURL.lastPathComponent);
_tracksArray = [[NSMutableArray alloc] initWithCapacity:_VobSubTracks.count];
for (SBVobSubTrack *track in _VobSubTracks) {
MP42SubtitleTrack *newTrack = [[MP42SubtitleTrack alloc] init];
@@ -242,9 +242,10 @@ static NSArray* LoadVobSubSubtitles(NSURL *theDirectory, NSString *filename)
[newTrack release];
}
if (![_tracksArray count]) {
if (outError)
if (!_tracksArray.count) {
if (outError) {
*outError = MP42Error(@"The file could not be opened.", @"The file is not a idx file, or it does not contain any subtitles.", 100);
}
[self release];
return nil;
@@ -290,70 +291,84 @@ static NSArray* LoadVobSubSubtitles(NSURL *theDirectory, NSString *filename)
- (void)demux:(id)sender
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSURL *subFileURL = [[_fileURL URLByDeletingPathExtension] URLByAppendingPathExtension:@"sub"];
@autoreleasepool {
NSData *subFileData = [NSData dataWithContentsOfURL:subFileURL];
NSURL *subFileURL = [[_fileURL URLByDeletingPathExtension] URLByAppendingPathExtension:@"sub"];
NSInteger tracksNumber = [_inputTracks count];
NSInteger tracksDone = 0;
NSData *subFileData = [NSData dataWithContentsOfURL:subFileURL];
NSInteger tracksNumber = [_inputTracks count];
NSInteger tracksDone = 0;
for (MP42Track *track in _inputTracks) {
SBVobSubTrack *vobTrack = [_VobSubTracks objectAtIndex:track.sourceId];
SBVobSubSample *firstSample = nil;
uint32_t lastTime = 0;
int i, sampleCount = [vobTrack->samples count];
for (i = 0; i < sampleCount && !_cancelled; i++) {
SBVobSubSample *currentSample = [vobTrack->samples objectAtIndex:i];
int offset = currentSample->fileOffset;
int nextOffset;
if (i == sampleCount - 1)
nextOffset = [subFileData length];
else
nextOffset = ((SBVobSubSample *)[vobTrack->samples objectAtIndex:i+1])->fileOffset;
int size = nextOffset - offset;
if (size < 0)
//Skip samples for which we cannot determine size
continue;
NSData *subData = [subFileData subdataWithRange:NSMakeRange(offset, size)];
uint8_t *extracted = (uint8_t *)malloc(size);
//The index here likely should really be track->index, but I'm not sure we can really trust it.
int extractedSize = ExtractVobSubPacket(extracted, (UInt8 *)[subData bytes], size, &size, -1);
uint16_t startTimestamp, endTimestamp;
uint8_t forced;
if (!ReadPacketTimes(extracted, extractedSize, &startTimestamp, &endTimestamp, &forced)) {
free(extracted);
continue;
}
uint32_t startTime = currentSample->timeStamp + startTimestamp;
uint32_t endTime = currentSample->timeStamp + endTimestamp;
int duration = endTimestamp - startTimestamp;
if (duration <= 0 && i < sampleCount - 1) {
//Sample with no end duration, use the duration of the next one
endTime = ((SBVobSubSample *)[vobTrack->samples objectAtIndex:i+1])->timeStamp;
duration = endTime - startTime;
}
if (duration <= 0) {
//Skip samples which are broken
free(extracted);
continue;
}
if (firstSample == nil) {
currentSample->timeStamp = startTime;
firstSample = currentSample;
}
if (lastTime != startTime) {
//insert a sample with no real data, to clear the subs
MP42SampleBuffer *sample = [[MP42SampleBuffer alloc] init];
sample->size = 2;
sample->data = calloc(1, 2);
sample->duration = startTime - lastTime;
sample->offset = 0;
sample->timestamp = startTime;
sample->isSync = YES;
sample->trackId = track.sourceId;
[self enqueue:sample];
[sample release];
}
for (MP42Track *track in _inputTracks) {
SBVobSubTrack *vobTrack = [_VobSubTracks objectAtIndex:track.sourceId];
SBVobSubSample *firstSample = nil;
uint32_t lastTime = 0;
int i, sampleCount = [vobTrack->samples count];
for (i = 0; i < sampleCount && !_cancelled; i++) {
SBVobSubSample *currentSample = [vobTrack->samples objectAtIndex:i];
int offset = currentSample->fileOffset;
int nextOffset;
if (i == sampleCount - 1)
nextOffset = [subFileData length];
else
nextOffset = ((SBVobSubSample *)[vobTrack->samples objectAtIndex:i+1])->fileOffset;
int size = nextOffset - offset;
if (size < 0)
//Skip samples for which we cannot determine size
continue;
NSData *subData = [subFileData subdataWithRange:NSMakeRange(offset, size)];
uint8_t *extracted = (uint8_t *)malloc(size);
//The index here likely should really be track->index, but I'm not sure we can really trust it.
int extractedSize = ExtractVobSubPacket(extracted, (UInt8 *)[subData bytes], size, &size, -1);
uint16_t startTimestamp, endTimestamp;
uint8_t forced;
if (!ReadPacketTimes(extracted, extractedSize, &startTimestamp, &endTimestamp, &forced)) {
free(extracted);
continue;
}
uint32_t startTime = currentSample->timeStamp + startTimestamp;
uint32_t endTime = currentSample->timeStamp + endTimestamp;
int duration = endTimestamp - startTimestamp;
if (duration <= 0 && i < sampleCount - 1) {
//Sample with no end duration, use the duration of the next one
endTime = ((SBVobSubSample *)[vobTrack->samples objectAtIndex:i+1])->timeStamp;
duration = endTime - startTime;
}
if (duration <= 0) {
//Skip samples which are broken
free(extracted);
continue;
}
if (firstSample == nil) {
currentSample->timeStamp = startTime;
firstSample = currentSample;
}
if (lastTime != startTime) {
//insert a sample with no real data, to clear the subs
MP42SampleBuffer *sample = [[MP42SampleBuffer alloc] init];
sample->size = 2;
sample->data = calloc(1, 2);
sample->duration = startTime - lastTime;
sample->data = extracted;
sample->size = size;
sample->duration = duration;
sample->offset = 0;
sample->timestamp = startTime;
sample->isSync = YES;
@@ -361,29 +376,16 @@ static NSArray* LoadVobSubSubtitles(NSURL *theDirectory, NSString *filename)
[self enqueue:sample];
[sample release];
lastTime = endTime;
_progress = ((i / (CGFloat) sampleCount ) * 100 / tracksNumber) + (tracksDone / (CGFloat) tracksNumber * 100);
}
MP42SampleBuffer *sample = [[MP42SampleBuffer alloc] init];
sample->data = extracted;
sample->size = size;
sample->duration = duration;
sample->offset = 0;
sample->timestamp = startTime;
sample->isSync = YES;
sample->trackId = track.sourceId;
[self enqueue:sample];
[sample release];
lastTime = endTime;
_progress = ((i / (CGFloat) sampleCount ) * 100 / tracksNumber) + (tracksDone / (CGFloat) tracksNumber * 100);
tracksDone++;
}
tracksDone++;
[self setDone:YES];
}
[self setDone:YES];
[pool release];
}
- (void)startReading