// // MP42VobSubImporter.m // Subler // // Created by Damiano Galassi on 20/12/12. // Based on parts of Perian's source code. // #import "MP42VobSubImporter.h" #import "MP42FileImporter+Private.h" #import "MP42SubUtilities.h" #import "MP42Languages.h" #import "MP42File.h" #import "mp4v2.h" #import "MP42PrivateUtilities.h" #import "MP42Track+Private.h" #import "MP42SampleBuffer.h" // MP42SupConverter — the vendored sup2vob PGS→VobSub converter (Sup2Vob/). #import "MP42-Shared-Swift.h" MP42_OBJC_DIRECT_MEMBERS @interface SBVobSubSample : NSObject { @public long timeStamp; long fileOffset; } - (id)initWithTime:(long)time offset:(long)offset; @end MP42_OBJC_DIRECT_MEMBERS @interface SBVobSubTrack : NSObject { @public NSArray *privateData; NSString *language; int index; long duration; int imageWidth; int imageHeight; NSMutableArray *samples; } - (id)initWithPrivateData:(NSArray *)idxPrivateData language:(NSString *)lang andIndex:(int)trackIndex; - (void)addSample:(SBVobSubSample *)sample; - (void)addSampleTime:(long)time offset:(long)offset; @end MP42_OBJC_DIRECT_MEMBERS @implementation SBVobSubSample - (id)initWithTime:(long)time offset:(long)offset { self = [super init]; if(!self) return self; timeStamp = time; fileOffset = offset; return self; } @end MP42_OBJC_DIRECT_MEMBERS @implementation SBVobSubTrack - (id)initWithPrivateData:(NSArray *)idxPrivateData language:(NSString *)lang andIndex:(int)trackIndex { self = [super init]; if(!self) return self; privateData = [idxPrivateData copy]; language = [lang copy]; index = trackIndex; samples = [[NSMutableArray alloc] init]; return self; } - (void)addSample:(SBVobSubSample *)sample { [samples addObject:sample]; duration = sample->timeStamp; } - (void)addSampleTime:(long)time offset:(long)offset { SBVobSubSample *sample = [[SBVobSubSample alloc] initWithTime:time offset:offset]; [self addSample:sample]; } @end typedef enum { VOB_SUB_STATE_READING_PRIVATE, VOB_SUB_STATE_READING_TRACK_HEADER, VOB_SUB_STATE_READING_DELAY, VOB_SUB_STATE_READING_TRACK_DATA } VobSubState; static NSString *getNextVobSubLine(NSEnumerator *lineEnum) { NSString *line; while ((line = [lineEnum nextObject]) != nil) { //Reject empty lines which may contain whitespace if([line length] < 3) continue; if([line characterAtIndex:0] == '#') continue; break; } return line; } static NSArray * LoadVobSubSubtitles(NSURL *theDirectory, NSString *filename) { @autoreleasepool { NSURL *nsURL = [theDirectory URLByAppendingPathComponent:filename]; NSString *idxContent = STLoadFileWithUnknownEncoding(nsURL); NSData *privateData = nil; VobSubState state = VOB_SUB_STATE_READING_PRIVATE; SBVobSubTrack *currentTrack = nil; int imageWidth = 0, imageHeight = 0; long delay=0; NSURL *subFileURL = [[nsURL URLByDeletingPathExtension] URLByAppendingPathExtension:@"sub"]; if ([idxContent length]) { NSError *nsErr; NSDictionary *attr = [[NSFileManager defaultManager] attributesOfItemAtPath:subFileURL.path error:&nsErr]; if (!attr) goto bail; int subFileSize = [[attr objectForKey:NSFileSize] intValue]; NSArray *lines = [idxContent componentsSeparatedByString:@"\n"]; NSMutableArray *privateLines = [NSMutableArray array]; NSEnumerator *lineEnum = [lines objectEnumerator]; NSString *line; NSMutableArray *tracks = [NSMutableArray array]; while((line = getNextVobSubLine(lineEnum)) != NULL) { if([line hasPrefix:@"timestamp: "]) state = VOB_SUB_STATE_READING_TRACK_DATA; else if([line hasPrefix:@"id: "]) { if(privateData == nil) { NSString *allLines = [privateLines componentsJoinedByString:@"\n"]; privateData = [allLines dataUsingEncoding:NSUTF8StringEncoding]; } state = VOB_SUB_STATE_READING_TRACK_HEADER; } else if([line hasPrefix:@"delay: "]) state = VOB_SUB_STATE_READING_DELAY; else if(state != VOB_SUB_STATE_READING_PRIVATE) state = VOB_SUB_STATE_READING_TRACK_HEADER; switch(state) { case VOB_SUB_STATE_READING_PRIVATE: [privateLines addObject:line]; if([line hasPrefix:@"size: "]) { sscanf([line UTF8String], "size: %dx%d", &imageWidth, &imageHeight); } break; case VOB_SUB_STATE_READING_TRACK_HEADER: if([line hasPrefix:@"id: "]) { char *langStr = (char *)malloc(line.length * sizeof(char)); int index; sscanf([line UTF8String], "id: %s index: %d", langStr, &index); size_t langLength = strlen(langStr); if(langLength > 0 && langStr[langLength-1] == ',') langStr[langLength-1] = 0; NSString *language = [NSString stringWithUTF8String:langStr]; free(langStr); currentTrack = [[SBVobSubTrack alloc] initWithPrivateData:privateLines language:language andIndex:index]; [tracks addObject:currentTrack]; } break; case VOB_SUB_STATE_READING_DELAY: delay = ParseSubTime([[line substringFromIndex:7] UTF8String], 1000, YES); break; case VOB_SUB_STATE_READING_TRACK_DATA: { char *timeStr = (char *)malloc(line.length * sizeof(char)); unsigned int position; sscanf(line.UTF8String, "timestamp: %s filepos: %x", timeStr, &position); long time = ParseSubTime(timeStr, 1000, YES); free(timeStr); if (position > subFileSize) { position = subFileSize; } [currentTrack addSampleTime:time + delay offset:position]; } break; } } // The `size:` line is global private data that appears before the // first track header, so apply it to every parsed track. for (SBVobSubTrack *track in tracks) { track->imageWidth = imageWidth; track->imageHeight = imageHeight; } return [tracks copy]; } bail: NSLog(@"Exception occurred while importing VobSub"); return nil; } } MP42_OBJC_DIRECT_MEMBERS @implementation MP42VobSubImporter { @private NSArray *_VobSubTracks; /// For .sup sources: the temp directory holding the sup2vob-generated /// .idx/.sub pair, and that .idx's URL. The pair lives until dealloc — /// the model tracks retain this importer through export, and demux reads /// the .sub from disk. Both nil for .idx sources, where the .idx sits /// beside its .sub at fileURL. NSURL *_convertedDirectory; NSURL *_indexFileURL; } + (NSArray *)supportedFileFormats { return @[@"idx", @"sup"]; } + (NSArray *)supportedContentTypes { return @[[UTType typeWithFilenameExtension:@"idx"], [UTType typeWithFilenameExtension:@"sup"]]; } // Convert a BLU-RAY PGS .sup into a VobSub pair in a private temp directory // and return the generated .idx URL. The tracks retain this importer until the // model drops them, so dealloc's cleanup can't pull the pair out from under a // later demux. - (NSURL *)convertSupAtURL:(NSURL *)supURL error:(NSError * __autoreleasing *)outError { NSURL *tempDirectory = [[NSURL fileURLWithPath:NSTemporaryDirectory() isDirectory:YES] URLByAppendingPathComponent:[NSString stringWithFormat:@"sup2vob-%@", [NSUUID UUID].UUIDString]]; NSURL *subURL = [tempDirectory URLByAppendingPathComponent:@"subtitles.sub"]; if (![NSFileManager.defaultManager createDirectoryAtURL:tempDirectory withIntermediateDirectories:YES attributes:nil error:outError]) { return nil; } NSError *conversionError = nil; if (![MP42SupConverter convertSupAtURL:supURL toSubAtURL:subURL language:@"en" languageName:@"English" error:&conversionError]) { // Nothing usable was written; don't leave the empty directory behind // (on success the pair lives here until dealloc instead). [[NSFileManager defaultManager] removeItemAtURL:tempDirectory error:NULL]; if (outError) { *outError = conversionError ?: MP42Error(MP42LocalizedString(@"The file could not be opened.", @"vobsub error message"), MP42LocalizedString(@"The file is not a sup file, or it does not contain any subtitles.", @"vobsub error message"), 101); } return nil; } _convertedDirectory = tempDirectory; return [tempDirectory URLByAppendingPathComponent:@"subtitles.idx"]; } - (void)dealloc { if (_convertedDirectory) { [[NSFileManager defaultManager] removeItemAtURL:_convertedDirectory error:NULL]; } } - (instancetype)initWithURL:(NSURL *)fileURL error:(NSError * __autoreleasing *)outError { if ((self = [super initWithURL:fileURL])) { _indexFileURL = fileURL; if ([fileURL.pathExtension caseInsensitiveCompare:@"sup"] == NSOrderedSame) { _indexFileURL = [self convertSupAtURL:fileURL error:outError]; if (!_indexFileURL) { return nil; } } MP42TrackId count = 0; _VobSubTracks = LoadVobSubSubtitles(_indexFileURL.URLByDeletingLastPathComponent, _indexFileURL.lastPathComponent); // PGS carries no usable language (the generated idx id: line is the // converter default), so — like the .srt/.ssa importers — take it from // the filename; the 2-letter code path below would otherwise pin "en". NSString *filenameLanguage = _convertedDirectory ? getFilenameLanguage((__bridge CFStringRef)fileURL.path) : nil; for (SBVobSubTrack *track in _VobSubTracks) { MP42SubtitleTrack *newTrack = [[MP42SubtitleTrack alloc] init]; newTrack.format = kMP42SubtitleCodecType_VobSub; newTrack.URL = self.fileURL; newTrack.alternateGroup = 2; newTrack.trackId = count++; newTrack.language = [MP42Languages.defaultManager extendedTagForISO_639_1:track->language]; if (filenameLanguage && ![filenameLanguage isEqualToString:@"und"]) { newTrack.language = filenameLanguage; } // "...eng.sdh.idx/sup" style type tokens name the track after // the type ("SDH") — MP4 has no SDH/CC flag, the name is the // convention players show; the language rides its own element. newTrack.name = getFilenameSubtitlesTrackName((__bridge CFStringRef)fileURL.path); newTrack.timescale = 1000; newTrack.duration = track->duration; // Carry the frame size declared by the idx `size:` line into the // model, so the muxer can mux the subpic track at the size the // subtitle actually uses instead of a generic default. // Note: trackWidth/trackHeight are intentionally left unset here: // the tx3g conversion path reads them as the tx3g default text box // size, which must keep its own 0.15-height fallback. if (track->imageWidth > 0 && track->imageHeight > 0) { newTrack.width = (uint64_t)track->imageWidth; newTrack.height = (uint64_t)track->imageHeight; } [self addTrack:newTrack]; } if (!self.tracks.count) { if (outError) { *outError = MP42Error(MP42LocalizedString(@"The file could not be opened.", @"vobsub error message"), MP42LocalizedString(@"The file is not a idx file, or it does not contain any subtitles.", @"vobsub error message"), 100); } return nil; } } return self; } - (NSData *)magicCookieForTrack:(MP42Track *)track { SBVobSubTrack *vobTrack = [_VobSubTracks objectAtIndex:track.sourceId]; NSData *magicCookie = nil; for (NSString *line in vobTrack->privateData) { if ([line hasPrefix:@"palette: "]) { const char *palette = [line UTF8String]; UInt32 colorPalette[32]; if (palette != NULL) { sscanf(palette, "palette: %lx, %lx, %lx, %lx, %lx, %lx, %lx, %lx, %lx, %lx, %lx, %lx, %lx, %lx, %lx, %lx", (unsigned long*)&colorPalette[ 0], (unsigned long*)&colorPalette[ 1], (unsigned long*)&colorPalette[ 2], (unsigned long*)&colorPalette[ 3], (unsigned long*)&colorPalette[ 4], (unsigned long*)&colorPalette[ 5], (unsigned long*)&colorPalette[ 6], (unsigned long*)&colorPalette[ 7], (unsigned long*)&colorPalette[ 8], (unsigned long*)&colorPalette[ 9], (unsigned long*)&colorPalette[10], (unsigned long*)&colorPalette[11], (unsigned long*)&colorPalette[12], (unsigned long*)&colorPalette[13], (unsigned long*)&colorPalette[14], (unsigned long*)&colorPalette[15]); } magicCookie = [NSData dataWithBytes:colorPalette length:sizeof(UInt32)*16]; } } return magicCookie; } - (void)demux { @autoreleasepool { NSURL *subFileURL = [_indexFileURL.URLByDeletingPathExtension URLByAppendingPathExtension:@"sub"]; NSData *subFileData = [NSData dataWithContentsOfURL:subFileURL]; NSInteger tracksNumber = self.inputTracks.count; NSInteger tracksDone = 0; for (MP42Track *track in self.inputTracks) { SBVobSubTrack *vobTrack = [_VobSubTracks objectAtIndex:track.sourceId]; SBVobSubSample *firstSample = nil; uint64_t lastTime = 0; NSUInteger sampleCount = vobTrack->samples.count; for (NSUInteger i = 0; i < sampleCount && !self.isCancelled; i++) { SBVobSubSample *currentSample = [vobTrack->samples objectAtIndex:i]; long offset = currentSample->fileOffset; long nextOffset; if (i == sampleCount - 1) { nextOffset = subFileData.length; } else { nextOffset = [vobTrack->samples objectAtIndex:i+1]->fileOffset; } int size = (int)(nextOffset - offset); if (size < 0) { //Skip samples for which we cannot determine size continue; } NSData *subData = [subFileData subdataWithRange:NSMakeRange(offset, size)]; uint8_t *extracted = (uint8_t *)malloc(size); //The index here likely should really be track->index, but I'm not sure we can really trust it. int extractedSize = ExtractVobSubPacket(extracted, (UInt8 *)subData.bytes, size, &size, -1); uint16_t startTimestamp, endTimestamp; uint8_t forced; if (!ReadPacketTimes(extracted, extractedSize, &startTimestamp, &endTimestamp, &forced)) { free(extracted); continue; } uint64_t startTime = currentSample->timeStamp + startTimestamp; uint64_t endTime = currentSample->timeStamp + endTimestamp; uint64_t duration = endTimestamp - startTimestamp; if (duration <= 0 && i < sampleCount - 1) { //Sample with no end duration, use the duration of the next one endTime = [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->timescale = 1000; sample->duration = startTime - lastTime; sample->offset = 0; sample->presentationTimestamp = startTime; sample->presentationOutputTimestamp = startTime; sample->decodeTimestamp = startTime; sample->flags |= MP42SampleBufferFlagIsSync; sample->trackId = track.sourceId; [self enqueue:sample]; } MP42SampleBuffer *sample = [[MP42SampleBuffer alloc] init]; sample->data = extracted; sample->size = size; sample->duration = duration; sample->offset = 0; sample->presentationTimestamp = startTime; sample->presentationOutputTimestamp = startTime; sample->decodeTimestamp = startTime; sample->flags |= MP42SampleBufferFlagIsSync; sample->trackId = track.sourceId; [self enqueue:sample]; lastTime = endTime; self.progress = ((i / (CGFloat) sampleCount ) * 100 / tracksNumber) + (tracksDone / (CGFloat) tracksNumber * 100); } tracksDone++; } [self setDone]; } } - (NSString *)description { return @"VobSub demuxer"; } @end