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
+982 -897

No files matched your search

+13 -5
View File
@@ -9,6 +9,7 @@
#import "MP42AACImporter.h" #import "MP42AACImporter.h"
#import "MP42Languages.h" #import "MP42Languages.h"
#import "MP42File.h" #import "MP42File.h"
#import "MP42PrivateUtilities.h"
@implementation MP42AACImporter @implementation MP42AACImporter
@@ -731,7 +732,9 @@ static bool GetFirstHeader(FILE* inFile)
u_int8_t channelConfig; u_int8_t channelConfig;
if (!GetFirstHeader(inFile)) { 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]; [newTrack release];
return nil; return nil;
} }
@@ -741,7 +744,9 @@ static bool GetFirstHeader(FILE* inFile)
profile = MP4AV_AdtsGetProfile(firstHeader); profile = MP4AV_AdtsGetProfile(firstHeader);
if (aacProfileLevel == 2) { if (aacProfileLevel == 2) {
if (profile > MP4_MPEG4_AAC_SSR_AUDIO_TYPE) { 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]; [newTrack release];
return nil; return nil;
} }
@@ -768,7 +773,9 @@ static bool GetFirstHeader(FILE* inFile)
//audioType = MP4_MPEG2_AAC_SSR_AUDIO_TYPE; //audioType = MP4_MPEG2_AAC_SSR_AUDIO_TYPE;
break; break;
case 3: 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]; [newTrack release];
return nil; return nil;
default: default:
@@ -821,8 +828,9 @@ static bool GetFirstHeader(FILE* inFile)
- (void)demux:(id)sender - (void)demux:(id)sender
{ {
@autoreleasepool { @autoreleasepool {
if (!inFile) if (!inFile) {
inFile = fopen([[_fileURL path] fileSystemRepresentation], "rb"); inFile = fopen(_fileURL.path.fileSystemRepresentation, "rb");
}
MP4TrackId trackId = [[_inputTracks lastObject] sourceId]; MP4TrackId trackId = [[_inputTracks lastObject] sourceId];
+3 -2
View File
@@ -339,8 +339,9 @@ static bool GetFirstHeader(FILE* inFile)
- (void)demux:(id)sender - (void)demux:(id)sender
{ {
@autoreleasepool { @autoreleasepool {
if (!inFile) if (!inFile) {
inFile = fopen([[_fileURL path] fileSystemRepresentation], "rb"); inFile = fopen(_fileURL.path.fileSystemRepresentation, "rb");
}
MP4TrackId trackId = [[_inputTracks lastObject] sourceId]; MP4TrackId trackId = [[_inputTracks lastObject] sourceId];
+10 -6
View File
@@ -10,12 +10,14 @@
#include "sfifo.h" #include "sfifo.h"
#include "downmix.h" #include "downmix.h"
#import "MP42ConverterProtocol.h" #import "MP42ConverterProtocol.h"
#import "MP42Fifo.h"
#import <AudioToolbox/AudioToolbox.h> #import <AudioToolbox/AudioToolbox.h>
#import <CoreAudio/CoreAudio.h> #import <CoreAudio/CoreAudio.h>
NS_ASSUME_NONNULL_BEGIN
@class MP42SampleBuffer; @class MP42SampleBuffer;
@class MP42Fifo;
@class MP42AudioTrack; @class MP42AudioTrack;
extern NSString * const SBMonoMixdown; extern NSString * const SBMonoMixdown;
@@ -41,7 +43,7 @@ struct AudioFileIO
AudioStreamBasicDescription srcFormat; AudioStreamBasicDescription srcFormat;
AudioStreamPacketDescription *pktDescs; AudioStreamPacketDescription *pktDescs;
MP42Fifo *inputSamplesBuffer; MP42Fifo<MP42SampleBuffer *> *inputSamplesBuffer;
MP42SampleBuffer *sample; MP42SampleBuffer *sample;
int fileReaderDone; int fileReaderDone;
@@ -67,8 +69,8 @@ struct AudioFileIO
NSUInteger layout; NSUInteger layout;
hb_chan_map_t *ichanmap; hb_chan_map_t *ichanmap;
MP42Fifo *_inputSamplesBuffer; MP42Fifo<MP42SampleBuffer *> *_inputSamplesBuffer;
MP42Fifo *_outputSamplesBuffer; MP42Fifo<MP42SampleBuffer *> *_outputSamplesBuffer;
NSData * outputMagicCookie; NSData * outputMagicCookie;
@@ -76,10 +78,10 @@ struct AudioFileIO
struct AudioFileIO encoderData; 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; - (void)addSample:(MP42SampleBuffer *)sample;
- (MP42SampleBuffer *)copyEncodedSample; - (nullable MP42SampleBuffer *)copyEncodedSample;
- (NSData *)magicCookie; - (NSData *)magicCookie;
@@ -88,4 +90,6 @@ struct AudioFileIO
- (void)setInputDone; - (void)setInputDone;
NS_ASSUME_NONNULL_END
@end @end
+190 -182
View File
@@ -31,7 +31,8 @@ OSStatus EncoderDataProc(AudioConverterRef inAudioConverter,
struct AudioFileIO *afio = (struct AudioFileIO *)inUserData; struct AudioFileIO *afio = (struct AudioFileIO *)inUserData;
// figure out how much to read // figure out how much to read
if (*ioNumberDataPackets > afio->numPacketsPerRead) *ioNumberDataPackets = afio->numPacketsPerRead; if (*ioNumberDataPackets > afio->numPacketsPerRead) {
*ioNumberDataPackets = afio->numPacketsPerRead;}
// read from the fifo // read from the fifo
UInt32 outNumBytes; UInt32 outNumBytes;
@@ -45,8 +46,9 @@ OSStatus EncoderDataProc(AudioConverterRef inAudioConverter,
return err; return err;
} }
if (*ioNumberDataPackets == 0) if (*ioNumberDataPackets == 0) {
printf ("End\n"); printf("End\n");
}
// put the data pointer into the buffer list // put the data pointer into the buffer list
@@ -59,10 +61,12 @@ OSStatus EncoderDataProc(AudioConverterRef inAudioConverter,
afio->pos += *ioNumberDataPackets; afio->pos += *ioNumberDataPackets;
if (outDataPacketDescription) { if (outDataPacketDescription) {
if (afio->pktDescs) if (afio->pktDescs) {
*outDataPacketDescription = afio->pktDescs; *outDataPacketDescription = afio->pktDescs;
else }
else {
*outDataPacketDescription = NULL; *outDataPacketDescription = NULL;
}
} }
return err; return err;
@@ -70,189 +74,186 @@ OSStatus EncoderDataProc(AudioConverterRef inAudioConverter,
- (void)EncoderThreadMainRoutine:(id)sender - (void)EncoderThreadMainRoutine:(id)sender
{ {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; @autoreleasepool {
encoderDone = NO;
OSStatus err;
encoderDone = NO; // set up aac converter
OSStatus err; AudioConverterRef converterEnc;
AudioStreamBasicDescription inputFormat, encoderFormat;
// set up aac converter bzero( &inputFormat, sizeof( AudioStreamBasicDescription ) );
AudioConverterRef converterEnc; inputFormat.mSampleRate = sampleRate;
AudioStreamBasicDescription inputFormat, encoderFormat; 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 ) ); bzero( &encoderFormat, sizeof( AudioStreamBasicDescription ) );
inputFormat.mSampleRate = sampleRate; encoderFormat.mFormatID = kAudioFormatMPEG4AAC;
inputFormat.mFormatID = kAudioFormatLinearPCM ; encoderFormat.mSampleRate = ( Float64 ) inputFormat.mSampleRate;
inputFormat.mFormatFlags = kLinearPCMFormatFlagIsFloat | kAudioFormatFlagsNativeEndian; encoderFormat.mChannelsPerFrame = inputFormat.mChannelsPerFrame;
inputFormat.mBytesPerPacket = 4 * outputChannelCount;
inputFormat.mFramesPerPacket = 1;
inputFormat.mBytesPerFrame = inputFormat.mBytesPerPacket * inputFormat.mFramesPerPacket;
inputFormat.mChannelsPerFrame = outputChannelCount;
inputFormat.mBitsPerChannel = 32;
bzero( &encoderFormat, sizeof( AudioStreamBasicDescription ) ); err = AudioConverterNew( &inputFormat, &encoderFormat, &converterEnc );
encoderFormat.mFormatID = kAudioFormatMPEG4AAC; if (err) {
encoderFormat.mSampleRate = ( Float64 ) inputFormat.mSampleRate; NSLog(@"Boom encoder converter init failed");
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; UInt32 tmp, tmpsiz = sizeof( tmp );
ReadESDSDescExt(cookie, &cookieBuffer, &ESDSsize, 1);
outputMagicCookie = [[NSData dataWithBytes:cookieBuffer length:ESDSsize] retain];
free(cookieBuffer); // set encoder quality to maximum
free(cookie); tmp = kAudioConverterQuality_Max;
} AudioConverterSetProperty( converterEnc, kAudioConverterCodecQuality,
sizeof( tmp ), &tmp );
// loop to convert data // set encoder bitrate control mode to constrained variable
SInt64 outputPos = 0; tmp = kAudioCodecBitRateControlMode_VariableConstrained;
AudioConverterSetProperty( converterEnc, kAudioCodecPropertyBitRateControlMode,
sizeof( tmp ), &tmp );
while (1) { // set bitrate
AudioStreamPacketDescription odesc = {0, 0, 0}; UInt32 bitrate = (UInt32)[[[NSUserDefaults standardUserDefaults] valueForKey:@"SBAudioBitrate"] integerValue];
if (!bitrate) bitrate = 80;
// set up output buffer list // get available bitrates
AudioBufferList fillBufList; AudioValueRange *bitrates;
fillBufList.mNumberBuffers = 1; ssize_t bitrateCounts;
fillBufList.mBuffers[0].mNumberChannels = inputFormat.mChannelsPerFrame; err = AudioConverterGetPropertyInfo( converterEnc, kAudioConverterApplicableEncodeBitRates,
fillBufList.mBuffers[0].mDataByteSize = theOutputBufSize; &tmpsiz, NULL);
fillBufList.mBuffers[0].mData = outputBuffer; 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 );
while ((sfifo_used(&fifo) < (inputFormat.mBytesPerPacket * encoderFormat.mFramesPerPacket * 4)) && !readerDone) { // set bitrate
usleep(500); 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");
} }
// convert data UInt32 theOutputBufSize = outputSizePerPacket;
UInt32 ioOutputDataPackets = 1; char *outputBuffer = (char *)malloc(theOutputBufSize);
err = AudioConverterFillComplexBuffer(converterEnc, EncoderDataProc, &encoderData, &ioOutputDataPackets,
&fillBufList, &odesc); // grab the cookie from the converter and write it to the file
if (err) UInt32 cookieSize = 0;
{ err = AudioConverterGetPropertyInfo(converterEnc, kAudioConverterCompressionMagicCookie, &cookieSize, NULL);
//NSLog(@"Error converterEnc %ld", (long)err); // 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);
} }
if (ioOutputDataPackets == 0) {
// this is the EOF conditon
break;
}
MP42SampleBuffer *sample = [[MP42SampleBuffer alloc] init]; // loop to convert data
sample->data = malloc(fillBufList.mBuffers[0].mDataByteSize); SInt64 outputPos = 0;
memcpy(sample->data, outputBuffer, fillBufList.mBuffers[0].mDataByteSize);
sample->size = fillBufList.mBuffers[0].mDataByteSize; while (1) {
sample->duration = 1024; AudioStreamPacketDescription odesc = {0, 0, 0};
sample->offset = 0;
sample->timestamp = outputPos;
sample->isSync = YES;
while ([_outputSamplesBuffer isFull] && !_cancelled) // set up output buffer list
usleep(500); AudioBufferList fillBufList;
fillBufList.mNumberBuffers = 1;
fillBufList.mBuffers[0].mNumberChannels = inputFormat.mChannelsPerFrame;
fillBufList.mBuffers[0].mDataByteSize = theOutputBufSize;
fillBufList.mBuffers[0].mData = outputBuffer;
[_outputSamplesBuffer enqueue:sample]; while ((sfifo_used(&fifo) < (inputFormat.mBytesPerPacket * encoderFormat.mFramesPerPacket * 4)) && !readerDone) {
[sample release]; usleep(500);
}
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;
}
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);
encoderDone = YES;
} }
free(outputBuffer);
AudioConverterDispose(converterEnc);
[pool release];
encoderDone = YES;
return; return;
} }
@@ -267,17 +268,19 @@ OSStatus DecoderDataProc(AudioConverterRef inAudioConverter,
OSStatus err = noErr; OSStatus err = noErr;
struct AudioFileIO *afio = inUserData; struct AudioFileIO *afio = inUserData;
if (afio->sample) if (afio->sample) {
[afio->sample release]; [afio->sample release];
}
// figure out how much to read // figure out how much to read
if (*ioNumberDataPackets > afio->numPacketsPerRead) *ioNumberDataPackets = afio->numPacketsPerRead; if (*ioNumberDataPackets > afio->numPacketsPerRead) *ioNumberDataPackets = afio->numPacketsPerRead;
// read from the buffer // read from the buffer
while (![afio->inputSamplesBuffer count] && !afio->fileReaderDone) while ([afio->inputSamplesBuffer isEmpty] && !afio->fileReaderDone) {
usleep(250); usleep(250);
}
if (![afio->inputSamplesBuffer count] && afio->fileReaderDone) { if ([afio->inputSamplesBuffer isEmpty] && afio->fileReaderDone) {
*ioNumberDataPackets = 0; *ioNumberDataPackets = 0;
return err; return err;
} }
@@ -300,8 +303,9 @@ OSStatus DecoderDataProc(AudioConverterRef inAudioConverter,
afio->pktDescs->mDataByteSize = afio->sample->size; afio->pktDescs->mDataByteSize = afio->sample->size;
*outDataPacketDescription = afio->pktDescs; *outDataPacketDescription = afio->pktDescs;
} }
else else {
*outDataPacketDescription = NULL; *outDataPacketDescription = NULL;
}
} }
return err; return err;
@@ -424,8 +428,9 @@ OSStatus DecoderDataProc(AudioConverterRef inAudioConverter,
free(outputBuffer); free(outputBuffer);
if (downmix) if (downmix) {
hb_downmix_close(&downmix); hb_downmix_close(&downmix);
}
AudioConverterDispose(decoderData.converter); AudioConverterDispose(decoderData.converter);
@@ -433,7 +438,7 @@ OSStatus DecoderDataProc(AudioConverterRef inAudioConverter,
return; 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])) { if ((self = [super init])) {
OSStatus err; OSStatus err;
@@ -451,8 +456,9 @@ OSStatus DecoderDataProc(AudioConverterRef inAudioConverter,
return nil; return nil;
} }
if (outputChannelCount > inputChannelsCount) if (outputChannelCount > inputChannelsCount) {
outputChannelCount = inputChannelsCount; outputChannelCount = inputChannelsCount;
}
if ([mixdownType isEqualToString:SBMonoMixdown] && inputChannelsCount > 1) { if ([mixdownType isEqualToString:SBMonoMixdown] && inputChannelsCount > 1) {
downmixType = HB_AMIXDOWN_MONO; downmixType = HB_AMIXDOWN_MONO;
@@ -530,10 +536,12 @@ OSStatus DecoderDataProc(AudioConverterRef inAudioConverter,
} }
else if ([track.sourceFormat isEqualToString:MP42AudioFormatPCM]) { else if ([track.sourceFormat isEqualToString:MP42AudioFormatPCM]) {
AudioStreamBasicDescription temp = [track.muxer_helper->importer audioDescriptionForTrack:track]; AudioStreamBasicDescription temp = [track.muxer_helper->importer audioDescriptionForTrack:track];
if (temp.mFormatID) if (temp.mFormatID) {
inputFormat = temp; inputFormat = temp;
else }
else {
inputFormat.mFormatID = kAudioFormatLinearPCM; inputFormat.mFormatID = kAudioFormatLinearPCM;
}
} }
} }
@@ -604,15 +612,17 @@ OSStatus DecoderDataProc(AudioConverterRef inAudioConverter,
UInt32 size = sizeof(inputFormat); UInt32 size = sizeof(inputFormat);
err = AudioConverterGetProperty( decoderData.converter, kAudioConverterCurrentInputStreamDescription, err = AudioConverterGetProperty( decoderData.converter, kAudioConverterCurrentInputStreamDescription,
&size, &inputFormat); &size, &inputFormat);
if (err != noErr) if (err != noErr) {
NSLog(@"Boom kAudioConverterCurrentInputStreamDescription %ld",(long)err); NSLog(@"Boom kAudioConverterCurrentInputStreamDescription %ld",(long)err);
}
// Read the complete outputStreamDescription from the audio converter. // Read the complete outputStreamDescription from the audio converter.
size = sizeof(outputFormat); size = sizeof(outputFormat);
err = AudioConverterGetProperty(decoderData.converter, kAudioConverterCurrentOutputStreamDescription, err = AudioConverterGetProperty(decoderData.converter, kAudioConverterCurrentOutputStreamDescription,
&size, &outputFormat); &size, &outputFormat);
if (err != noErr) if (err != noErr) {
NSLog(@"Boom kAudioConverterCurrentOutputStreamDescription %ld",(long)err); NSLog(@"Boom kAudioConverterCurrentOutputStreamDescription %ld",(long)err);
}
decoderData.inputFormat = inputFormat; decoderData.inputFormat = inputFormat;
decoderData.outputFormat = outputFormat; decoderData.outputFormat = outputFormat;
@@ -633,9 +643,6 @@ OSStatus DecoderDataProc(AudioConverterRef inAudioConverter,
- (MP42SampleBuffer *)copyEncodedSample - (MP42SampleBuffer *)copyEncodedSample
{ {
if (![_outputSamplesBuffer count])
return nil;
return [_outputSamplesBuffer deque]; return [_outputSamplesBuffer deque];
} }
@@ -655,8 +662,9 @@ OSStatus DecoderDataProc(AudioConverterRef inAudioConverter,
[_inputSamplesBuffer cancel]; [_inputSamplesBuffer cancel];
[_outputSamplesBuffer cancel]; [_outputSamplesBuffer cancel];
while (!(readerDone && encoderDone)) while (!(readerDone && encoderDone)) {
usleep(500); usleep(500);
}
} }
- (BOOL)encoderDone - (BOOL)encoderDone
+7 -3
View File
@@ -12,6 +12,8 @@
#include <avcodec.h> #include <avcodec.h>
NS_ASSUME_NONNULL_BEGIN
@class MP42SampleBuffer; @class MP42SampleBuffer;
@class MP42SubtitleTrack; @class MP42SubtitleTrack;
@class MP42OCRWrapper; @class MP42OCRWrapper;
@@ -26,8 +28,8 @@
AVCodecContext *avContext; AVCodecContext *avContext;
AVSubtitle subtitle; AVSubtitle subtitle;
MP42Fifo *_inputSamplesBuffer; MP42Fifo<MP42SampleBuffer *> *_inputSamplesBuffer;
MP42Fifo *_outputSamplesBuffer; MP42Fifo<MP42SampleBuffer *> *_outputSamplesBuffer;
UInt32 paletteG[16]; UInt32 paletteG[16];
NSData *srcMagicCookie; NSData *srcMagicCookie;
@@ -43,7 +45,7 @@
- (instancetype)initWithTrack:(MP42SubtitleTrack *)track error:(NSError **)outError; - (instancetype)initWithTrack:(MP42SubtitleTrack *)track error:(NSError **)outError;
- (void)addSample:(MP42SampleBuffer *)sample; - (void)addSample:(MP42SampleBuffer *)sample;
- (MP42SampleBuffer *)copyEncodedSample; - (nullable MP42SampleBuffer *)copyEncodedSample;
- (void)cancel; - (void)cancel;
@@ -51,3 +53,5 @@
- (void)setInputDone; - (void)setInputDone;
@end @end
NS_ASSUME_NONNULL_END
+2 -6
View File
@@ -453,12 +453,8 @@ void FFInitFFmpeg() {
[_inputSamplesBuffer enqueue:sample]; [_inputSamplesBuffer enqueue:sample];
} }
- (MP42SampleBuffer *)copyEncodedSample - (nullable MP42SampleBuffer *)copyEncodedSample
{ {
if (![_outputSamplesBuffer count]) {
return nil;
}
return [_outputSamplesBuffer deque]; return [_outputSamplesBuffer deque];
} }
@@ -479,7 +475,7 @@ void FFInitFFmpeg() {
- (BOOL)encoderDone - (BOOL)encoderDone
{ {
return _encoderDone; return _encoderDone && [_outputSamplesBuffer isEmpty];
} }
- (void)dealloc - (void)dealloc
+105 -106
View File
@@ -106,88 +106,122 @@ static int ParseByte(const char *string, UInt8 *byte, Boolean hex)
- (void)demux:(id)sender - (void)demux:(id)sender
{ {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; @autoreleasepool {
MP4TrackId trackId = [[_inputTracks lastObject] sourceId]; MP4TrackId trackId = [[_inputTracks lastObject] sourceId];
NSString *scc = STStandardizeStringNewlines(STLoadFileWithUnknownEncoding([_fileURL path])); NSString *scc = STStandardizeStringNewlines(STLoadFileWithUnknownEncoding([_fileURL path]));
if (!scc) return; if (!scc) return;
NSScanner *sc = [NSScanner scannerWithString:scc]; NSScanner *sc = [NSScanner scannerWithString:scc];
NSString *res=nil; NSString *res=nil;
[sc setCharactersToBeSkipped:nil]; [sc setCharactersToBeSkipped:nil];
[sc scanUpToString:@"\n" intoString:&res]; [sc scanUpToString:@"\n" intoString:&res];
if (![res isEqualToString:@"Scenarist_SCC V1.0"]) if (![res isEqualToString:@"Scenarist_SCC V1.0"])
return; return;
unsigned startTime=0; unsigned startTime=0;
BOOL firstSample = YES; BOOL firstSample = YES;
NSString *splitLine = @"\\n+"; NSString *splitLine = @"\\n+";
NSString *splitTimestamp = @"\\t+"; NSString *splitTimestamp = @"\\t+";
NSString *splitBytes = @"\\s+"; NSString *splitBytes = @"\\s+";
NSArray *fileArray = nil; NSArray *fileArray = nil;
NSUInteger i = 0; 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 dropFrame = 0;
uint64_t frameDrop = 0; uint64_t frameDrop = 0;
uint64_t minutesDrop = 0; uint64_t minutesDrop = 0;
for (NSString *line in fileArray) { for (NSString *line in fileArray) {
NSArray *lineArray = [line componentsSeparatedByRegex:splitTimestamp]; NSArray *lineArray = [line componentsSeparatedByRegex:splitTimestamp];
if ([lineArray count] < 2) if ([lineArray count] < 2)
continue; continue;
startTime = ParseTimeCode([[lineArray objectAtIndex:0] UTF8String], 30000, NO, &dropFrame); startTime = ParseTimeCode([[lineArray objectAtIndex:0] UTF8String], 30000, NO, &dropFrame);
MP42TextSample *sample = [[MP42TextSample alloc] init]; MP42TextSample *sample = [[MP42TextSample alloc] init];
sample.timestamp = startTime; sample.timestamp = startTime;
sample.title = [lineArray lastObject]; sample.title = [lineArray lastObject];
[sampleArray addObject:[sample autorelease]]; [sampleArray addObject:[sample autorelease]];
}
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) { for (MP42TextSample *ccSample in sampleArray) {
MP42TextSample *boh = [sampleArray objectAtIndex:1]; if (_cancelled)
sampleDuration = boh.timestamp - ccSample.timestamp; break;
firstSample = NO;
u_int8_t *emptyBuffer = malloc(sizeof(u_int8_t)*8); NSArray *bytesArray = nil;
u_int8_t empty[8] = {0,0,0,8,'c','d','a','t'}; MP4Duration sampleDuration = 0;
memcpy(emptyBuffer, empty, sizeof(u_int8_t)*8); 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]; MP42SampleBuffer *sample = [[MP42SampleBuffer alloc] init];
sample->data = emptyBuffer; sample->data = bytes;
sample->size = 8; sample->size = byteCount + 8;
sample->duration = ccSample.timestamp *= 1001; sample->duration = sampleDuration * 1001;
sample->offset = 0; sample->offset = 0;
sample->timestamp = 0; sample->timestamp = 0;
sample->isSync = 1; sample->isSync = 1;
@@ -196,48 +230,13 @@ static int ParseByte(const char *string, UInt8 *byte, Boolean hex)
[self enqueue:sample]; [self enqueue:sample];
[sample release]; [sample release];
frameDrop += ccSample.timestamp; i++;
minutesDrop += frameDrop; _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) { [sampleArray release];
if (minutesDrop > 18000) [self setDone:YES];
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];
[pool release];
} }
- (void)startReading - (void)startReading
+1 -1
View File
@@ -18,7 +18,7 @@ NS_ASSUME_NONNULL_BEGIN
@required @required
- (void)addSample:(MP42SampleBuffer *)sample; - (void)addSample:(MP42SampleBuffer *)sample;
- (MP42SampleBuffer *)copyEncodedSample; - (nullable MP42SampleBuffer *)copyEncodedSample;
- (void)cancel; - (void)cancel;
- (BOOL)encoderDone; - (BOOL)encoderDone;
+1 -3
View File
@@ -27,14 +27,12 @@ NS_ASSUME_NONNULL_BEGIN
} }
- (instancetype)init; - (instancetype)init;
- (instancetype)initWithCapacity:(NSUInteger)numItems; - (instancetype)initWithCapacity:(NSUInteger)numItems NS_DESIGNATED_INITIALIZER;
- (void)enqueue:(ObjectType)item; - (void)enqueue:(ObjectType)item;
- (nullable ObjectType)deque NS_RETURNS_RETAINED; - (nullable ObjectType)deque NS_RETURNS_RETAINED;
- (nullable ObjectType)dequeAndWait NS_RETURNS_RETAINED; - (nullable ObjectType)dequeAndWait NS_RETURNS_RETAINED;
- (NSUInteger)count;
- (BOOL)isFull; - (BOOL)isFull;
- (BOOL)isEmpty; - (BOOL)isEmpty;
+9 -5
View File
@@ -20,7 +20,7 @@
if (self) { if (self) {
_size = (int32_t)numItems; _size = (int32_t)numItems;
_array = (id *) malloc(sizeof(id) * _size); _array = (id *) malloc(sizeof(id) * _size);
_full = dispatch_semaphore_create(_size); _full = dispatch_semaphore_create(_size - 1);
_empty = dispatch_semaphore_create(0); _empty = dispatch_semaphore_create(0);
} }
@@ -36,8 +36,9 @@
_array[_tail++] = item; _array[_tail++] = item;
if (_tail == _size) if (_tail == _size) {
_tail = 0; _tail = 0;
}
OSAtomicIncrement32(&_count); OSAtomicIncrement32(&_count);
dispatch_semaphore_signal(_empty); dispatch_semaphore_signal(_empty);
@@ -48,8 +49,9 @@
id item = _array[_head++]; id item = _array[_head++];
if (_head == _size) if (_head == _size) {
_head = 0; _head = 0;
}
OSAtomicDecrement32(&_count); OSAtomicDecrement32(&_count);
dispatch_semaphore_signal(_full); dispatch_semaphore_signal(_full);
@@ -81,8 +83,10 @@
} }
- (void)drain { - (void)drain {
while (![self isEmpty]) id item;
[[self deque] release]; while ((item = [self deque])) {
[item release];
}
} }
- (void)cancel { - (void)cancel {
+1 -1
View File
@@ -117,7 +117,7 @@ typedef NS_ENUM(NSUInteger, MP42Status) {
* *
* @return An instance of MP42File * @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 * 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 { - (BOOL)startReading {
NSAssert(self.fileHandle == MP4_INVALID_FILE_HANDLE, @"File Handle already open"); 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) { if (self.fileHandle != MP4_INVALID_FILE_HANDLE) {
self.status = MP42StatusReading; self.status = MP42StatusReading;
@@ -129,7 +129,7 @@ static void logCallback(MP4LogLevel loglevel, const char *fmt, va_list ap) {
- (BOOL)startWriting { - (BOOL)startWriting {
NSAssert(self.fileHandle == MP4_INVALID_FILE_HANDLE, @"File Handle already open"); 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) { if (self.fileHandle != MP4_INVALID_FILE_HANDLE) {
self.status = MP42StatusWriting; self.status = MP42StatusWriting;
@@ -165,7 +165,7 @@ static void logCallback(MP4LogLevel loglevel, const char *fmt, va_list ap) {
return self; return self;
} }
- (instancetype)initWithExistingFile:(NSURL *)URL andDelegate:(id <MP42FileDelegate>)del { - (instancetype)initWithURL:(NSURL *)URL delegate:(nullable id <MP42FileDelegate>)del {
self = [super init]; self = [super init];
if (self) { if (self) {
_delegate = del; _delegate = del;
@@ -557,37 +557,47 @@ static void logCallback(MP4LogLevel loglevel, const char *fmt, va_list ap) {
@autoreleasepool { @autoreleasepool {
NSError *error = nil; NSError *error = nil;
NSFileManager *fileManager = [[NSFileManager alloc] init];
NSURL *tempURL = [self tempURL]; NSURL *tempURL = [self tempURL];
NSFileManager *fileManager = [[NSFileManager alloc] init];
if (tempURL) { 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), ^{ 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; done = YES;
}); });
// Loop to check the progress // Loop to check the progress
while (!done) { 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]; [self progressStatus:((CGFloat)fileSize / originalFileSize) * 100];
usleep(450000); usleep(450000);
} }
// Additional check to see if we can open the optimized file // 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 // Replace the original file
NSURL *result = nil; 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) { if (noErr) {
self.URL = result; self.URL = result;
} else {
[_logger writeErrorToLog:error];
} }
} }
if (!noErr) { if (!noErr) {
// Remove the temp file if the optimization didn't complete // 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 (!url) {
if (outError) { if (outError) {
*outError = MP42Error(@"Invalid path.", @"The destination path cannot be empty.", 100); *outError = MP42Error(@"Invalid path.", @"The destination path cannot be empty.", 100);
[_logger writeErrorToLog:*outError];
} }
return NO; return NO;
} }
@@ -697,6 +708,7 @@ static void logCallback(MP4LogLevel loglevel, const char *fmt, va_list ap) {
success = NO; success = NO;
if (outError) { if (outError) {
*outError = MP42Error(@"The file could not be saved.", @"You do not have sufficient permissions for this operation.", 101); *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 // Close the mp4 file handle
if (![self stopWriting]) { if (![self stopWriting]) {
if (*outError == nil) { if (outError) {
*outError = MP42Error(@"File excedes 4 GB.", *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.", @"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); 102);
@@ -820,9 +832,9 @@ static void logCallback(MP4LogLevel loglevel, const char *fmt, va_list ap) {
} }
// Generate previews images for chapters // Generate previews images for chapters
if ([[attributes valueForKey:MP42GenerateChaptersPreviewTrack] boolValue] && [self.itracks count]) { if ([attributes[MP42GenerateChaptersPreviewTrack] boolValue] && [self.itracks count]) {
[self createChaptersPreview]; [self createChaptersPreview];
} else if ([[attributes valueForKey:MP42CustomChaptersPreviewTrack] boolValue] && [self.itracks count]) { } else if ([attributes[MP42CustomChaptersPreviewTrack] boolValue] && [self.itracks count]) {
[self customChaptersPreview]; [self customChaptersPreview];
} }
+39 -34
View File
@@ -93,6 +93,35 @@
return self; 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 - (NSUInteger)timescaleForTrack:(MP42Track *)track
{ {
return 0; return 0;
@@ -103,7 +132,7 @@
return NSMakeSize(0,0); return NSMakeSize(0,0);
} }
- (NSData *)magicCookieForTrack:(MP42Track *)track - (nullable NSData *)magicCookieForTrack:(MP42Track *)track
{ {
return nil; return nil;
} }
@@ -121,20 +150,24 @@
} }
BOOL alreadyAdded = NO; BOOL alreadyAdded = NO;
for (MP42Track *inputTrack in _inputTracks) for (MP42Track *inputTrack in _inputTracks) {
if (inputTrack.sourceId == track.sourceId) if (inputTrack.sourceId == track.sourceId) {
alreadyAdded = YES; alreadyAdded = YES;
}
}
if (!alreadyAdded) if (!alreadyAdded) {
[_inputTracks addObject:track]; [_inputTracks addObject:track];
}
[_outputsTracks addObject:track]; [_outputsTracks addObject:track];
} }
- (void)startReading - (void)startReading
{ {
for (MP42Track *track in _outputsTracks) for (MP42Track *track in _outputsTracks) {
track.muxer_helper->fifo = [[MP42Fifo alloc] init]; track.muxer_helper->fifo = [[MP42Fifo alloc] init];
}
_doneSem = dispatch_semaphore_create(0); _doneSem = dispatch_semaphore_create(0);
} }
@@ -185,7 +218,7 @@
- (BOOL)cleanUp:(MP4FileHandle)fileHandle - (BOOL)cleanUp:(MP4FileHandle)fileHandle
{ {
return NO; return YES;
} }
- (BOOL)containsTrack:(MP42Track *)track - (BOOL)containsTrack:(MP42Track *)track
@@ -204,32 +237,4 @@
return nil; 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 @end
+162 -161
View File
@@ -1414,192 +1414,193 @@ NSData* H264Info(const char *filePath, uint32_t *pic_width, uint32_t *pic_height
- (void)demux:(id)sender - (void)demux:(id)sender
{ {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; @autoreleasepool {
if (!inFile) if (!inFile) {
inFile = fopen([[_fileURL path] fileSystemRepresentation], "rb"); inFile = fopen([[_fileURL path] fileSystemRepresentation], "rb");
}
MP42Track *track = [_inputTracks lastObject]; MP42Track *track = [_inputTracks lastObject];
MP4TrackId trackId = [track sourceId]; MP4TrackId trackId = [track sourceId];
framerate_t * framerate; framerate_t * framerate;
int64_t currentSize = 0; int64_t currentSize = 0;
for (framerate = (framerate_t*) framerates; framerate->code; framerate++) for (framerate = (framerate_t*) framerates; framerate->code; framerate++)
if([track sourceId] == framerate->code) if([track sourceId] == framerate->code)
break; break;
timescale = framerate->timescale; timescale = framerate->timescale;
mp4FrameDuration = framerate->duration; mp4FrameDuration = framerate->duration;
// the current syntactical object // the current syntactical object
// typically 1:1 with a sample // typically 1:1 with a sample
// but not always, i.e. non-VOP's // but not always, i.e. non-VOP's
// the current sample // the current sample
MP4SampleId sampleId = 1; MP4SampleId sampleId = 1;
// track configuration info // track configuration info
nal_reader_t nal; nal_reader_t nal;
h264_decode_t h264_dec; h264_decode_t h264_dec;
memset(&nal, 0, sizeof(nal)); memset(&nal, 0, sizeof(nal));
nal.ifile = inFile; nal.ifile = inFile;
if (timescale == 0) { if (timescale == 0) {
fprintf(stderr, "%s: Must specify a timescale when reading H.264 files", fprintf(stderr, "%s: Must specify a timescale when reading H.264 files",
ProgName); ProgName);
timescale = 30000; timescale = 30000;
mp4FrameDuration = 1001; mp4FrameDuration = 1001;
} }
rewind(nal.ifile); rewind(nal.ifile);
nal.buffer_size = 0; nal.buffer_size = 0;
nal.buffer_on = 0; nal.buffer_on = 0;
nal.buffer_size_max = 0; nal.buffer_size_max = 0;
free(nal.buffer); free(nal.buffer);
nal.buffer = NULL; nal.buffer = NULL;
uint8_t *nal_buffer; uint8_t *nal_buffer;
uint32_t nal_buffer_size, nal_buffer_size_max; uint32_t nal_buffer_size, nal_buffer_size_max;
nal_buffer = NULL; nal_buffer = NULL;
nal_buffer_size = 0; nal_buffer_size = 0;
nal_buffer_size_max = 0; nal_buffer_size_max = 0;
bool first = true; bool first = true;
bool nal_is_sync = false; bool nal_is_sync = false;
bool slice_is_idr = false; bool slice_is_idr = false;
int32_t poc = 0; int32_t poc = 0;
uint32_t dflags = 0; uint32_t dflags = 0;
// now process the rest of the video stream // now process the rest of the video stream
memset(&h264_dec, 0, sizeof(h264_dec)); memset(&h264_dec, 0, sizeof(h264_dec));
DpbInit(&h264_dpb); DpbInit(&h264_dpb);
while ( (LoadNal(&nal) != false) && !_cancelled) { while ( (LoadNal(&nal) != false) && !_cancelled) {
uint32_t header_size; uint32_t header_size;
header_size = nal.buffer[2] == 1 ? 3 : 4; header_size = nal.buffer[2] == 1 ? 3 : 4;
bool boundary = h264_detect_boundary(nal.buffer, bool boundary = h264_detect_boundary(nal.buffer,
nal.buffer_on, nal.buffer_on,
&h264_dec); &h264_dec);
if (boundary && first == false) { if (boundary && first == false) {
// write the previous sample // write the previous sample
if (nal_buffer_size != 0) { if (nal_buffer_size != 0) {
samplesWritten++; samplesWritten++;
void* sampleData = malloc(nal_buffer_size); void* sampleData = malloc(nal_buffer_size);
memcpy(sampleData, nal_buffer, nal_buffer_size); memcpy(sampleData, nal_buffer, nal_buffer_size);
MP42SampleBuffer *sample = [[MP42SampleBuffer alloc] init]; MP42SampleBuffer *sample = [[MP42SampleBuffer alloc] init];
sample->data = sampleData; sample->data = sampleData;
sample->size = nal_buffer_size; sample->size = nal_buffer_size;
sample->duration = mp4FrameDuration; sample->duration = mp4FrameDuration;
sample->offset = 0; sample->offset = 0;
sample->timestamp = 0; sample->timestamp = 0;
sample->isSync = nal_is_sync; sample->isSync = nal_is_sync;
sample->trackId = trackId; sample->trackId = trackId;
[self enqueue:sample]; [self enqueue:sample];
[sample release]; [sample release];
currentSize += nal_buffer_size; currentSize += nal_buffer_size;
_progress = (currentSize / (CGFloat) _size) * 100; _progress = (currentSize / (CGFloat) _size) * 100;
sampleId++; sampleId++;
DpbAdd( &h264_dpb, poc, slice_is_idr ); DpbAdd( &h264_dpb, poc, slice_is_idr );
nal_is_sync = false; nal_is_sync = false;
nal_buffer_size = 0; 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;
} }
} }
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); if (nal_buffer_size != 0) {
} else { samplesWritten++;
switch (h264_dec.nal_unit_type) { void *sampleData = malloc(nal_buffer_size);
case H264_NAL_TYPE_SEQ_PARAM: memcpy(sampleData, nal_buffer, nal_buffer_size);
// 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; 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];
} }
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];
[pool release];
} }
- (BOOL)cleanUp:(MP4FileHandle)fileHandle - (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. * A simple heap/priority queue implementations with a static size.
* It takes a NSComparator in input. * It takes a NSComparator in input.
*/ */
@interface MP42Heap : NSObject { @interface MP42Heap<ObjectType> : NSObject {
@private @private
id *_array; id *_array;
uint64 _size; uint64 _size;
@@ -25,8 +25,8 @@ NS_ASSUME_NONNULL_BEGIN
- (instancetype)initWithCapacity:(NSUInteger)numItems andComparator:(NSComparator)cmptr; - (instancetype)initWithCapacity:(NSUInteger)numItems andComparator:(NSComparator)cmptr;
- (void)insert:(id)item; - (void)insert:(ObjectType)item;
- (nullable id)extract NS_RETURNS_RETAINED; - (nullable ObjectType)extract NS_RETURNS_RETAINED;
- (NSInteger)count; - (NSInteger)count;
+14 -13
View File
@@ -159,11 +159,12 @@ int readMkvPacket(struct StdIoStream *ioStream, TrackInfo *trackInfo, uint64_t
_fileURL = [fileURL retain]; _fileURL = [fileURL retain];
_ioStream = calloc(1, sizeof(StdIoStream)); _ioStream = calloc(1, sizeof(StdIoStream));
_matroskaFile= openMatroskaFile((char *)[[_fileURL path] UTF8String], _ioStream); _matroskaFile = openMatroskaFile((char *)[[_fileURL path] UTF8String], _ioStream);
if(!_matroskaFile) { if (!_matroskaFile) {
if (outError) if (outError) {
*outError = MP42Error(@"The movie could not be opened.", @"The file is not a matroska file.", 100); *outError = MP42Error(@"The movie could not be opened.", @"The file is not a matroska file.", 100);
}
[self release]; [self release];
return nil; return nil;
@@ -574,14 +575,15 @@ int readMkvPacket(struct StdIoStream *ioStream, TrackInfo *trackInfo, uint64_t
NSData *magicCookie = [NSData dataWithBytes:trackInfo->CodecPrivate length:trackInfo->CodecPrivateSize]; NSData *magicCookie = [NSData dataWithBytes:trackInfo->CodecPrivate length:trackInfo->CodecPrivateSize];
if (magicCookie) if (magicCookie) {
return magicCookie; return magicCookie;
else }
else {
return nil; return nil;
}
} }
// Methods to extract all the samples from the active tracks at the same time // Methods to extract all the samples from the active tracks at the same time
- (void)demux:(id)sender - (void)demux:(id)sender
{ {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; 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]; [self enqueue:demuxHelper->previousSample];
[demuxHelper->previousSample release]; [demuxHelper->previousSample release];
demuxHelper->previousSample = nil; demuxHelper->previousSample = nil;
} }
} }
[self setDone:YES]; [self setDone:YES];
@@ -939,9 +944,6 @@ int readMkvPacket(struct StdIoStream *ioStream, TrackInfo *trackInfo, uint64_t
{ {
[super startReading]; [super startReading];
if (!_matroskaFile)
return;
if (!_demuxerThread && !_done) { if (!_demuxerThread && !_done) {
_demuxerThread = [[NSThread alloc] initWithTarget:self selector:@selector(demux:) object:self]; _demuxerThread = [[NSThread alloc] initWithTarget:self selector:@selector(demux:) object:self];
[_demuxerThread setName:@"Matroska Demuxer"]; [_demuxerThread setName:@"Matroska Demuxer"];
@@ -976,9 +978,8 @@ int readMkvPacket(struct StdIoStream *ioStream, TrackInfo *trackInfo, uint64_t
return YES; return YES;
} }
- (void) dealloc - (void)dealloc
{ {
/* close matroska parser */
closeMatroskaFile(_matroskaFile, _ioStream); closeMatroskaFile(_matroskaFile, _ioStream);
[super dealloc]; [super dealloc];
+105 -87
View File
@@ -35,7 +35,7 @@
if ((self = [super init])) { if ((self = [super init])) {
_fileURL = [fileURL retain]; _fileURL = [fileURL retain];
MP42File *sourceFile = [[MP42File alloc] initWithExistingFile:_fileURL andDelegate:self]; MP42File *sourceFile = [[MP42File alloc] initWithURL:_fileURL delegate:self];
if(!sourceFile) { if(!sourceFile) {
if (outError) { if (outError) {
@@ -46,8 +46,8 @@
return nil; return nil;
} }
_tracksArray = [[sourceFile tracks] mutableCopy]; _tracksArray = [sourceFile.tracks mutableCopy];
_metadata = [[sourceFile metadata] retain]; _metadata = [sourceFile.metadata retain];
[sourceFile release]; [sourceFile release];
} }
@@ -57,30 +57,32 @@
- (NSUInteger)timescaleForTrack:(MP42Track *)track - (NSUInteger)timescaleForTrack:(MP42Track *)track
{ {
return MP4GetTrackTimeScale(_fileHandle, [track sourceId]); return MP4GetTrackTimeScale(_fileHandle, track.sourceId);
} }
- (NSSize)sizeForTrack:(MP42Track *)track - (NSSize)sizeForTrack:(MP42Track *)track
{ {
MP42VideoTrack* currentTrack = (MP42VideoTrack*) track; MP42VideoTrack *currentTrack = (MP42VideoTrack *) track;
return NSMakeSize([currentTrack width], [currentTrack height]); return NSMakeSize([currentTrack width], [currentTrack height]);
} }
- (NSData *)magicCookieForTrack:(MP42Track *)track - (NSData *)magicCookieForTrack:(MP42Track *)track
{ {
if (!_fileHandle) if (!_fileHandle) {
_fileHandle = MP4Read([[_fileURL path] UTF8String]); _fileHandle = MP4Read(_fileURL.path.fileSystemRepresentation);
}
NSData *magicCookie = nil; NSData *magicCookie = nil;
MP4TrackId srcTrackId = [track sourceId]; MP4TrackId srcTrackId = track.sourceId;
const char *trackType = MP4GetTrackType(_fileHandle, srcTrackId); const char *trackType = MP4GetTrackType(_fileHandle, srcTrackId);
const char *media_data_name = MP4GetTrackMediaDataName(_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")) { if (!strcmp(media_data_name, "ac-3")) {
uint64_t fscod, bsid, bsmod, acmod, lfeon, bit_rate_code; 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.fscod", &fscod);
MP4GetTrackIntegerProperty(_fileHandle, srcTrackId, "mdia.minf.stbl.stsd.ac-3.dac3.bsid", &bsid); MP4GetTrackIntegerProperty(_fileHandle, srcTrackId, "mdia.minf.stbl.stsd.ac-3.dac3.bsid", &bsid);
@@ -99,7 +101,8 @@
return [ac3Info autorelease]; 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")) { if (MP4HaveTrackAtom(_fileHandle, srcTrackId, "mdia.minf.stbl.stsd.alac.alac")) {
uint8_t* ppValue; uint8_t* ppValue;
uint32_t pValueSize; uint32_t pValueSize;
@@ -132,9 +135,10 @@
return magicCookie; return magicCookie;
} }
else if (MP4_IS_VIDEO_TRACK_TYPE(trackType)) else if (MP4_IS_VIDEO_TRACK_TYPE(trackType)) {
{
if (!strcmp(media_data_name, "avc1")) { if (!strcmp(media_data_name, "avc1")) {
// Extract and rewrite some kind of avcC extradata from the mp4 file. // Extract and rewrite some kind of avcC extradata from the mp4 file.
NSMutableData *avcCData = [[[NSMutableData alloc] init] autorelease]; NSMutableData *avcCData = [[[NSMutableData alloc] init] autorelease];
@@ -214,86 +218,96 @@
- (void)demux:(id)sender - (void)demux:(id)sender
{ {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; @autoreleasepool {
NSInteger tracksNumber = [_inputTracks count]; NSInteger tracksNumber = _inputTracks.count;
NSInteger tracksDone = 0; NSInteger tracksDone = 0;
MP4DemuxHelper *demuxHelper; MP4DemuxHelper *demuxHelper;
if (!_fileHandle) if (!_fileHandle) {
return; 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;
}
} }
_progress = ((CGFloat)currentTime * timescale / totalDuration) * 100; for (MP42Track *track in _inputTracks) {
currentTime += 3; 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]; MP4Timestamp currentTime = 1;
[pool release]; 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 - (void)startReading
{ {
if (!_fileHandle) if (!_fileHandle) {
_fileHandle = MP4Read([[_fileURL path] UTF8String]); _fileHandle = MP4Read(_fileURL.path.fileSystemRepresentation);
}
[super startReading]; [super startReading];
@@ -323,14 +337,17 @@
MP4AddTrackEdit(dstFileHandle, dstTrackId, i, editMediaStart, editDuration, editDwell); MP4AddTrackEdit(dstFileHandle, dstTrackId, i, editMediaStart, editDuration, editDwell);
i++; i++;
} }
if (trackEditCount) if (trackEditCount) {
MP4SetTrackIntegerProperty(dstFileHandle, dstTrackId, "tkhd.duration", trackDuration); MP4SetTrackIntegerProperty(dstFileHandle, dstTrackId, "tkhd.duration", trackDuration);
}
else if (MP4GetSampleRenderingOffset(dstFileHandle, dstTrackId, 1)) { else if (MP4GetSampleRenderingOffset(dstFileHandle, dstTrackId, 1)) {
uint32_t firstFrameOffset = MP4GetSampleRenderingOffset(dstFileHandle, dstTrackId, 1); uint32_t firstFrameOffset = MP4GetSampleRenderingOffset(dstFileHandle, dstTrackId, 1);
MP4Duration editDuration = MP4ConvertFromTrackDuration(_fileHandle, MP4Duration editDuration = MP4ConvertFromTrackDuration(_fileHandle,
srcTrackId, srcTrackId,
MP4GetTrackDuration(_fileHandle, srcTrackId), MP4GetTrackDuration(_fileHandle, srcTrackId),
MP4GetTimeScale(dstFileHandle)); MP4GetTimeScale(dstFileHandle));
MP4AddTrackEdit(dstFileHandle, dstTrackId, MP4_INVALID_EDIT_ID, firstFrameOffset, MP4AddTrackEdit(dstFileHandle, dstTrackId, MP4_INVALID_EDIT_ID, firstFrameOffset,
editDuration, 0); editDuration, 0);
} }
@@ -341,8 +358,9 @@
- (void)dealloc - (void)dealloc
{ {
if (_fileHandle) if (_fileHandle) {
MP4Close(_fileHandle, 0); MP4Close(_fileHandle, 0);
}
[super dealloc]; [super dealloc];
} }
+40 -36
View File
@@ -402,29 +402,30 @@
- (void)work - (void)work
{ {
if (![_workingTracks count]) { if (!_workingTracks.count) {
return; return;
} }
@autoreleasepool { NSMutableArray<MP42FileImporter *> *trackImportersArray = [[NSMutableArray alloc] init];
NSMutableArray<MP42FileImporter *> *trackImportersArray = [[NSMutableArray alloc] init]; NSUInteger done = 0, update = 0;
NSUInteger done = 0, update = 0; CGFloat progress = 0;
CGFloat progress = 0;
for (MP42Track *track in _workingTracks) { for (MP42Track *track in _workingTracks) {
if (![trackImportersArray containsObject:track.muxer_helper->importer]) { if (![trackImportersArray containsObject:track.muxer_helper->importer]) {
[trackImportersArray addObject:track.muxer_helper->importer]; [trackImportersArray addObject:track.muxer_helper->importer];
}
} }
}
for (MP42FileImporter *importerHelper in trackImportersArray) { for (MP42FileImporter *importerHelper in trackImportersArray) {
[importerHelper startReading]; [importerHelper startReading];
} }
NSUInteger tracksImportersCount = [trackImportersArray count]; NSUInteger tracksImportersCount = trackImportersArray.count;
NSUInteger tracksCount = [_workingTracks count]; NSUInteger tracksCount = _workingTracks.count;
for (;;) {
@autoreleasepool {
for (;;) {
usleep(1000); usleep(1000);
// Iterate the tracks array and mux the samples // Iterate the tracks array and mux the samples
@@ -435,8 +436,9 @@
if (!MP4WriteSample(_fileHandle, track.Id, if (!MP4WriteSample(_fileHandle, track.Id,
sampleBuffer->data, sampleBuffer->size, sampleBuffer->data, sampleBuffer->size,
sampleBuffer->duration, sampleBuffer->offset, sampleBuffer->duration, sampleBuffer->offset,
sampleBuffer->isSync)) sampleBuffer->isSync)) {
_cancelled = YES; _cancelled = YES;
}
[sampleBuffer release]; [sampleBuffer release];
} }
@@ -467,27 +469,29 @@
} }
update++; 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 - (void)cancel
+8
View File
@@ -11,6 +11,10 @@
#import "MP42Utilities.h" #import "MP42Utilities.h"
#include "mp4v2.h" #include "mp4v2.h"
#ifdef __cplusplus
extern "C" {
#endif
typedef enum { TRACK_DISABLED = 0x0, typedef enum { TRACK_DISABLED = 0x0,
TRACK_ENABLED = 0x1, TRACK_ENABLED = 0x1,
TRACK_IN_MOVIE = 0x2, 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); void *fast_realloc_with_padding(void *ptr, unsigned int *size, unsigned int min_size);
int DecompressZlib(uint8_t **sampleData, uint32_t *sampleSize); int DecompressZlib(uint8_t **sampleData, uint32_t *sampleSize);
int DecompressBzlib(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) @interface MP42QTImporter(Private)
-(void) movieLoaded; -(void) movieLoaded;
-(NSString*)formatForTrack: (QTTrack *)track; -(NSString *)formatForTrack: (QTTrack *)track;
-(NSString*)langForTrack: (QTTrack *)track; -(NSString *)langForTrack: (QTTrack *)track;
@end @end
@interface MovDemuxHelper : NSObject { @interface MovDemuxHelper : NSObject {
@@ -47,27 +47,25 @@
if ((self = [super init])) { if ((self = [super init])) {
_fileURL = [fileURL retain]; _fileURL = [fileURL retain];
NSDictionary * dict = [NSDictionary dictionaryWithObjectsAndKeys: NSDictionary *attrs = @{@"QTMovieOpenAsyncRequiredAttribute": @NO,
_fileURL, QTMovieURLAttribute, @"QTMovieOpenAsyncOKAttribute": @NO};
@NO, @"QTMovieOpenAsyncRequiredAttribute",
@NO, @"QTMovieOpenAsyncOKAttribute",
nil];
if (dispatch_get_current_queue() != dispatch_get_main_queue()) { if (dispatch_get_current_queue() != dispatch_get_main_queue()) {
dispatch_sync(dispatch_get_main_queue(), ^{ dispatch_sync(dispatch_get_main_queue(), ^{
_sourceFile = [[QTMovie alloc] initWithAttributes:dict _sourceFile = [[QTMovie alloc] initWithAttributes:attrs
error:outError]; error:outError];
}); });
} }
else else {
_sourceFile = [[QTMovie alloc] initWithAttributes:dict _sourceFile = [[QTMovie alloc] initWithAttributes:attrs
error:outError]; error:outError];
}
if (_sourceFile) if (_sourceFile) {
[self movieLoaded]; [self movieLoaded];
}
else { else {
[self release]; [self release];
return nil; return nil;
} }
} }
@@ -75,16 +73,17 @@
return self; return self;
} }
-(void) movieLoaded - (void)movieLoaded
{ {
for (QTTrack *track in [_sourceFile tracks]) for (QTTrack *track in _sourceFile.tracks) {
if ([[track attributeForKey:QTTrackIsChapterTrackAttribute] boolValue]) if ([[track attributeForKey:QTTrackIsChapterTrackAttribute] boolValue]) {
_chapterId = [[track attributeForKey:QTTrackIDAttribute] integerValue]; _chapterId = [[track attributeForKey:QTTrackIDAttribute] integerValue];
}
}
_tracksArray = [[NSMutableArray alloc] init]; _tracksArray = [[NSMutableArray alloc] init];
if (NSClassFromString(@"QTMetadataItem")) //QTMetadataItem is only 10.7+ [self convertMetadata];
[self convertMetadata];
for (QTTrack *track in [_sourceFile tracks]) { for (QTTrack *track in [_sourceFile tracks]) {
NSString* mediaType = [track attributeForKey:QTTrackMediaTypeAttribute]; NSString* mediaType = [track attributeForKey:QTTrackMediaTypeAttribute];
@@ -828,111 +827,111 @@
- (void)demux:(id)sender - (void)demux:(id)sender
{ {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; @autoreleasepool {
OSStatus err = noErr; OSStatus err = noErr;
NSInteger tracksNumber = [_inputTracks count]; NSInteger tracksNumber = [_inputTracks count];
NSInteger tracksDone = 0; NSInteger tracksDone = 0;
MovDemuxHelper *demuxHelper = nil; MovDemuxHelper *demuxHelper = nil;
for (MP42Track *track in _inputTracks) { for (MP42Track *track in _inputTracks) {
track.muxer_helper->demuxer_context = [[MovDemuxHelper alloc] init]; track.muxer_helper->demuxer_context = [[MovDemuxHelper alloc] init];
Track qtcTrack = [[_sourceFile trackWithTrackID:[track sourceId]] quickTimeTrack]; Track qtcTrack = [[_sourceFile trackWithTrackID:[track sourceId]] quickTimeTrack];
Media media = GetTrackMedia(qtcTrack); Media media = GetTrackMedia(qtcTrack);
demuxHelper = track.muxer_helper->demuxer_context; demuxHelper = track.muxer_helper->demuxer_context;
demuxHelper->totalSampleNumber = GetMediaSampleCount(media); 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);
} }
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: bail:
QTSampleTableRelease(sampleTable); QTSampleTableRelease(sampleTable);
} }
[self setDone:YES]; [self setDone:YES];
[pool release]; }
} }
- (void)startReading - (void)startReading
@@ -973,12 +972,14 @@
editTrackDuration = (editTrackDuration / (double)GetMovieTimeScale([_sourceFile quickTimeMovie])) * MP4GetTimeScale(fileHandle); editTrackDuration = (editTrackDuration / (double)GetMovieTimeScale([_sourceFile quickTimeMovie])) * MP4GetTimeScale(fileHandle);
editDwell = GetTrackEditRate64(qtcTrack, editTrackStart); 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, MP4AddTrackEdit(fileHandle, track.Id, MP4_INVALID_EDIT_ID, editDisplayStart - demuxHelper->minDisplayOffset,
editTrackDuration, !Fix2X(editDwell)); editTrackDuration, !Fix2X(editDwell));
else }
else {
MP4AddTrackEdit(fileHandle, track.Id, MP4_INVALID_EDIT_ID, editDisplayStart, MP4AddTrackEdit(fileHandle, track.Id, MP4_INVALID_EDIT_ID, editDisplayStart,
editTrackDuration, !Fix2X(editDwell)); editTrackDuration, !Fix2X(editDwell));
}
trackDuration += editTrackDuration; trackDuration += editTrackDuration;
// Find the next edit // Find the next edit
@@ -996,7 +997,7 @@
return YES; return YES;
} }
- (void) dealloc - (void)dealloc
{ {
[_sourceFile release]; [_sourceFile release];
+5
View File
@@ -10,6 +10,10 @@
@class MP42Track; @class MP42Track;
typedef NS_OPTIONS(NSUInteger, MP42SampleBufferFlag) {
MP42SampleBufferFlagEndOfFile = 1 << 0,
};
@interface MP42SampleBuffer : NSObject { @interface MP42SampleBuffer : NSObject {
@public @public
void *data; void *data;
@@ -28,6 +32,7 @@
BOOL isForced; BOOL isForced;
void *attachments; void *attachments;
uint16_t flags;
} }
@end @end
+26 -24
View File
@@ -91,8 +91,9 @@
[newTrack setDuration:duration]; [newTrack setDuration:duration];
if (!success) { 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); *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]; [newTrack release];
[self release]; [self release];
@@ -106,8 +107,9 @@
newTrack.verticalPlacement = YES; newTrack.verticalPlacement = YES;
_verticalPlacement = YES; _verticalPlacement = YES;
} }
if ([_ss forced]) if ([_ss forced]) {
newTrack.someSamplesAreForced = YES; newTrack.someSamplesAreForced = YES;
}
[_tracksArray addObject:newTrack]; [_tracksArray addObject:newTrack];
[newTrack release]; [newTrack release];
@@ -128,34 +130,34 @@
- (void)demux:(id)sender - (void)demux:(id)sender
{ {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; @autoreleasepool {
MP42SampleBuffer *sample; MP42SampleBuffer *sample;
for (MP42SubtitleTrack *track in _inputTracks) { for (MP42SubtitleTrack *track in _inputTracks) {
CGSize trackSize; CGSize trackSize;
trackSize.width = track.trackWidth; trackSize.width = track.trackWidth;
trackSize.height = track.trackHeight; trackSize.height = track.trackHeight;
while (![_ss isEmpty] && !_cancelled) { while (![_ss isEmpty] && !_cancelled) {
SBSubLine *sl = [_ss getSerializedPacket]; SBSubLine *sl = [_ss getSerializedPacket];
if ([sl->line isEqualToString:@"\n"]) { if ([sl->line isEqualToString:@"\n"]) {
sample = copyEmptySubtitleSample(track.sourceId, sl->end_time - sl->begin_time, NO); 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 - (void)startReading
+1 -1
View File
@@ -386,7 +386,7 @@ static int ParseForced(NSString *str)
int LoadSRTFromPath(NSString *path, SBSubSerializer *ss, MP4Duration *duration) int LoadSRTFromPath(NSString *path, SBSubSerializer *ss, MP4Duration *duration)
{ {
NSMutableString *srt = STStandardizeStringNewlines(STLoadFileWithUnknownEncoding(path)); 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:0] == 0xFEFF) [srt deleteCharactersInRange:NSMakeRange(0,1)];
if ([srt characterAtIndex:[srt length]-1] != '\n') [srt appendFormat:@"%c",'\n']; 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 - (BOOL)exportToURL:(NSURL *)url error:(NSError **)error
{ {
MP4FileHandle fileHandle = MP4Read([[_sourceURL path] UTF8String]); MP4FileHandle fileHandle = MP4Read(_sourceURL.path.fileSystemRepresentation);
if (!fileHandle) if (!fileHandle)
return NO; return NO;
+1 -1
View File
@@ -20,7 +20,7 @@ typedef struct muxer_helper {
// Output helpers // Output helpers
id <MP42ConverterProtocol> converter; id <MP42ConverterProtocol> converter;
MP42Fifo *fifo; MP42Fifo<MP42SampleBuffer *> *fifo;
BOOL done; BOOL done;
} muxer_helper; } muxer_helper;
+11 -7
View File
@@ -12,8 +12,9 @@
- (muxer_helper *)muxer_helper - (muxer_helper *)muxer_helper
{ {
if (_helper == NULL) if (_helper == NULL) {
_helper = calloc(1, sizeof(muxer_helper)); _helper = calloc(1, sizeof(muxer_helper));
}
return _helper; return _helper;
} }
@@ -23,19 +24,22 @@
muxer_helper *helper = (muxer_helper *)_helper; muxer_helper *helper = (muxer_helper *)_helper;
if (helper->converter) { if (helper->converter) {
if ([helper->importer done]) if ([helper->importer done]) {
[helper->converter setInputDone]; [helper->converter setInputDone];
}
if ([helper->converter encoderDone]) if ([helper->converter encoderDone]) {
helper->done = YES; helper->done = YES;
}
sample = [helper->converter copyEncodedSample]; sample = [helper->converter copyEncodedSample];
} else { }
if ([helper->fifo isEmpty] && [helper->importer done]) else {
if ([helper->fifo isEmpty] && [helper->importer done]) {
helper->done = YES; helper->done = YES;
}
if ([helper->fifo count]) sample = [helper->fifo deque];
sample = [helper->fifo deque];
} }
return sample; return sample;
+82 -80
View File
@@ -119,7 +119,7 @@ static NSString *getNextVobSubLine(NSEnumerator *lineEnum)
return line; return line;
} }
static NSArray* LoadVobSubSubtitles(NSURL *theDirectory, NSString *filename) static NSArray<SBVobSubTrack *> * LoadVobSubSubtitles(NSURL *theDirectory, NSString *filename)
{ {
@autoreleasepool { @autoreleasepool {
NSString *nsPath = [[theDirectory path] stringByAppendingPathComponent:filename]; NSString *nsPath = [[theDirectory path] stringByAppendingPathComponent:filename];
@@ -144,7 +144,7 @@ static NSArray* LoadVobSubSubtitles(NSURL *theDirectory, NSString *filename)
NSEnumerator *lineEnum = [lines objectEnumerator]; NSEnumerator *lineEnum = [lines objectEnumerator];
NSString *line; NSString *line;
NSMutableArray *tracks = [NSMutableArray array]; NSMutableArray<SBVobSubTrack *> *tracks = [NSMutableArray array];
while((line = getNextVobSubLine(lineEnum)) != NULL) while((line = getNextVobSubLine(lineEnum)) != NULL)
{ {
@@ -225,8 +225,8 @@ static NSArray* LoadVobSubSubtitles(NSURL *theDirectory, NSString *filename)
NSInteger count = 0; NSInteger count = 0;
_fileURL = [fileURL retain]; _fileURL = [fileURL retain];
_VobSubTracks = LoadVobSubSubtitles([_fileURL URLByDeletingLastPathComponent], [_fileURL lastPathComponent]); _VobSubTracks = LoadVobSubSubtitles(_fileURL.URLByDeletingLastPathComponent, _fileURL.lastPathComponent);
_tracksArray = [[NSMutableArray alloc] initWithCapacity:[_VobSubTracks count]]; _tracksArray = [[NSMutableArray alloc] initWithCapacity:_VobSubTracks.count];
for (SBVobSubTrack *track in _VobSubTracks) { for (SBVobSubTrack *track in _VobSubTracks) {
MP42SubtitleTrack *newTrack = [[MP42SubtitleTrack alloc] init]; MP42SubtitleTrack *newTrack = [[MP42SubtitleTrack alloc] init];
@@ -242,9 +242,10 @@ static NSArray* LoadVobSubSubtitles(NSURL *theDirectory, NSString *filename)
[newTrack release]; [newTrack release];
} }
if (![_tracksArray count]) { if (!_tracksArray.count) {
if (outError) 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); *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]; [self release];
return nil; return nil;
@@ -290,70 +291,84 @@ static NSArray* LoadVobSubSubtitles(NSURL *theDirectory, NSString *filename)
- (void)demux:(id)sender - (void)demux:(id)sender
{ {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; @autoreleasepool {
NSURL *subFileURL = [[_fileURL URLByDeletingPathExtension] URLByAppendingPathExtension:@"sub"];
NSData *subFileData = [NSData dataWithContentsOfURL:subFileURL]; NSURL *subFileURL = [[_fileURL URLByDeletingPathExtension] URLByAppendingPathExtension:@"sub"];
NSInteger tracksNumber = [_inputTracks count]; NSData *subFileData = [NSData dataWithContentsOfURL:subFileURL];
NSInteger tracksDone = 0;
for (MP42Track *track in _inputTracks) { NSInteger tracksNumber = [_inputTracks count];
SBVobSubTrack *vobTrack = [_VobSubTracks objectAtIndex:track.sourceId]; NSInteger tracksDone = 0;
SBVobSubSample *firstSample = nil;
uint32_t lastTime = 0; for (MP42Track *track in _inputTracks) {
int i, sampleCount = [vobTrack->samples count]; SBVobSubTrack *vobTrack = [_VobSubTracks objectAtIndex:track.sourceId];
SBVobSubSample *firstSample = nil;
for (i = 0; i < sampleCount && !_cancelled; i++) { uint32_t lastTime = 0;
SBVobSubSample *currentSample = [vobTrack->samples objectAtIndex:i]; int i, sampleCount = [vobTrack->samples count];
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)]; for (i = 0; i < sampleCount && !_cancelled; i++) {
uint8_t *extracted = (uint8_t *)malloc(size); SBVobSubSample *currentSample = [vobTrack->samples objectAtIndex:i];
//The index here likely should really be track->index, but I'm not sure we can really trust it. int offset = currentSample->fileOffset;
int extractedSize = ExtractVobSubPacket(extracted, (UInt8 *)[subData bytes], size, &size, -1); 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;
uint16_t startTimestamp, endTimestamp; NSData *subData = [subFileData subdataWithRange:NSMakeRange(offset, size)];
uint8_t forced; uint8_t *extracted = (uint8_t *)malloc(size);
if (!ReadPacketTimes(extracted, extractedSize, &startTimestamp, &endTimestamp, &forced)) { //The index here likely should really be track->index, but I'm not sure we can really trust it.
free(extracted); int extractedSize = ExtractVobSubPacket(extracted, (UInt8 *)[subData bytes], size, &size, -1);
continue;
}
uint32_t startTime = currentSample->timeStamp + startTimestamp; uint16_t startTimestamp, endTimestamp;
uint32_t endTime = currentSample->timeStamp + 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];
}
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]; MP42SampleBuffer *sample = [[MP42SampleBuffer alloc] init];
sample->size = 2; sample->data = extracted;
sample->data = calloc(1, 2); sample->size = size;
sample->duration = startTime - lastTime; sample->duration = duration;
sample->offset = 0; sample->offset = 0;
sample->timestamp = startTime; sample->timestamp = startTime;
sample->isSync = YES; sample->isSync = YES;
@@ -361,29 +376,16 @@ static NSArray* LoadVobSubSubtitles(NSURL *theDirectory, NSString *filename)
[self enqueue:sample]; [self enqueue:sample];
[sample release]; [sample release];
lastTime = endTime;
_progress = ((i / (CGFloat) sampleCount ) * 100 / tracksNumber) + (tracksDone / (CGFloat) tracksNumber * 100);
} }
tracksDone++;
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++;
}
[self setDone:YES]; [self setDone:YES];
[pool release]; }
} }
- (void)startReading - (void)startReading