Almost working edit lists implementation in the AVFoundation importer. yay!

This commit is contained in:
Damiano Galassi committed 2014-03-26 19:35:55 +01:00
1 parent 1035b321c6
commit b7668b0fc8
3 files changed
+88 -142

No files matched your search

+83 -139
View File
@@ -20,20 +20,15 @@
#import <AVFoundation/AVFoundation.h> #import <AVFoundation/AVFoundation.h>
#import <AudioToolbox/AudioToolbox.h> #import <AudioToolbox/AudioToolbox.h>
#define SB_AVF_DEBUG
@interface AVFDemuxHelper : NSObject { @interface AVFDemuxHelper : NSObject {
@public @public
BOOL countFrames; CMTimeRange *edits;
int64_t correctionValue; uint64_t editsCount;
int64_t disTimeStamp; uint64_t editsSize;
CMTimeRange *discontinuity; int64_t currentTime;
uint64_t discontinuityCount;
BOOL doNotDisplay;
CMTime currentTime;
CMTime segmentEndTimestamp;
CMTime segmentDuration;
CMTime segmentStarTime;
AVAssetReaderOutput *assetReaderOutput; AVAssetReaderOutput *assetReaderOutput;
int64_t minDisplayOffset;
} }
@end @end
@@ -42,9 +37,9 @@
@implementation MP42AVFImporter @implementation MP42AVFImporter
- (NSString*)formatForTrack: (AVAssetTrack *)track; - (NSString *)formatForTrack: (AVAssetTrack *)track;
{ {
NSString* result = @""; NSString *result = @"";
CMFormatDescriptionRef formatDescription = NULL; CMFormatDescriptionRef formatDescription = NULL;
NSArray *formatDescriptions = track.formatDescriptions; NSArray *formatDescriptions = track.formatDescriptions;
@@ -154,6 +149,9 @@
case kCMVideoCodecType_DVCPROHD1080p25: case kCMVideoCodecType_DVCPROHD1080p25:
result = @"DVCProHD"; result = @"DVCProHD";
break; break;
case 'AVdn':
result = @"DNxHD";
break;
default: default:
result = @"Unknown"; result = @"Unknown";
break; break;
@@ -638,16 +636,30 @@
return nil; return nil;
} }
- (void)startEditListAtTime:(CMTime)time helper:(AVFDemuxHelper *)helper {
if (helper->editsSize <= helper->editsCount) {
helper->editsSize += 20;
helper->edits = (CMTimeRange *) realloc(helper->edits, sizeof(CMTimeRange) * helper->editsSize);
}
helper->edits[helper->editsCount] = CMTimeRangeMake(time, kCMTimeInvalid);
}
- (void)endEditListAtTime:(CMTime)time helper:(AVFDemuxHelper *)helper {
time.value -= helper->edits[helper->editsCount].start.value;
helper->edits[helper->editsCount].duration = time;
helper->editsCount++;
}
- (void)demux:(id)sender - (void)demux:(id)sender
{ {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
BOOL success = YES; BOOL success = YES;
OSStatus err = noErr; OSStatus err = noErr;
uint64_t currentDataLength = 0; uint64_t currentDataLength = 0;
uint64_t totalDataLength = 0; uint64_t totalDataLength = 0;
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
AVFDemuxHelper *demuxHelper=nil; AVFDemuxHelper *demuxHelper=nil;
NSError *localError; NSError *localError;
AVAssetReader *assetReader = [[AVAssetReader alloc] initWithAsset:_localAsset error:&localError]; AVAssetReader *assetReader = [[AVAssetReader alloc] initWithAsset:_localAsset error:&localError];
@@ -677,6 +689,8 @@
demuxHelper = track.muxer_helper->demuxer_context; demuxHelper = track.muxer_helper->demuxer_context;
AVAssetReaderOutput *assetReaderOutput = demuxHelper->assetReaderOutput; AVAssetReaderOutput *assetReaderOutput = demuxHelper->assetReaderOutput;
[self startEditListAtTime:kCMTimeInvalid helper:demuxHelper];
while (!_cancelled) { while (!_cancelled) {
CMSampleBufferRef sampleBuffer = [assetReaderOutput copyNextSampleBuffer]; CMSampleBufferRef sampleBuffer = [assetReaderOutput copyNextSampleBuffer];
if (sampleBuffer) { if (sampleBuffer) {
@@ -707,38 +721,30 @@
} }
} }
if ((presentationTimeStamp.value + demuxHelper->correctionValue) != presentationOutputTimeStamp.value) { #ifdef SB_AVF_DEBUG
if (!demuxHelper->discontinuity) NSLog(@"Dur: %lld, D: %lld, P: %lld, PO: %lld Display: %d", duration.value, decodeTimeStamp.value, presentationTimeStamp.value, presentationOutputTimeStamp.value, doNotDisplay);
demuxHelper->discontinuity = (CMTimeRange *) malloc(sizeof(CMTimeRange) * 100); #endif
NSLog(@"We found a timestamp discontinuity"); CFTypeRef trimStart = CMGetAttachment(sampleBuffer, kCMSampleBufferAttachmentKey_TrimDurationAtStart, kCMAttachmentMode_ShouldNotPropagate);
NSLog(@"Current presentationTimeStamp: %lld", presentationTimeStamp.value); if (trimStart) {
demuxHelper->correctionValue = -presentationTimeStamp.value + presentationOutputTimeStamp.value; CMTime trimStartTime = CMTimeMakeFromDictionary(trimStart);
//demuxHelper->disTimeStamp = presentationOutputTimeStamp.value;
NSLog(@"Making an adjustment of %lld", -demuxHelper->correctionValue);
NSLog(@"Timestamp of discontinuity %lld", presentationOutputTimeStamp.value);
demuxHelper->discontinuity[demuxHelper->discontinuityCount].start = presentationTimeStamp; trimStartTime = CMTimeConvertScale(trimStartTime, duration.timescale, kCMTimeRoundingMethod_Default);
demuxHelper->discontinuity[demuxHelper->discontinuityCount].duration.value = -demuxHelper->correctionValue; //presentationTimeStamp.value; CMTime editStart = CMTimeMake(demuxHelper->currentTime, duration.timescale);
demuxHelper->discontinuity[demuxHelper->discontinuityCount].duration.timescale = presentationTimeStamp.timescale; editStart.value += trimStartTime.value;
demuxHelper->discontinuityCount++; [self startEditListAtTime:editStart helper:demuxHelper];
demuxHelper->countFrames = YES;
}
if (demuxHelper->countFrames) {
demuxHelper->disTimeStamp += duration.value;
}
if (presentationOutputTimeStamp.value >= demuxHelper->currentTime.value) {
demuxHelper->currentTime = presentationOutputTimeStamp;
if (demuxHelper->countFrames) {
demuxHelper->discontinuity[demuxHelper->discontinuityCount-1].duration.value -= demuxHelper->disTimeStamp;
NSLog(@"Corrected decode time stamp: %lld", demuxHelper->disTimeStamp);
}
demuxHelper->countFrames = NO;
} }
CFTypeRef trimEnd = CMGetAttachment(sampleBuffer, kCMSampleBufferAttachmentKey_TrimDurationAtEnd, kCMAttachmentMode_ShouldNotPropagate);
if (trimEnd) {
CMTime trimEndTime = CMTimeMakeFromDictionary(trimEnd);
//NSLog(@"D: %lld, P: %lld, PO: %lld Display: %d", decodeTimeStamp.value, presentationTimeStamp.value, presentationOutputTimeStamp.value, doNotDisplay); trimEndTime = CMTimeConvertScale(trimEndTime, duration.timescale, kCMTimeRoundingMethod_Default);
CMTime editEnd = CMTimeMake(demuxHelper->currentTime, duration.timescale);
editEnd.value += duration.value - trimEndTime.value;
[self endEditListAtTime:editEnd helper:demuxHelper];
}
MP42SampleBuffer *sample = [[MP42SampleBuffer alloc] init]; MP42SampleBuffer *sample = [[MP42SampleBuffer alloc] init];
sample->data = sampleData; sample->data = sampleData;
@@ -752,9 +758,9 @@
[self enqueue:sample]; [self enqueue:sample];
[sample release]; [sample release];
demuxHelper->currentTime += duration.value;
currentDataLength += sampleSize; currentDataLength += sampleSize;
} } else {
else {
if (!CMSampleBufferDataIsReady(sampleBuffer)) if (!CMSampleBufferDataIsReady(sampleBuffer))
CMSampleBufferMakeDataReady(sampleBuffer); CMSampleBufferMakeDataReady(sampleBuffer);
@@ -789,8 +795,19 @@
CMBlockBufferRef buffer = CMSampleBufferGetDataBuffer(sampleBuffer); CMBlockBufferRef buffer = CMSampleBufferGetDataBuffer(sampleBuffer);
size_t bufferSize = CMBlockBufferGetDataLength(buffer); size_t bufferSize = CMBlockBufferGetDataLength(buffer);
int i = 0, pos = 0; #ifdef SB_AVF_DEBUG
for (i = 0; i < samplesNum; i++) { #endif
CFTypeRef trimStart = CMGetAttachment(sampleBuffer, kCMSampleBufferAttachmentKey_TrimDurationAtStart, kCMAttachmentMode_ShouldNotPropagate);
if (trimStart) {
CMTime trimStartTime = CMTimeMakeFromDictionary(trimStart);
}
CFTypeRef trimEnd = CMGetAttachment(sampleBuffer, kCMSampleBufferAttachmentKey_TrimDurationAtEnd, kCMAttachmentMode_ShouldNotPropagate);
if (trimEnd) {
CMTime trimEndTime = CMTimeMakeFromDictionary(trimStart);
}
int pos = 0;
for (int i = 0; i < samplesNum; i++) {
CMSampleTimingInfo sampleTimingInfo; CMSampleTimingInfo sampleTimingInfo;
CMTime decodeTimeStamp = {0,0,0,0}; CMTime decodeTimeStamp = {0,0,0,0};
CMTime presentationTimeStamp = {0,0,0,0}; CMTime presentationTimeStamp = {0,0,0,0};
@@ -807,8 +824,7 @@
presentationTimeStamp = sampleTimingInfo.presentationTimeStamp; presentationTimeStamp = sampleTimingInfo.presentationTimeStamp;
presentationTimeStamp.value = presentationTimeStamp.value + ( sampleTimingInfo.duration.value * i); presentationTimeStamp.value = presentationTimeStamp.value + ( sampleTimingInfo.duration.value * i);
} } else {
else {
sampleTimingInfo = timingArrayOut[i]; sampleTimingInfo = timingArrayOut[i];
decodeTimeStamp = sampleTimingInfo.decodeTimeStamp; decodeTimeStamp = sampleTimingInfo.decodeTimeStamp;
presentationTimeStamp = sampleTimingInfo.presentationTimeStamp; presentationTimeStamp = sampleTimingInfo.presentationTimeStamp;
@@ -817,10 +833,11 @@
presentationOutputTimeStamp.value = presentationOutputTimeStamp.value + ( sampleTimingInfo.duration.value * i / ( (double) sampleTimingInfo.duration.timescale / presentationOutputTimeStamp.timescale)); presentationOutputTimeStamp.value = presentationOutputTimeStamp.value + ( sampleTimingInfo.duration.value * i / ( (double) sampleTimingInfo.duration.timescale / presentationOutputTimeStamp.timescale));
// If the size of sample size array is equal to 1, it means every sample has got the same size // If the size of sample size array is equal to 1, it means every sample has got the same size
if (sizeArrayEntries == 1) if (sizeArrayEntries == 1) {
sampleSize = sizeArrayOut[0]; sampleSize = sizeArrayOut[0];
else } else {
sampleSize = sizeArrayOut[i]; sampleSize = sizeArrayOut[i];
}
if (!sampleSize) if (!sampleSize)
continue; continue;
@@ -844,38 +861,9 @@
} }
} }
if ((presentationTimeStamp.value + demuxHelper->correctionValue) != presentationOutputTimeStamp.value) { #ifdef SB_AVF_DEBUG
if (!demuxHelper->discontinuity) NSLog(@"D: %lld, P: %lld, PO: %lld", decodeTimeStamp.value, presentationTimeStamp.value, presentationOutputTimeStamp.value);
demuxHelper->discontinuity = (CMTimeRange *) malloc(sizeof(CMTimeRange) * 100); #endif
NSLog(@"We found a timestamp discontinuity");
NSLog(@"Current presentationTimeStamp: %lld", presentationTimeStamp.value);
demuxHelper->correctionValue = -presentationTimeStamp.value + presentationOutputTimeStamp.value;
//demuxHelper->disTimeStamp = presentationOutputTimeStamp.value;
NSLog(@"Making an adjustment of %lld", -demuxHelper->correctionValue);
NSLog(@"Timestamp of discontinuity %lld", presentationOutputTimeStamp.value);
demuxHelper->discontinuity[demuxHelper->discontinuityCount].start = presentationTimeStamp;
demuxHelper->discontinuity[demuxHelper->discontinuityCount].duration.value = -demuxHelper->correctionValue; //presentationTimeStamp.value;
demuxHelper->discontinuity[demuxHelper->discontinuityCount].duration.timescale = presentationTimeStamp.timescale;
demuxHelper->discontinuityCount++;
demuxHelper->countFrames = YES;
}
if (demuxHelper->countFrames) {
demuxHelper->disTimeStamp += sampleTimingInfo.duration.value;
}
if (presentationOutputTimeStamp.value >= demuxHelper->currentTime.value) {
demuxHelper->currentTime = presentationOutputTimeStamp;
if (demuxHelper->countFrames) {
demuxHelper->discontinuity[demuxHelper->discontinuityCount-1].duration.value -= demuxHelper->disTimeStamp;
NSLog(@"Corrected decode time stamp: %lld", demuxHelper->disTimeStamp);
}
demuxHelper->countFrames = NO;
}
//NSLog(@"D: %lld, P: %lld, PO: %lld", decodeTimeStamp.value, presentationTimeStamp.value, presentationOutputTimeStamp.value);
MP42SampleBuffer *sample = [[MP42SampleBuffer alloc] init]; MP42SampleBuffer *sample = [[MP42SampleBuffer alloc] init];
sample->data = sampleData; sample->data = sampleData;
@@ -901,8 +889,7 @@
_progress = (((CGFloat) currentDataLength / totalDataLength ) * 100); _progress = (((CGFloat) currentDataLength / totalDataLength ) * 100);
} } else {
else {
AVAssetReaderStatus status = assetReader.status; AVAssetReaderStatus status = assetReader.status;
if (status == AVAssetReaderStatusCompleted) { if (status == AVAssetReaderStatusCompleted) {
@@ -933,73 +920,30 @@
- (BOOL)cleanUp:(MP4FileHandle) fileHandle - (BOOL)cleanUp:(MP4FileHandle) fileHandle
{ {
uint32_t timescale = MP4GetTimeScale(fileHandle); uint32_t timescale = MP4GetTimeScale(fileHandle);
long i;
for (MP42Track *track in _inputTracks) { for (MP42Track *track in _inputTracks) {
AVAssetTrack *assetTrack = [_localAsset trackWithTrackID:track.sourceId];
MP42Track *inputTrack = [self inputTrackWithTrackID:track.sourceId];
MP4Duration trackDuration = 0; MP4Duration trackDuration = 0;
MP4Timestamp editDuration; MP42Track *inputTrack = [self inputTrackWithTrackID:track.sourceId];
AVFDemuxHelper *demuxHelper = inputTrack.muxer_helper->demuxer_context; AVFDemuxHelper *demuxHelper = inputTrack.muxer_helper->demuxer_context;
for (AVAssetTrackSegment *segment in assetTrack.segments) { for (int i = 0; i < demuxHelper->editsCount; i++) {
bool empty = NO; CMTimeRange timeRange = demuxHelper->edits[i];
CMTimeMapping timeMapping = segment.timeMapping; CMTime duration = CMTimeConvertScale(timeRange.duration, timescale, kCMTimeRoundingMethod_Default);
CMTimeValue correction = 0;
for (i = demuxHelper->discontinuityCount - 1; i >= 0; i--) { trackDuration += duration.value;
CMTimeRange timeRange = demuxHelper->discontinuity[i];
if (timeMapping.source.start.value > timeRange.start.value) { MP4AddTrackEdit(fileHandle, track.Id, MP4_INVALID_EDIT_ID, timeRange.start.value,
correction = timeRange.duration.value; duration.value, 0);
NSLog(@"Discontinuity --");
NSLog(@"Presentation Time: %lld", timeRange.start.value);
NSLog(@"Timescale: %d", timeRange.start.timescale);
NSLog(@"Correction: %lld", timeRange.duration.value);
break; #ifdef SB_AVF_DEBUG
} NSLog(@"Edit start: %lld, duration: %lld", timeRange.start.value, duration.value);
#endif
}
if (timeMapping.source.duration.flags & kCMTimeFlags_Indefinite || timeMapping.target.duration.flags & kCMTimeFlags_Indefinite) {
NSLog(@"Indefinite time mappings");
}
else {
NSLog(@"Source --");
NSLog(@"Start: %lld", timeMapping.source.start.value);
NSLog(@"Timescale: %d", timeMapping.source.start.timescale);
NSLog(@"Duration: %lld", timeMapping.source.duration.value);
NSLog(@"Timescale: %d", timeMapping.source.duration.timescale);
NSLog(@"Target --");
NSLog(@"Start %lld", timeMapping.target.start.value);
NSLog(@"Timescale: %d", timeMapping.target.start.timescale);
NSLog(@"Duration: %lld", timeMapping.target.duration.value);
NSLog(@"Timescale: %d", timeMapping.target.start.timescale);
if (segment.empty) {
NSLog(@"Empty segment");
empty = YES;
}
editDuration = timeMapping.target.duration.value * ((double) timescale / timeMapping.target.duration.timescale);
if (empty)
MP4AddTrackEdit(fileHandle, track.Id, MP4_INVALID_EDIT_ID, -1,
editDuration, 0);
else
MP4AddTrackEdit(fileHandle, track.Id, MP4_INVALID_EDIT_ID, timeMapping.source.start.value - correction,
editDuration, 0);
trackDuration = trackDuration + editDuration;
}
} }
if (trackDuration) if (trackDuration)
MP4SetTrackIntegerProperty(fileHandle, track.Id, "tkhd.duration", trackDuration); MP4SetTrackIntegerProperty(fileHandle, track.Id, "tkhd.duration", trackDuration);
} }
return YES; return YES;
} }
+3 -2
View File
@@ -225,7 +225,7 @@ static void logCallback(MP4LogLevel loglevel, const char* fmt, va_list ap)
if ([track.format isEqualToString:MP42VideoFormatJPEG]) if ([track.format isEqualToString:MP42VideoFormatJPEG])
previewsId = track.Id; previewsId = track.Id;
[self loadPreviewsFromTrackID:previewsId]; //[self loadPreviewsFromTrackID:previewsId];
_tracksToBeDeleted = [[NSMutableArray alloc] init]; _tracksToBeDeleted = [[NSMutableArray alloc] init];
_metadata = [[MP42Metadata alloc] initWithSourceURL:_fileURL fileHandle:_fileHandle]; _metadata = [[MP42Metadata alloc] initWithSourceURL:_fileURL fileHandle:_fileHandle];
@@ -281,7 +281,8 @@ static void logCallback(MP4LogLevel loglevel, const char* fmt, va_list ap)
NSData *frameData = [[NSData alloc] initWithBytes:pBytes length:numBytes]; NSData *frameData = [[NSData alloc] initWithBytes:pBytes length:numBytes];
MP42Image *frame = [[MP42Image alloc] initWithData:frameData type:MP42_ART_JPEG]; MP42Image *frame = [[MP42Image alloc] initWithData:frameData type:MP42_ART_JPEG];
[[self chapters] chapterAtIndex:currentSampleNum - 1].image = frame; if ([[self chapters].chapters count] >= currentSampleNum)
[[self chapters] chapterAtIndex:currentSampleNum - 1].image = frame;
[frameData release]; [frameData release];
[frame release]; [frame release];
+2 -1
View File
@@ -66,7 +66,8 @@
// If we are on 10.7 or later, use the AVFoundation path // If we are on 10.7 or later, use the AVFoundation path
else if (NSClassFromString(@"AVAsset")) { else if (NSClassFromString(@"AVAsset")) {
if ([[fileURL pathExtension] caseInsensitiveCompare: @"m2ts"] == NSOrderedSame || if ([[fileURL pathExtension] caseInsensitiveCompare: @"m2ts"] == NSOrderedSame ||
[[fileURL pathExtension] caseInsensitiveCompare: @"mts"] == NSOrderedSame ) { [[fileURL pathExtension] caseInsensitiveCompare: @"mts"] == NSOrderedSame ||
[[fileURL pathExtension] caseInsensitiveCompare: @"mov"] == NSOrderedSame) {
self = [MP42AVFImporter alloc]; self = [MP42AVFImporter alloc];
} }
} }