diff --git a/MP42/MP42SubtitleTrack.m b/MP42/MP42SubtitleTrack.m index f98bed2..60ec68d 100644 --- a/MP42/MP42SubtitleTrack.m +++ b/MP42/MP42SubtitleTrack.m @@ -12,6 +12,8 @@ #import "MP42MediaFormat.h" #import "MP42HtmlParser.h" +#import + @implementation MP42SubtitleTrack - (instancetype)initWithSourceURL:(NSURL *)URL trackID:(NSInteger)trackID fileHandle:(MP4FileHandle)fileHandle @@ -208,20 +210,16 @@ static void insertTagsFromStyleRecord(style_record record, NSMutableString *samp - (BOOL)exportToURL:(NSURL *)url error:(NSError * __autoreleasing *)error { MP4FileHandle fileHandle = MP4Read(self.URL.fileSystemRepresentation); - if (!fileHandle) + if (!fileHandle) { return NO; + } MP4TrackId srcTrackId = self.trackId; - - MP4SampleId sampleId = 1; NSUInteger srtSampleNumber = 1; - - MP4Timestamp time = 0; uint32_t timeScale = MP4GetTrackTimeScale(fileHandle, srcTrackId); - uint64_t samples = MP4GetTrackNumberOfSamples(fileHandle, srcTrackId); NSMutableString *srtFile = [[NSMutableString alloc] init]; - + uint64_t r, g, b, a; MP4GetTrackIntegerProperty(fileHandle, srcTrackId, "mdia.minf.stbl.stsd.tx3g.fontColorRed", &r); MP4GetTrackIntegerProperty(fileHandle, srcTrackId, "mdia.minf.stbl.stsd.tx3g.fontColorGreen", &g); @@ -229,7 +227,13 @@ static void insertTagsFromStyleRecord(style_record record, NSMutableString *samp MP4GetTrackIntegerProperty(fileHandle, srcTrackId, "mdia.minf.stbl.stsd.tx3g.fontColorAlpha", &a); rgba_color dcolor = {r, g, b, a}; - for (sampleId = 1; sampleId <= samples; sampleId++) { + MP42SampleCursor *cursor = [[MP42SampleCursor alloc] initWithFileHandle:fileHandle trackId:srcTrackId]; + if (cursor == nil) { + goto fail; + } + + do { + uint8_t *pBytes = NULL; uint64_t pos = 0; uint32_t numBytes = 0; @@ -242,14 +246,14 @@ static void insertTagsFromStyleRecord(style_record record, NSMutableString *samp if (!MP4ReadSample(fileHandle, srcTrackId, - sampleId, + cursor.currentSampleId, &pBytes, &numBytes, &pStartTime, &sampleDuration, &renderingOffset, &isSyncSample)) { break; } - NSMutableString * sampleText = nil; + NSMutableString *sampleText = nil; NSUInteger textSampleLength = ((pBytes[0] << 8) & 0xff00) + pBytes[1]; if (textSampleLength) { @@ -261,13 +265,13 @@ static void insertTagsFromStyleRecord(style_record record, NSMutableString *samp // Let's see if there is an atom after the text sample pos = textSampleLength + 2; - while (pos + 8 < numBytes && sampleText) { - uint8_t *styleAtoms = pBytes + pos; - size_t atomLength = ((styleAtoms[0] << 24) & 0xff000000) + ((styleAtoms[1] << 16) & 0xff0000) + ((styleAtoms[2] << 8) & 0xff00) + styleAtoms[3]; + while (pos + 8 < numBytes && sampleText) { + uint8_t *styleAtoms = pBytes + pos; + size_t atomLength = ((styleAtoms[0] << 24) & 0xff000000) + ((styleAtoms[1] << 16) & 0xff0000) + ((styleAtoms[2] << 8) & 0xff00) + styleAtoms[3]; pos += atomLength; - if (pos <= numBytes) { + if (pos <= numBytes) { // If we found a style atom, read it and insert html-like tags in the new file if (styleAtoms[4] == 's' && styleAtoms[5] == 't' && styleAtoms[6] == 'y' && styleAtoms[7] == 'l') { uint16_t styleCount = ((styleAtoms[8] << 8) & 0xff00) + styleAtoms[9]; @@ -287,7 +291,7 @@ static void insertTagsFromStyleRecord(style_record record, NSMutableString *samp record.endChar += style_sample[3]; record.fontID = (style_sample[4] << 8) & 0xff00; record.fontID += style_sample[5]; - record.fontStyles = style_sample[6]; + record.fontStyles = style_sample[6]; record.fontSize = style_sample[7]; record.color.r = style_sample[8]; record.color.g = style_sample[9]; @@ -295,8 +299,9 @@ static void insertTagsFromStyleRecord(style_record record, NSMutableString *samp record.color.a = style_sample[11]; // Is the color different? - if (compare_color(record.color, dcolor)) + if (compare_color(record.color, dcolor)) { record.fontStyles |= kStyleColor; + } // Create a record to close the gap between two non-adiacent records if (record.startChar > previousRecord.endChar + 1) { @@ -335,34 +340,42 @@ static void insertTagsFromStyleRecord(style_record record, NSMutableString *samp record.right = (tbox_atom[6] << 8) & 0xff00; record.right += tbox_atom[7]; - if (record.top == 0) + if (record.top == 0) { tbox = YES; + } } } } if (textSampleLength) { - if ([sampleText characterAtIndex:[sampleText length] - 1] == '\n') + if ([sampleText characterAtIndex:[sampleText length] - 1] == '\n') { [sampleText deleteCharactersInRange:NSMakeRange([sampleText length] - 1, 1)]; + } if (sampleText) { + MP4Timestamp time = cursor.presentationTimeStamp; + [srtFile appendFormat:@"%lu\n%@ --> %@", (unsigned long)srtSampleNumber++, - SRTStringFromTime(time, timeScale, ','), SRTStringFromTime(time + sampleDuration, timeScale, ',')]; - if (tbox) + SRTStringFromTime(time, timeScale, ','), + SRTStringFromTime(time + cursor.currentSampleDuration, timeScale, ',')]; + if (tbox) { [srtFile appendString:@" X1:0"]; - if (forced) + } + if (forced) { [srtFile appendString:@" !!!"]; + } [srtFile appendString:@"\n"]; [srtFile appendString:sampleText]; [srtFile appendString:@"\n\n"]; } - } + } - time += sampleDuration; free(pBytes); - } + } while ([cursor stepInDecodeOrderByCount:1] > 0); + +fail: MP4Close(fileHandle, 0); return [srtFile writeToURL:url atomically:YES encoding:NSUTF8StringEncoding error:error]; diff --git a/MP42/SampleCursor.swift b/MP42/SampleCursor.swift new file mode 100644 index 0000000..f7e3264 --- /dev/null +++ b/MP42/SampleCursor.swift @@ -0,0 +1,204 @@ +// +// SampleCursor.swift +// MP42Foundation +// +// Created by Damiano Galassi on 12/03/2020. +// Copyright © 2020 Damiano Galassi. All rights reserved. +// + +import Foundation +import mp4v2 + +private struct Edit { + /// The media start time of the edit segment in track time scale units of the track in the mp4 file. + let mediaStart: MP4Timestamp + + /// The duration of the edit segment in track time scale units of the track in the mp4 file. + let duration: MP4Duration + + /// the dwell value of the specified track edit segment. + /// A value of true indicates that during this edit segment the media will be paused; + /// a value of false indicates that during this edit segment the media will be played at its normal rate. + let dwell: Bool + + /// Edit list version.0 is 32bit, 1 is 64bit. + let version: UInt64 + + var isEmpty: Bool { + switch (version, mediaStart) { + case (0, UInt64(UInt32.max)): + return true + case (1, UInt64.max): + return true + default: + return false + } + } +} + +@objc(MP42SampleCursor) public class SampleCursor: NSObject { + + private let fileHandle: MP4FileHandle + private let trackId: MP4TrackId + + private let edits: [Edit] + + private let movieTimescale: UInt32 + private let trackTimescale: UInt32 + + private let numOfSamples: UInt32 + + @objc public init?(fileHandle: MP4FileHandle, trackId: MP4TrackId) { + self.fileHandle = fileHandle + self.trackId = trackId + + self.movieTimescale = MP4GetTimeScale(fileHandle) + self.trackTimescale = MP4GetTrackTimeScale(fileHandle, trackId) + + self.numOfSamples = MP4GetTrackNumberOfSamples(fileHandle, trackId) + + if (self.numOfSamples == 0) { + return nil + } + + self.edits = Self.readEdits(fileHandle, trackId, movieTimescale) + + self.currentTime = 0 + + self.currentEdit = 0 + self.currentEditDuration = 0 + self.currentTrimStart = 0 + + self.currentSampleId = 1 + self.currentSampleDuration = 0 + + self.presentationTimeStamp = 0 + self.decodeTimeStamp = 0 + + super.init() + + reset() + } + + private static func readEdits(_ fileHandle: MP4FileHandle, _ trackId: MP4TrackId, _ movieTimescale: UInt32) -> [Edit] { + let numberOfEdits = MP4GetTrackNumberOfEdits(fileHandle, trackId) + + if (numberOfEdits > 0) { + let range = 1...numberOfEdits + + var editListVersion: UInt64 = 0 + MP4GetTrackIntegerProperty(fileHandle, trackId, "edts.elst.version", &editListVersion) + + let edits = range.map { editId -> Edit in + let mediaStart = MP4GetTrackEditMediaStart(fileHandle, trackId, editId) + let duration = MP4GetTrackEditDuration(fileHandle, trackId, editId) + let durationInTrackTimescale = MP4ConvertToTrackDuration(fileHandle, trackId, duration, movieTimescale) + let dwell = MP4GetTrackEditDwell(fileHandle, trackId, editId) + return Edit(mediaStart: mediaStart, duration: durationInTrackTimescale, dwell: dwell == 1, version: editListVersion) + } + + return edits + } else { + let duration = MP4GetTrackDuration(fileHandle, trackId) + return [Edit(mediaStart: 0, duration: duration, dwell: false, version: 1)] + } + } + + private var currentTime: MP4Timestamp + + private var currentEdit: Int + private var currentEditDuration: MP4Duration + private var currentTrimStart: MP4Duration + + @objc public private(set) var currentSampleId: MP4SampleId + @objc public private(set) var currentSampleDuration: MP4Duration + + @objc public private(set) var presentationTimeStamp: MP4Timestamp + @objc public private(set) var decodeTimeStamp: MP4Timestamp + + private func skipEmptyEdits() { + while currentEdit < edits.endIndex { + let edit = edits[currentEdit] + if edit.isEmpty { + currentTime += edit.duration + currentEdit += 1 + } else { + break + } + } + } + + private func resetMediaTime() { + let edit = edits[currentEdit] + currentSampleId = MP4GetSampleIdFromTime(fileHandle, trackId, edit.mediaStart, false) + let time = MP4GetSampleTime(fileHandle, trackId, currentSampleId) + + if edit.isEmpty == false { + currentTrimStart = edit.mediaStart - time + } else { + currentTrimStart = 0 + } + currentEditDuration = 0 + } + + private func nextEdit() { + currentEdit += 1 + guard currentEdit < edits.endIndex else { return } + skipEmptyEdits() + resetMediaTime() + } + + private func reset() { + currentTime = 0 + + currentEdit = 0 + currentEditDuration = 0 + currentTrimStart = 0 + + currentSampleId = 0 + currentSampleDuration = 0 + + presentationTimeStamp = 0 + decodeTimeStamp = 0 + + skipEmptyEdits() + + _ = stepInDecodeOrder(byCount: 1) + } + + @objc public func stepInDecodeOrder(byCount stepCount: Int64) -> Int64 { + guard currentEdit < edits.endIndex else { return 0 } + + var stepped: Int64 = 0 + + for _ in 0..= edit.duration || currentSampleId == numOfSamples) { + currentSampleDuration = edit.duration - currentEditDuration - currentTrimStart + nextEdit() + } else { + currentSampleDuration = duration - currentTrimStart + currentTrimStart = 0 + } + + currentEditDuration += currentSampleDuration + currentTime += currentSampleDuration + stepped += 1 + } + + return stepped + } +}