diff --git a/MP42/MP42BitmapSubConverter.h b/MP42/MP42BitmapSubConverter.h index 40ecaa6..8c65a39 100644 --- a/MP42/MP42BitmapSubConverter.h +++ b/MP42/MP42BitmapSubConverter.h @@ -6,7 +6,7 @@ // Copyright 2011 Damiano Galassi. All rights reserved. // -#import +#import #import "MP42ConverterProtocol.h" NS_ASSUME_NONNULL_BEGIN diff --git a/MP42/MP42MkvImporter.m b/MP42/MP42MkvImporter.m index f82fbe0..ca5e67b 100644 --- a/MP42/MP42MkvImporter.m +++ b/MP42/MP42MkvImporter.m @@ -11,7 +11,6 @@ #import "MP42Sample.h" #import "MP42File.h" -#import "MP42SubUtilities.h" #import "MP42Languages.h" #import "MatroskaParser.h" @@ -50,7 +49,6 @@ unsigned int buffer, samplesWritten, bufferFlush; MP42SampleBuffer *previousSample; - SBSubSerializer *ss; } @end @@ -323,10 +321,10 @@ static int readMkvPacket(struct StdIoStream *ioStream, TrackInfo *trackInfo, ui uint8_t *avcCAtom = (uint8_t *)malloc(mkvTrack->CodecPrivateSize); // mkv stores h.264 avcC in CodecPrivate memcpy(avcCAtom, mkvTrack->CodecPrivate, mkvTrack->CodecPrivateSize); if (mkvTrack->CodecPrivateSize >= 3) { - [(MP42VideoTrack*)newTrack setOrigProfile:avcCAtom[1]]; - [(MP42VideoTrack*)newTrack setNewProfile:avcCAtom[1]]; - [(MP42VideoTrack*)newTrack setOrigLevel:avcCAtom[3]]; - [(MP42VideoTrack*)newTrack setNewLevel:avcCAtom[3]]; + [(MP42VideoTrack *)newTrack setOrigProfile:avcCAtom[1]]; + [(MP42VideoTrack *)newTrack setNewProfile:avcCAtom[1]]; + [(MP42VideoTrack *)newTrack setOrigLevel:avcCAtom[3]]; + [(MP42VideoTrack *)newTrack setNewLevel:avcCAtom[3]]; } free(avcCAtom); } @@ -879,7 +877,6 @@ static NSString * TrackNameToString(TrackInfo *track) demuxHelper->previousSample = sample; #else [self enqueue:sample]; - [sample release]; #endif } } @@ -887,24 +884,19 @@ static NSString * TrackNameToString(TrackInfo *track) if (trackInfo->Type == TT_SUB) { if (readMkvPacket(_ioStream, trackInfo, FilePos, &frame, &FrameSize)) { if (strcmp(trackInfo->CodecID, "S_VOBSUB") && strcmp(trackInfo->CodecID, "S_HDMV/PGS")) { - if (!demuxHelper->ss) { - demuxHelper->ss = [[SBSubSerializer alloc] init]; - if (!strcmp(trackInfo->CodecID, "S_TEXT/ASS") || !strcmp(trackInfo->CodecID, "S_TEXT/SSA")) { - [demuxHelper->ss setSSA:YES]; - } - } - NSString *string = [[NSString alloc] initWithBytes:frame length:FrameSize encoding:NSUTF8StringEncoding]; - if (!strcmp(trackInfo->CodecID, "S_TEXT/ASS") || !strcmp(trackInfo->CodecID, "S_TEXT/SSA")) { - string = StripSSALine(string); - } + MP42SampleBuffer *sample = [[MP42SampleBuffer alloc] init]; + sample->data = frame; + sample->size = FrameSize; + sample->duration = EndTime / SCALE_FACTOR - StartTime / SCALE_FACTOR; + sample->offset = 0; + sample->decodeTimestamp = StartTime / SCALE_FACTOR; + sample->flags |= MP42SampleBufferFlagIsSync; + sample->trackId = demuxHelper->sourceID; + + [self enqueue:sample]; - if ([string length]) { - SBSubLine *sl = [[SBSubLine alloc] initWithLine:string start:StartTime / SCALE_FACTOR end:EndTime / SCALE_FACTOR]; - [demuxHelper->ss addLine:sl]; - } demuxHelper->samplesWritten++; - free(frame); } else { MP42SampleBuffer *nextSample = [[MP42SampleBuffer alloc] init]; @@ -1105,36 +1097,6 @@ static NSString * TrackNameToString(TrackInfo *track) } } - if (demuxHelper->ss) { - MP42SampleBuffer *sample = nil; - MP4TrackId dstTrackId = demuxHelper->sourceID; - SBSubSerializer *ss = demuxHelper->ss; - - [ss setFinished:YES]; - - while (![ss isEmpty] && !self.isCancelled) { - SBSubLine *sl = [ss getSerializedPacket]; - - if ([sl->line isEqualToString:@"\n"]) { - sample = copyEmptySubtitleSample(dstTrackId, sl->end_time - sl->begin_time, NO); - } - else { - sample = copySubtitleSample(dstTrackId, sl->line, sl->end_time - sl->begin_time, NO, NO, YES, CGSizeMake(0, 0), 0); - } - - if (!sample) { - break; - } - - demuxHelper->currentTime += sample->duration; - sample->decodeTimestamp = demuxHelper->currentTime; - - [self enqueue:sample]; - - demuxHelper->samplesWritten++; - } - } - if (demuxHelper->previousSample) { if (trackInfo->Type == TT_SUB) { demuxHelper->previousSample->duration = 100; diff --git a/MP42/MP42Muxer.m b/MP42/MP42Muxer.m index b622e87..7cfd936 100644 --- a/MP42/MP42Muxer.m +++ b/MP42/MP42Muxer.m @@ -15,6 +15,7 @@ #import "MP42Sample.h" #import "MP42AudioConverter.h" #import "MP42BitmapSubConverter.h" +#import "MP42TextSubConverter.h" #import "mp4v2.h" #import "MP42FormatUtilites.h" @@ -129,6 +130,18 @@ track.converter = subConverter; format = track.conversionSettings.format; } else if ([track isMemberOfClass:[MP42SubtitleTrack class]] && track.conversionSettings) { + MP42TextSubConverter *subConverter = [[MP42TextSubConverter alloc] initWithTrack:(MP42SubtitleTrack *)track + error:outError]; + + if (subConverter == nil) { + if (outError && *outError) { + [_logger writeErrorToLog:*outError]; + } + [unsupportedTracks addObject:track]; + continue; + } + + track.converter = subConverter; format = track.conversionSettings.format; } diff --git a/MP42/MP42SSAConverter.h b/MP42/MP42SSAConverter.h new file mode 100644 index 0000000..a35b8f3 --- /dev/null +++ b/MP42/MP42SSAConverter.h @@ -0,0 +1,19 @@ +// +// MP42SSAConverter.h +// SSA parser +// +// Created by Damiano Galassi on 02/10/2017. +// Copyright © 2017 Damiano Galassi. All rights reserved. +// + +#import + +@class MP42SSAParser; +@class MP42SSALine; + +@interface MP42SSAConverter : NSObject + +- (instancetype)initWithParser:(MP42SSAParser *)parser; +- (NSString *)convertLine:(MP42SSALine *)line; + +@end diff --git a/MP42/MP42SSAConverter.m b/MP42/MP42SSAConverter.m new file mode 100644 index 0000000..fa29ad9 --- /dev/null +++ b/MP42/MP42SSAConverter.m @@ -0,0 +1,174 @@ +// +// MP42SSAConverter.m +// SSA parser +// +// Created by Damiano Galassi on 02/10/2017. +// Copyright © 2017 Damiano Galassi. All rights reserved. +// + +#import "MP42SSAConverter.h" +#import "MP42SSAParser.h" + +typedef NS_ENUM(NSUInteger, MP42SSATokenType) { + MP42SSATokenTypeText, + MP42SSATokenTypeBoldOpen, + MP42SSATokenTypeBoldClose, + MP42SSATokenTypeItalicOpen, + MP42SSATokenTypeItalicClose, + MP42SSATokenTypeUnderlinedOpen, + MP42SSATokenTypeUnderlinedClose, + MP42SSATokenTypeDrawingOpen, + MP42SSATokenTypeDrawingClose +}; + +@interface MP42SSAToken : NSObject +{ +@public + MP42SSATokenType _type; + NSString *_text; +} +@end + +@implementation MP42SSAToken + +@end + +@interface MP42SSAConverter () + +@property (nonatomic, readonly) MP42SSAParser *parser; + +@end + +@implementation MP42SSAConverter + +- (instancetype)initWithParser:(MP42SSAParser *)parser +{ + self = [super init]; + if (self) { + _parser = parser; + } + return self; +} + +- (NSArray *)convertedLines +{ + NSMutableArray *result = [NSMutableArray array]; + for (MP42SSALine *line in _parser.lines) { + NSString *convertedLine = [self convertLine:line]; + if (convertedLine.length) { + [result addObject:convertedLine]; + } + } + return result; +} + +#pragma mark - Conversion + +- (NSString *)convertLine:(MP42SSALine *)line +{ + NSMutableString *result = [NSMutableString string]; + NSArray *tokens = tokenizer(line.text); + + BOOL drawingMode = NO; + + for (MP42SSAToken *token in tokens) { + NSString *textToAppend = nil; + + if (token->_type == MP42SSATokenTypeText) { + textToAppend = token->_text; + } + else if (token->_type == MP42SSATokenTypeBoldOpen) { + textToAppend = @""; + } + else if (token->_type == MP42SSATokenTypeBoldClose) { + textToAppend = @""; + } + else if (token->_type == MP42SSATokenTypeItalicOpen) { + textToAppend = @""; + } + else if (token->_type == MP42SSATokenTypeItalicClose) { + textToAppend = @""; + } + else if (token->_type == MP42SSATokenTypeUnderlinedOpen) { + textToAppend = @""; + } + else if (token->_type == MP42SSATokenTypeUnderlinedClose) { + textToAppend = @""; + } + else if (token->_type == MP42SSATokenTypeDrawingOpen) { + drawingMode = YES; + } + else if (token->_type == MP42SSATokenTypeDrawingClose) { + drawingMode = NO; + } + + if (textToAppend && drawingMode == NO) { + [result appendString:textToAppend]; + } + } + + [result replaceOccurrencesOfString:@"\\N" withString:@"\n" options:NSLiteralSearch range:NSMakeRange(0, result.length)]; + [result replaceOccurrencesOfString:@"\\n" withString:@"\n" options:NSLiteralSearch range:NSMakeRange(0, result.length)]; + + if (result.length) { + if (line.style.bold) { + [result insertString:@"" atIndex:0]; + } + if (line.style.underline) { + [result insertString:@"" atIndex:0]; + } + if (line.style.italic) { + [result insertString:@"" atIndex:0]; + } + } + + return result; +} + +static inline NSArray *tokenizer(NSString *line) +{ + NSScanner *sc = [NSScanner scannerWithString:line]; + NSMutableArray *tokens = [NSMutableArray array]; + NSString *string; + + while ([sc scanUpToString:@"{" intoString:&string] || [sc scanString:@"{" intoString:&string]) { + if (![string hasPrefix:@"{"]) { + addToken(string, MP42SSATokenTypeText, tokens); + } + + [sc scanString:@"{" intoString:nil]; + + if ([sc scanUpToString:@"}" intoString:&string] || [sc scanString:@"}" intoString:&string]) { + NSScanner *tagSc = [NSScanner scannerWithString:string]; + + while ([tagSc scanUpToString:@"\\" intoString:&string] || [tagSc scanString:@"\\" intoString:&string]) { + if (![string hasPrefix:@"\\"]) { + [sc scanString:@"\\" intoString:nil]; + + if ([string hasPrefix:@"p"]) { + if ([string hasPrefix:@"p0"]) { + addToken(string, MP42SSATokenTypeDrawingClose, tokens); + } + else if (![string hasPrefix:@"pos"]) { + addToken(string, MP42SSATokenTypeDrawingOpen, tokens); + } + } + } + } + + [sc scanString:@"}" intoString:nil]; + } + } + + return tokens; +} + +static inline void addToken(NSString *text, MP42SSATokenType type, NSMutableArray *tokens) +{ + MP42SSAToken *token = [[MP42SSAToken alloc] init]; + token->_text = text; + token->_type = type; + [tokens addObject:token]; +} + +@end diff --git a/MP42/MP42SSAImporter.m b/MP42/MP42SSAImporter.m index 27ff3d7..caf63b2 100644 --- a/MP42/MP42SSAImporter.m +++ b/MP42/MP42SSAImporter.m @@ -10,7 +10,10 @@ #import "MP42FileImporter+Private.h" #import "MP42File.h" + #import "MP42SSAParser.h" +#import "MP42SSAConverter.h" + #import "MP42SubUtilities.h" #import "MP42Languages.h" @@ -43,6 +46,14 @@ NSString *stringFromFileAtURL = [NSString stringWithContentsOfURL:fileURL encoding:NSUTF8StringEncoding error:NULL]; + if (!stringFromFileAtURL) { + if (outError) { + *outError = MP42Error(MP42LocalizedString(@"The file could not be opened.", @"ssa error message"), + MP42LocalizedString(@"The file is not a ssa file, or it does not contain any subtitles.", @"ssa error message"), 100); + } + return nil; + } + // Check if a 10.10 only class is available, NSLinguisticTagger crashes on 10.9 // if the string contains some characters. if ([newTrack.language isEqualToString:@"und"] && NSClassFromString(@"NSVisualEffectView")) { @@ -98,21 +109,8 @@ } return nil; } - - _ss = [[SBSubSerializer alloc] init]; - [_ss setSSA:YES]; - - for (MP42SSALine *line in _parser.lines) { - SBSubLine *sl = [[SBSubLine alloc] initWithLine:line.text start:line.start end: line.end]; - [_ss addLine:sl]; - } - [_ss setFinished:YES]; - if ([_ss forced]) { - newTrack.someSamplesAreForced = YES; - } - - newTrack.duration = _parser.lines.lastObject.end; + newTrack.duration = _parser.duration; [self addTrack:newTrack]; } @@ -138,12 +136,26 @@ - (void)demux { @autoreleasepool { - MP42SampleBuffer *sample; + + MP42SSAConverter *converter = [[MP42SSAConverter alloc] initWithParser:_parser]; + + _ss = [[SBSubSerializer alloc] init]; + [_ss setSSA:YES]; + + for (MP42SSALine *line in _parser.lines) { + NSString *text = [converter convertLine:line]; + if (text.length) { + SBSubLine *sl = [[SBSubLine alloc] initWithLine:text start:line.start end: line.end]; + [_ss addLine:sl]; + } + } + [_ss setFinished:YES]; for (MP42SubtitleTrack *track in self.inputTracks) { CGSize trackSize; trackSize.width = track.trackWidth; trackSize.height = track.trackHeight; + MP42SampleBuffer *sample; while (!_ss.isEmpty && !self.isCancelled) { SBSubLine *sl = [_ss getSerializedPacket]; diff --git a/MP42/MP42SSAParser.h b/MP42/MP42SSAParser.h index 2393abf..09338ca 100644 --- a/MP42/MP42SSAParser.h +++ b/MP42/MP42SSAParser.h @@ -1,6 +1,6 @@ // // MP42SSAParser.h -// Subler +// SSA parser // // Created by Damiano Galassi on 02/10/2017. // Copyright © 2017 Damiano Galassi. All rights reserved. @@ -8,22 +8,63 @@ #import +NS_ASSUME_NONNULL_BEGIN + +@interface MP42SSAStyle : NSObject + +@property (nonatomic, readonly) NSString *name; +@property (nonatomic, readonly, nullable) NSString *fontName; +@property (nonatomic, readonly) int fontSize; +@property (nonatomic, readonly) long primaryColour; +@property (nonatomic, readonly) long secondaryColour; +@property (nonatomic, readonly) long outlineColour; +@property (nonatomic, readonly) long backColour; +@property (nonatomic, readonly) BOOL bold; +@property (nonatomic, readonly) BOOL italic; +@property (nonatomic, readonly) BOOL underline; +@property (nonatomic, readonly) BOOL strikeOut; +@property (nonatomic, readonly) float scaleX; +@property (nonatomic, readonly) float scaleY; +@property (nonatomic, readonly) int spacing; +@property (nonatomic, readonly) float angle; +@property (nonatomic, readonly) short borderStyle; +@property (nonatomic, readonly) short outline; +@property (nonatomic, readonly) short shadow; +@property (nonatomic, readonly) short alignment; +@property (nonatomic, readonly) int marginL; +@property (nonatomic, readonly) int marginR; +@property (nonatomic, readonly) int marginV; +@property (nonatomic, readonly) int alphaLevel; +@property (nonatomic, readonly) int encoding; + +@end + @interface MP42SSALine : NSObject -@property (nonatomic, readwrite) unsigned start; -@property (nonatomic, readwrite) unsigned end; -@property (nonatomic, readwrite) NSString *text; +@property (nonatomic, readonly) int layer; +@property (nonatomic, readonly) unsigned start; +@property (nonatomic, readonly) unsigned end; +@property (nonatomic, readonly, nullable) MP42SSAStyle *style; +@property (nonatomic, readonly, nullable) NSString *name; +@property (nonatomic, readonly) int marginL; +@property (nonatomic, readonly) int marginR; +@property (nonatomic, readonly) int marginV; +@property (nonatomic, readonly, nullable) NSString *effect; +@property (nonatomic, readonly, nullable) NSString *text; @end @interface MP42SSAParser : NSObject - (instancetype)initWithString:(NSString *)string; -- (instancetype)initWithHeader:(NSString *)header; +- (instancetype)initWithMKVHeader:(NSString *)header; @property (nonatomic, readonly) NSArray *lines; +@property (nonatomic, readonly) NSDictionary *styles; +@property (nonatomic, readonly) unsigned duration; -- (void)addLine:(NSString *)line; +- (MP42SSALine *)addLine:(NSString *)line; @end +NS_ASSUME_NONNULL_END diff --git a/MP42/MP42SSAParser.m b/MP42/MP42SSAParser.m index 5d11561..35bcf7c 100644 --- a/MP42/MP42SSAParser.m +++ b/MP42/MP42SSAParser.m @@ -1,6 +1,6 @@ // // MP42SSAParser.m -// Subler +// SSA parser // // Created by Damiano Galassi on 02/10/2017. // Copyright © 2017 Damiano Galassi. All rights reserved. @@ -8,35 +8,10 @@ #import "MP42SSAParser.h" -@interface MP42SSAStyle : NSObject +@interface MP42SSAStyle () - (instancetype)initWith:(NSArray *)style formats:(NSArray *)format; -@property (nonatomic, readwrite) NSString *name; -@property (nonatomic, readwrite) NSString *fontName; -@property (nonatomic, readwrite) int fontSize; -@property (nonatomic, readwrite) long primaryColour; -@property (nonatomic, readwrite) long secondaryColour; -@property (nonatomic, readwrite) long outlineColour; -@property (nonatomic, readwrite) long backColour; -@property (nonatomic, readwrite) BOOL bold; -@property (nonatomic, readwrite) BOOL italic; -@property (nonatomic, readwrite) BOOL underline; -@property (nonatomic, readwrite) BOOL strikeOut; -@property (nonatomic, readwrite) float scaleX; -@property (nonatomic, readwrite) float scaleY; -@property (nonatomic, readwrite) int spacing; -@property (nonatomic, readwrite) float angle; -@property (nonatomic, readwrite) short borderStyle; -@property (nonatomic, readwrite) short outline; -@property (nonatomic, readwrite) short shadow; -@property (nonatomic, readwrite) short alignment; -@property (nonatomic, readwrite) int marginL; -@property (nonatomic, readwrite) int marginR; -@property (nonatomic, readwrite) int marginV; -@property (nonatomic, readwrite) int alphaLevel; -@property (nonatomic, readwrite) int encoding; - @end @implementation MP42SSAStyle @@ -47,11 +22,11 @@ if (self) { NSUInteger stylesCount = style.count; NSUInteger formatsCount = format.count; - + for (NSUInteger index = 0; index < stylesCount && index < formatsCount; index += 1) { NSString *value = style[index]; NSString *formatName = format[index]; - + if ([formatName isEqualToString:@"Name"]) { _name = value; } @@ -76,13 +51,13 @@ _backColour = value.intValue; } else if ([formatName isEqualToString:@"Bold"]) { - _bold = value.intValue == -1 ? YES : NO; + _bold = value.intValue > 0; // Hack } else if ([formatName isEqualToString:@"Italic"]) { - _italic = value.intValue == -1 ? YES : NO; + _italic = value.intValue != 0; } else if ([formatName isEqualToString:@"Underline"]) { - _underline = value.intValue == -1 ? YES : NO; + _underline = value.intValue != 0; } else if ([formatName isEqualToString:@"StrikeOut"]) { _strikeOut = value.intValue == -1 ? YES : NO; @@ -127,8 +102,12 @@ _encoding = value.intValue; } } + + if (_name == nil) { + return nil; + } } - + return self; } @@ -137,32 +116,24 @@ @interface MP42SSALine () -- (instancetype)initWithString:(NSString *)string format:(NSArray *)format; - -@property (nonatomic, readwrite) int layer; -@property (nonatomic, readwrite) NSString *style; -@property (nonatomic, readwrite) NSString *name; -@property (nonatomic, readwrite) int marginL; -@property (nonatomic, readwrite) int marginR; -@property (nonatomic, readwrite) int marginV; -@property (nonatomic, readwrite) NSString *effect; +- (instancetype)initWithString:(NSString *)string format:(NSArray *)format styles:(NSDictionary *)styles skipEventType:(BOOL)skipEventType; @end @implementation MP42SSALine -- (instancetype)initWithString:(NSString *)string format:(NSArray *)format +- (instancetype)initWithString:(NSString *)string format:(NSArray *)format styles:(NSDictionary *)styles skipEventType:(BOOL)skipEventType { self = [super init]; if (self) { NSUInteger formatsCount = format.count; - NSArray *values = [self parse:string count:formatsCount]; + NSArray *values = [self parse:string count:formatsCount skipEventType:skipEventType]; NSUInteger valuesCount = values.count; - + for (NSUInteger index = 0; index < valuesCount && index < formatsCount; index += 1) { NSString *value = values[index]; NSString *formatName = format[index]; - + if ([formatName isEqualToString:@"Layer"]) { _layer = value.intValue; } @@ -173,7 +144,7 @@ _end = ParseSubTime(value.UTF8String, 1000, NO); } else if ([formatName isEqualToString:@"Style"]) { - _style = value; + _style = styles[value]; } else if ([formatName isEqualToString:@"Name"]) { _name = value; @@ -194,21 +165,25 @@ _text = value; } } + + if (!_text) { + return nil; + } } - + return self; } -- (NSArray *)parse:(NSString *)string count:(NSUInteger)count +- (NSArray *)parse:(NSString *)string count:(NSUInteger)count skipEventType:(BOOL)skipEventType { NSScanner *sc = [NSScanner scannerWithString:string]; NSMutableArray *valuesArray = [NSMutableArray array]; - - if ([sc scanUpToString:@"Dialogue:" intoString:nil] || [sc scanString:@"Dialogue:" intoString:nil]) { + + if (skipEventType || [sc scanUpToString:@"Dialogue:" intoString:nil] || [sc scanString:@"Dialogue:" intoString:nil]) { [sc scanString:@"Dialogue:" intoString:nil]; - + NSString *value; - + for (NSUInteger index = 0; index < count - 1; index += 1) { if ([sc scanUpToString:@"," intoString:&value]) { [valuesArray addObject:value]; @@ -218,13 +193,13 @@ } [sc scanString:@"," intoString:nil]; } - + value = [sc.string substringFromIndex:sc.scanLocation]; if (value) { [valuesArray addObject:value]; } } - + return valuesArray; } @@ -233,30 +208,30 @@ static unsigned ParseSubTime(const char *time, unsigned secondScale, BOOL hasSig unsigned hour, minute, second, subsecond, timeval; char separator[3]; int sign = 1; - + if (hasSign && *time == '-') { sign = -1; time++; } - + if (sscanf(time, "%u:%u:%u%[,.:]%u", &hour, &minute, &second, separator, &subsecond) < 5) { subsecond = 0; if (sscanf(time, "%u:%u:%u", &hour, &minute, &second) < 3) { return 0; } } - + if (second > 60) { second = 0; } - + while (subsecond > secondScale) { subsecond /= 10; } - + timeval = hour * 60 * 60 + minute * 60 + second; timeval = secondScale * timeval + subsecond; - + return timeval * sign; } @@ -266,7 +241,6 @@ static unsigned ParseSubTime(const char *time, unsigned secondScale, BOOL hasSig @interface MP42SSAParser () @property (nonatomic, readonly) NSString *info; -@property (nonatomic, readonly) NSArray *styles; @property (nonatomic, readonly) NSArray *format; @property (nonatomic, readonly) NSMutableArray *lines_internal; @@ -279,7 +253,7 @@ static unsigned ParseSubTime(const char *time, unsigned secondScale, BOOL hasSig { self = [super init]; if (self) { - _styles = @[]; + _styles = @{}; _lines_internal = [NSMutableArray array]; } return self; @@ -295,12 +269,13 @@ static unsigned ParseSubTime(const char *time, unsigned secondScale, BOOL hasSig return self; } -- (instancetype)initWithHeader:(NSString *)header +- (instancetype)initWithMKVHeader:(NSString *)header { NSParameterAssert(header); self = [self init]; if (self) { [self parseHeader:header]; + _format = @[@"ReadOrder", @"Layer", @"Style", @"Name", @"MarginL",@ "MarginR", @"MarginV", @"Effect", @"Text"]; } return self; } @@ -318,18 +293,18 @@ static unsigned ParseSubTime(const char *time, unsigned secondScale, BOOL hasSig NSString *info; NSString *styles; NSString *format; - + NSScanner *sc = [NSScanner scannerWithString:header]; [sc setCharactersToBeSkipped:nil]; - + if ([sc scanUpToString:@"[V4+ Styles]" intoString:&info]) { _info = [self parseInfo:info]; } - + if ([sc scanUpToString:@"[Events]" intoString:&styles]) { _styles = [self parseStyles:styles]; } - + format = [sc.string substringFromIndex:sc.scanLocation]; if (format.length) { _format = [self parseFormat:format]; @@ -341,12 +316,12 @@ static unsigned ParseSubTime(const char *time, unsigned secondScale, BOOL hasSig return info; } -- (NSArray *)parseStyles:(NSString *)styles +- (NSDictionary *)parseStyles:(NSString *)styles { NSScanner *sc = [NSScanner scannerWithString:styles]; NSMutableArray *formatsArray = [NSMutableArray array]; - NSMutableArray *stylesArray = [NSMutableArray array]; - + NSMutableDictionary *stylesDict = [NSMutableDictionary dictionary]; + if ([sc scanUpToString:@"Format:" intoString:nil] || [sc scanString:@"Format:" intoString:nil]) { [sc scanString:@"Format:" intoString:nil]; NSString *formats; @@ -359,35 +334,35 @@ static unsigned ParseSubTime(const char *time, unsigned secondScale, BOOL hasSig } } } - + while ([sc scanUpToString:@"Style:" intoString:nil] || [sc scanString:@"Style:" intoString:nil]) { [sc scanString:@"Style:" intoString:nil]; NSString *styles; if ([sc scanUpToString:@"\n" intoString:&styles]) { NSMutableArray *stylesValueArray = [NSMutableArray array]; - + NSScanner *stylesScanner = [NSScanner scannerWithString:styles]; NSString *styleValue; while ([stylesScanner scanUpToString:@"," intoString:&styleValue]) { [stylesScanner scanString:@"," intoString:nil]; [stylesValueArray addObject:styleValue]; } - + MP42SSAStyle *style = [[MP42SSAStyle alloc] initWith:stylesValueArray formats:formatsArray]; if (style) { - [stylesArray addObject:style]; + stylesDict[style.name] = style; } } } - - return stylesArray; + + return stylesDict; } - (NSArray *)parseFormat:(NSString *)format { NSScanner *sc = [NSScanner scannerWithString:format]; NSMutableArray *formatsArray = [NSMutableArray array]; - + if ([sc scanUpToString:@"Format:" intoString:nil] || [sc scanString:@"Format:" intoString:nil]) { [sc scanString:@"Format:" intoString:nil]; NSString *formats; @@ -400,7 +375,7 @@ static unsigned ParseSubTime(const char *time, unsigned secondScale, BOOL hasSig } } } - + return formatsArray; } @@ -408,19 +383,23 @@ static unsigned ParseSubTime(const char *time, unsigned secondScale, BOOL hasSig { NSScanner *sc = [NSScanner scannerWithString:lines]; NSMutableArray *linesArray = [NSMutableArray array]; - + [sc scanUpToString:@"[Events]" intoString:nil]; [sc scanUpToString:@"Dialogue: " intoString:nil]; - + NSString *lineString; - + while ([sc scanUpToString:@"\n" intoString:&lineString]) { - MP42SSALine *line = [[MP42SSALine alloc] initWithString:lineString format:_format]; + MP42SSALine *line = [[MP42SSALine alloc] initWithString:lineString format:_format styles:_styles skipEventType:NO]; if (line) { [linesArray addObject:line]; + unsigned end = line.end; + if (end > _duration) { + _duration = end; + } } } - + _lines_internal = linesArray; } @@ -430,12 +409,13 @@ static unsigned ParseSubTime(const char *time, unsigned secondScale, BOOL hasSig return [_lines_internal copy]; } -- (void)addLine:(NSString *)lineString +- (MP42SSALine *)addLine:(NSString *)lineString { - MP42SSALine *line = [[MP42SSALine alloc] initWithString:lineString format:_format]; + MP42SSALine *line = [[MP42SSALine alloc] initWithString:lineString format:_format styles:_styles skipEventType:YES]; if (line) { [_lines_internal addObject:line]; } + return line; } @end diff --git a/MP42/MP42TextSubConverter.h b/MP42/MP42TextSubConverter.h new file mode 100644 index 0000000..8cc948c --- /dev/null +++ b/MP42/MP42TextSubConverter.h @@ -0,0 +1,28 @@ +// +// MP42TextSubConverter.h +// MP42Foundation +// +// Created by Damiano Galassi on 02/10/2017. +// Copyright © 2017 Damiano Galassi. All rights reserved. +// + +#import +#import "MP42ConverterProtocol.h" + +NS_ASSUME_NONNULL_BEGIN + +@class MP42SampleBuffer; +@class MP42SubtitleTrack; + +@interface MP42TextSubConverter : NSObject + +- (instancetype)initWithTrack:(MP42SubtitleTrack *)track error:(NSError **)outError; + +- (void)addSample:(MP42SampleBuffer *)sample; +- (nullable MP42SampleBuffer *)copyEncodedSample; + +- (void)cancel; + +@end + +NS_ASSUME_NONNULL_END diff --git a/MP42/MP42TextSubConverter.m b/MP42/MP42TextSubConverter.m new file mode 100644 index 0000000..9fd87cd --- /dev/null +++ b/MP42/MP42TextSubConverter.m @@ -0,0 +1,149 @@ +// +// MP42TextSubConverter.m +// MP42Foundation +// +// Created by Damiano Galassi on 02/10/2017. +// Copyright © 2017 Damiano Galassi. All rights reserved. +// + +#import "MP42TextSubConverter.h" + +#import "MP42FileImporter.h" +#import "MP42FileImporter+Private.h" + +#import "MP42Track.h" +#import "MP42SubtitleTrack.h" +#import "MP42Track+Private.h" + +#import "MP42Fifo.h" +#import "MP42Sample.h" + +#import "MP42SubUtilities.h" +#import "MP42SSAParser.h" +#import "MP42SSAConverter.h" + +@interface MP42TextSubConverter () + +@property (nonatomic, readonly) NSThread *decoderThread; +@property (nonatomic, readonly) dispatch_semaphore_t done; + +@property (nonatomic, readonly) MP42Fifo *inputSamplesBuffer; + +@property (nonatomic, readonly) SBSubSerializer *ss; + +@property (nonatomic, readonly) MP42SSAParser *parser; +@property (nonatomic, readonly) MP42SSAConverter *converter; + +@property (nonatomic, readonly) MP4TrackId trackID; + +@property (nonatomic, readonly) _Atomic int32_t finished; + +@end + +@implementation MP42TextSubConverter + +- (void)TextConverterThreadMainRoutine +{ + @autoreleasepool { + MP42SampleBuffer *sampleBuffer = nil; + + while ((sampleBuffer = [_inputSamplesBuffer dequeueAndWait])) { + @autoreleasepool { + + if (sampleBuffer->flags & MP42SampleBufferFlagEndOfFile) { + [_ss setFinished:YES]; + _finished = 1; + break; + } + + NSString *text = [[NSString alloc] initWithBytes:sampleBuffer->data + length:sampleBuffer->size + encoding:NSUTF8StringEncoding]; + + if (_converter && text.length) { + if (_converter) { + MP42SSALine *SSAline = [_parser addLine:text]; + text = [_converter convertLine:SSAline]; + } + } + + if (text.length) { + SBSubLine *sl = [[SBSubLine alloc] initWithLine:text + start:sampleBuffer->decodeTimestamp + end:sampleBuffer->decodeTimestamp + sampleBuffer->duration]; + [_ss addLine:sl]; + } + } + } + dispatch_semaphore_signal(_done); + } +} + +- (instancetype)initWithTrack:(MP42SubtitleTrack *)track error:(NSError **)outError +{ + if ((self = [super init])) { + MP42SubtitleCodecType format = track.format; + + if (format == kMP42SubtitleCodecType_SSA) { + NSData *cookie = [track.importer magicCookieForTrack:track]; + NSString *cookieString = [[NSString alloc] initWithData:cookie encoding:NSUTF8StringEncoding]; + _parser = [[MP42SSAParser alloc] initWithMKVHeader:cookieString]; + _converter = [[MP42SSAConverter alloc] initWithParser:_parser]; + } + + _ss = [[SBSubSerializer alloc] init]; + _inputSamplesBuffer = [[MP42Fifo alloc] initWithCapacity:100]; + _done = dispatch_semaphore_create(0); + _trackID = track.sourceId; + + _decoderThread = [[NSThread alloc] initWithTarget:self selector:@selector(TextConverterThreadMainRoutine) object:nil]; + [_decoderThread setName:@"Text Converter"]; + [_decoderThread start]; + } + + return self; +} + +- (void)addSample:(MP42SampleBuffer *)sample +{ + [_inputSamplesBuffer enqueue:sample]; +} + +- (nullable MP42SampleBuffer *)copyEncodedSample +{ + if (_finished) { + if (!_ss.isEmpty) { + SBSubLine *sl = [_ss getSerializedPacket]; + MP42SampleBuffer *sample; + + if ([sl->line isEqualToString:@"\n"]) { + sample = copyEmptySubtitleSample(_trackID, sl->end_time - sl->begin_time, NO); + } + else { + sample = copySubtitleSample(_trackID, sl->line, sl->end_time - sl->begin_time, sl->forced, NO, YES, CGSizeMake(0, 0), 0); + } + + return sample; + } + else { + MP42SampleBuffer *sample = [[MP42SampleBuffer alloc] init]; + sample->flags |= MP42SampleBufferFlagEndOfFile; + sample->trackId = _trackID; + + _finished = 0; + + return sample; + } + } + + return nil; +} + +- (void)cancel +{ + [_inputSamplesBuffer cancel]; + dispatch_semaphore_wait(_done, DISPATCH_TIME_FOREVER); +} + +@end + diff --git a/MP42Foundation.xcodeproj/project.pbxproj b/MP42Foundation.xcodeproj/project.pbxproj index 78f9263..8335b43 100644 --- a/MP42Foundation.xcodeproj/project.pbxproj +++ b/MP42Foundation.xcodeproj/project.pbxproj @@ -95,6 +95,14 @@ A941A7B51DA7B08600FB2A7C /* MP42MetadataFormat.h in Headers */ = {isa = PBXBuildFile; fileRef = A941A7B21DA7B08600FB2A7C /* MP42MetadataFormat.h */; }; A941A7B61DA7B08600FB2A7C /* MP42MetadataFormat.m in Sources */ = {isa = PBXBuildFile; fileRef = A941A7B31DA7B08600FB2A7C /* MP42MetadataFormat.m */; }; A941A7B71DA7B08600FB2A7C /* MP42MetadataFormat.m in Sources */ = {isa = PBXBuildFile; fileRef = A941A7B31DA7B08600FB2A7C /* MP42MetadataFormat.m */; }; + A941C9561F82996600FC5E8D /* MP42TextSubConverter.h in Headers */ = {isa = PBXBuildFile; fileRef = A941C9541F82996600FC5E8D /* MP42TextSubConverter.h */; }; + A941C9571F82996600FC5E8D /* MP42TextSubConverter.h in Headers */ = {isa = PBXBuildFile; fileRef = A941C9541F82996600FC5E8D /* MP42TextSubConverter.h */; }; + A941C9581F82996600FC5E8D /* MP42TextSubConverter.m in Sources */ = {isa = PBXBuildFile; fileRef = A941C9551F82996600FC5E8D /* MP42TextSubConverter.m */; }; + A941C9591F82996600FC5E8D /* MP42TextSubConverter.m in Sources */ = {isa = PBXBuildFile; fileRef = A941C9551F82996600FC5E8D /* MP42TextSubConverter.m */; }; + A941C95E1F82A9B900FC5E8D /* MP42SSAConverter.h in Headers */ = {isa = PBXBuildFile; fileRef = A941C95C1F82A9B800FC5E8D /* MP42SSAConverter.h */; }; + A941C95F1F82A9B900FC5E8D /* MP42SSAConverter.h in Headers */ = {isa = PBXBuildFile; fileRef = A941C95C1F82A9B800FC5E8D /* MP42SSAConverter.h */; }; + A941C9601F82A9B900FC5E8D /* MP42SSAConverter.m in Sources */ = {isa = PBXBuildFile; fileRef = A941C95D1F82A9B800FC5E8D /* MP42SSAConverter.m */; }; + A941C9611F82A9B900FC5E8D /* MP42SSAConverter.m in Sources */ = {isa = PBXBuildFile; fileRef = A941C95D1F82A9B800FC5E8D /* MP42SSAConverter.m */; }; A9422FC51D4917AF000DB435 /* audio_resample.c in Sources */ = {isa = PBXBuildFile; fileRef = A9422FC31D4917AF000DB435 /* audio_resample.c */; }; A9422FC61D4917AF000DB435 /* audio_resample.c in Sources */ = {isa = PBXBuildFile; fileRef = A9422FC31D4917AF000DB435 /* audio_resample.c */; }; A9422FC71D4917AF000DB435 /* audio_resample.h in Headers */ = {isa = PBXBuildFile; fileRef = A9422FC41D4917AF000DB435 /* audio_resample.h */; }; @@ -319,6 +327,10 @@ A925AAAE18379AF800BE84D4 /* MP42Utilities.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = MP42Utilities.m; sourceTree = ""; }; A941A7B21DA7B08600FB2A7C /* MP42MetadataFormat.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = MP42MetadataFormat.h; sourceTree = ""; }; A941A7B31DA7B08600FB2A7C /* MP42MetadataFormat.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = MP42MetadataFormat.m; sourceTree = ""; }; + A941C9541F82996600FC5E8D /* MP42TextSubConverter.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = MP42TextSubConverter.h; sourceTree = ""; }; + A941C9551F82996600FC5E8D /* MP42TextSubConverter.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = MP42TextSubConverter.m; sourceTree = ""; }; + A941C95C1F82A9B800FC5E8D /* MP42SSAConverter.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = MP42SSAConverter.h; sourceTree = ""; }; + A941C95D1F82A9B800FC5E8D /* MP42SSAConverter.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = MP42SSAConverter.m; sourceTree = ""; }; A9422FC31D4917AF000DB435 /* audio_resample.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = audio_resample.c; sourceTree = ""; }; A9422FC41D4917AF000DB435 /* audio_resample.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = audio_resample.h; sourceTree = ""; }; A947BA9A1824F0B3004C734B /* Ratings.json */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.json; path = Ratings.json; sourceTree = ""; }; @@ -755,6 +767,8 @@ A9B9C2371823923100416A4E /* MP42HtmlParser.m */, A9ED5B091F824A9A00E0E4FA /* MP42SSAParser.h */, A9ED5B0C1F824A9B00E0E4FA /* MP42SSAParser.m */, + A941C95C1F82A9B800FC5E8D /* MP42SSAConverter.h */, + A941C95D1F82A9B800FC5E8D /* MP42SSAConverter.m */, A96523431BAC315900E994E0 /* NSString+MP42Additions.h */, A96523441BAC315900E994E0 /* NSString+MP42Additions.m */, ); @@ -772,6 +786,8 @@ A9B9C2451823923100416A4E /* MP42OCRWrapper.mm */, A9B9C2251823923100416A4E /* MP42BitmapSubConverter.h */, A9B9C2261823923100416A4E /* MP42BitmapSubConverter.m */, + A941C9541F82996600FC5E8D /* MP42TextSubConverter.h */, + A941C9551F82996600FC5E8D /* MP42TextSubConverter.m */, A908010C1D4B83A3002B6950 /* MP42AudioDecoder.h */, A908010D1D4B83A3002B6950 /* MP42AudioDecoder.m */, A908010E1D4B83A3002B6950 /* MP42AudioEncoder.h */, @@ -801,10 +817,12 @@ A9ED5B161F824BC100E0E4FA /* MP42SSAImporter.h in Headers */, A9422FC81D4917AF000DB435 /* audio_resample.h in Headers */, A917286719FD2BCE00348DF8 /* MP42Logging.h in Headers */, + A941C95F1F82A9B900FC5E8D /* MP42SSAConverter.h in Headers */, A9ED5B0E1F824A9B00E0E4FA /* MP42SSAParser.h in Headers */, A99FCBC51BAD65EF0058E27A /* MP42Track+Private.h in Headers */, A9AEFE161B9B111B00771292 /* MP42FileImporter+Private.h in Headers */, A96523461BAC315900E994E0 /* NSString+MP42Additions.h in Headers */, + A941C9571F82996600FC5E8D /* MP42TextSubConverter.h in Headers */, A908011A1D4B83A3002B6950 /* MP42AudioUnit.h in Headers */, A9022A951D6F3FD9005F0920 /* MP42MetadataItem.h in Headers */, ); @@ -839,6 +857,7 @@ A99FCBC41BAD65EF0058E27A /* MP42Track+Private.h in Headers */, A925AAAF18379AF800BE84D4 /* MP42Utilities.h in Headers */, A9B9C28F1823923200416A4E /* MP42OCRWrapper.h in Headers */, + A941C9561F82996600FC5E8D /* MP42TextSubConverter.h in Headers */, A9B9C2811823923200416A4E /* MP42HtmlParser.h in Headers */, A9B9C2AA1823923200416A4E /* MatroskaParser.h in Headers */, A9B9C26E1823923200416A4E /* MP42AVFImporter.h in Headers */, @@ -854,6 +873,7 @@ A91711E6187D547D00459495 /* MP42PreviewGenerator.h in Headers */, A9B9C2951823923200416A4E /* MP42SrtImporter.h in Headers */, A9B9C2701823923200416A4E /* MP42BitmapSubConverter.h in Headers */, + A941C95E1F82A9B900FC5E8D /* MP42SSAConverter.h in Headers */, A9B9C2721823923200416A4E /* MP42CCImporter.h in Headers */, A9B9C2AF1823923200416A4E /* sfifo.h in Headers */, A9B9C27F1823923200416A4E /* MP42H264Importer.h in Headers */, @@ -1059,6 +1079,7 @@ A910B5E218394EB20064028F /* MP42Utilities.m in Sources */, A910B5E418394EB20064028F /* MP42SubUtilities.m in Sources */, A910B5E618394EB20064028F /* MP42XMLReader.m in Sources */, + A941C9611F82A9B900FC5E8D /* MP42SSAConverter.m in Sources */, A910B5E818394EB20064028F /* MP42HtmlParser.m in Sources */, A910B5F118394EB20064028F /* MP42Muxer.m in Sources */, A910B5F418394EB20064028F /* MP42Sample.m in Sources */, @@ -1070,6 +1091,7 @@ A910B5FF18394EB20064028F /* MP42BitmapSubConverter.m in Sources */, A910B60118394EB20064028F /* MP42AudioConverter.m in Sources */, A97EA7CA1D4B8A2D00257CEA /* FFmpegUtils.m in Sources */, + A941C9591F82996600FC5E8D /* MP42TextSubConverter.m in Sources */, A910B60318394EB20064028F /* MP42H264Importer.mm in Sources */, A910B60518394EB20064028F /* MP42VobSubImporter.m in Sources */, A9ED5B141F824BC100E0E4FA /* MP42SSAImporter.m in Sources */, @@ -1111,9 +1133,11 @@ A9B9C2AE1823923200416A4E /* sfifo.c in Sources */, A9B9C27E1823923200416A4E /* MP42FileImporter.m in Sources */, A9B9C27A1823923200416A4E /* MP42Fifo.m in Sources */, + A941C9581F82996600FC5E8D /* MP42TextSubConverter.m in Sources */, A9DFBDA3195FF5BA00410060 /* MP42Heap.m in Sources */, A9059DCC1D870B9C000D1B9A /* MP42ConversionSettings.m in Sources */, A9B9C26B1823923200416A4E /* MP42AudioConverter.m in Sources */, + A941C9601F82A9B900FC5E8D /* MP42SSAConverter.m in Sources */, A9B9C2711823923200416A4E /* MP42BitmapSubConverter.m in Sources */, A9B9C28E1823923200416A4E /* MP42Muxer.m in Sources */, A9ED5B0F1F824A9B00E0E4FA /* MP42SSAParser.m in Sources */,