Skip to content

Commit

Permalink
Fix crash with VobSub headers and Directories
Browse files Browse the repository at this point in the history
Signed-off-by: Ethan Dye <[email protected]>
  • Loading branch information
ecdye committed Oct 22, 2024
1 parent f8e223d commit b551948
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 5 deletions.
16 changes: 12 additions & 4 deletions Sources/macSubtitleOCR/FileHandler.swift
Original file line number Diff line number Diff line change
Expand Up @@ -9,17 +9,25 @@
import Foundation

struct FileHandler {
let outputDirectory: String
private let outputDirectory: URL

init(outputDirectory: String) {
self.outputDirectory = outputDirectory
self.outputDirectory = URL(fileURLWithPath: outputDirectory)
do {
try FileManager.default.createDirectory(
at: self.outputDirectory,
withIntermediateDirectories: true,
attributes: nil)
} catch {
fatalError("Failed to create output directory: \(error)")
}
}

func saveSRTFile(for result: macSubtitleOCRResult) throws {
if result.srt.isEmpty {
return
}
let srtFilePath = URL(fileURLWithPath: outputDirectory).appendingPathComponent("track_\(result.trackNumber).srt")
let srtFilePath = outputDirectory.appendingPathComponent("track_\(result.trackNumber).srt")
let srt = SRT(subtitles: result.srt.sorted { $0.index < $1.index })
srt.write(toFileAt: srtFilePath)
}
Expand All @@ -44,7 +52,7 @@ struct FileHandler {

let jsonData = try JSONSerialization.data(withJSONObject: jsonResults, options: [.prettyPrinted, .sortedKeys])
let jsonString = String(data: jsonData, encoding: .utf8) ?? "[]"
let jsonFilePath = URL(fileURLWithPath: outputDirectory).appendingPathComponent("track_\(result.trackNumber).json")
let jsonFilePath = outputDirectory.appendingPathComponent("track_\(result.trackNumber).json")
try jsonString.write(to: jsonFilePath, atomically: true, encoding: .utf8)
}
}
6 changes: 5 additions & 1 deletion Sources/macSubtitleOCR/Subtitles/VobSub/VobSubParser.swift
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ struct VobSubParser {
let subtitle: Subtitle
private let masterPalette: [UInt8]
private let fps = 24.0 // TODO: Make this configurable / dynamic
private let minimumControlHeaderSize = 22

// MARK: - Lifecycle

Expand Down Expand Up @@ -128,7 +129,10 @@ struct VobSubParser {

private func parseCommandHeader(_ header: Data, offset: Int) {
let relativeEndTimestamp = TimeInterval(Int(header.getUInt16BE()!)) * 1024 / 90000 / fps
let endOfControl = Int(header.getUInt16BE()!) - 4 - offset
let endOfControl = max(minimumControlHeaderSize, Int(header.getUInt16BE()!) - 4 - offset)
if endOfControl > header.count {
logger.warning("Control header is too short, \(header.count) bytes, trying to decode anyway, errors may occur")
}
subtitle.endTimestamp = subtitle.startTimestamp! + relativeEndTimestamp

var index = 2
Expand Down

0 comments on commit b551948

Please sign in to comment.