SPB Git

Repository Public License

TimingTests.swift 14.4 KB 215 lines swift

1// ORIX Convert — Packages/EngineSubtitle/Tests/EngineSubtitleTests/TimingTests.swift2// Description: Timing exactness: millisecond round-trips, the centisecond rounding rule, frame mapping without drift,3//              shift / two-point sync / frame-rate conversion in exact rational arithmetic, and timing repairs.4// Author: Simon-Pierre Boucher — contact@spboucher.ai5import ConvertCore6@testable import EngineSubtitle7import Foundation8import Testing910@Suite struct TimingTests {11    /// Deterministic pseudo-random numbers (the tests must not depend on the system generator).12    struct LCG { var state: UInt64; mutating func next(_ bound: Int) -> Int { state = state &* 6364136223846793005 &+ 1442695040888963407; return Int((state >> 33) % UInt64(bound)) } }1314    static func srt(_ cues: [(Int, Int)]) -> String {15        cues.enumerated().map { "\($0.offset + 1)\n\(SubtitleTime.srt($0.element.0)) --> \(SubtitleTime.srt($0.element.1))\nLine \($0.offset + 1)\n" }.joined(separator: "\n")16    }1718    @Test func srtAndVttRoundTripToTheMillisecond() async throws {19        let scratch = try Scratch(); defer { scratch.cleanUp() }20        var rng = LCG(state: 42)21        var t = 022        var cues: [(Int, Int)] = []23        for _ in 0..<2600 { let start = t + rng.next(4000); let end = start + 1 + rng.next(5999); cues.append((start, end)); t = end }24        #expect(cues.last.map { $0.1 > 3 * 3_600_000 } == true)          // longer than three hours25        let source = try scratch.file("long.srt", Self.srt(cues))26        let vtt = try await convert(source, .srt, .vtt, in: scratch)27        let back = try await convert(vtt.url, .vtt, .srt, in: scratch)28        let doc = try back.document(.srt)29        #expect(doc.cues.map { [$0.startMs, $0.endMs] } == cues.map { [$0.0, $0.1] })30        #expect(!vtt.warnings.has("timing-rounded") && !back.warnings.has("timing-rounded"))31        #expect(back.text == Self.srt(cues) + "\n")32    }3334    @Test(arguments: [(1004, 1000), (1005, 1010), (1014, 1010), (1015, 1020), (995, 1000), (999, 1000), (0, 0), (4, 0), (5, 10), (3_599_995, 3_600_000)])35    func assRoundsHalfUpToTheCentisecond(ms: Int, expected: Int) throws {36        #expect(SubtitleTime.centiseconds(ms) * 10 == expected)37        let doc = try SubtitleParser.parse(data: Data("1\n\(SubtitleTime.srt(ms)) --> \(SubtitleTime.srt(ms + 2000))\nx\n".utf8), format: .srt)38        let result = SubtitlePipeline.run(document: doc, to: .ass, settings: .init())39        let reread = try SubtitleParser.parse(data: result.data, format: .ass)40        #expect(reread.cues[0].startMs == expected)41        #expect((result.loss.roundedTimings == 1) == (ms % 10 != 0))42        #expect(result.warnings.contains { $0.code == "timing-rounded" } == (ms % 10 != 0))43    }4445    @Test func assTimestampsAreWrittenInTheScriptNotation() {46        #expect(SubtitleTime.ass(3_723_456) == "1:02:03.46")47        #expect(SubtitleTime.ass(59_999) == "0:01:00.00")48        #expect(SubtitleTime.srt(3_723_456) == "01:02:03,456")49        #expect(SubtitleTime.vtt(360_000_000) == "100:00:00.000")50    }5152    @Test(arguments: ["23.976", "24", "25", "29.97", "30", "50", "59.94", "60", "24000/1001", "120"])53    func frameToTimeToFrameIsTheIdentityOverThreeHours(rateText: String) throws {54        let rate = try #require(FrameRate(rateText))55        let frames = Int(3.1 * 3600 * rate.doubleValue)56        var mismatches = 057        var previous = -158        for frame in 0...frames {59            let ms = rate.milliseconds(forFrame: frame)60            if rate.frame(forMilliseconds: ms) != frame { mismatches += 1 }61            if ms <= previous { mismatches += 1 }62            previous = ms63        }64        #expect(mismatches == 0)65        // No cumulative drift: the last frame is where exact arithmetic says, to the millisecond.66        let exact = (Double(frames) * 1000 * Double(rate.denominator) / Double(rate.numerator)).rounded()67        #expect(abs(Double(rate.milliseconds(forFrame: frames)) - exact) <= 1)68    }6970    @Test func frameRatesAreExactRationals() throws {71        #expect(try #require(FrameRate("23.976")).description == "24000/1001")72        #expect(try #require(FrameRate("23.98")).description == "24000/1001")73        #expect(try #require(FrameRate("23,976")).description == "24000/1001")74        #expect(try #require(FrameRate("29.97")).description == "30000/1001")75        #expect(try #require(FrameRate("59.94")).description == "60000/1001")76        #expect(try #require(FrameRate("25.000")).description == "25")77        #expect(try #require(FrameRate("12.5")).description == "25/2")78        #expect(try #require(FrameRate("30000/1001")).decimalString == "29.97")79        for bad in ["", "abc", "0", "-25", "25/0", "1e9", "5000", "0.5", "24/1/1", "2 5"] { #expect(FrameRate(bad) == nil, "\(bad)") }80    }8182    @Test(arguments: ["25", "23.976", "29.97"])83    func microDVDRoundTripsThroughSubRipWithoutDrift(rateText: String) async throws {84        let scratch = try Scratch(); defer { scratch.cleanUp() }85        let rate = try #require(FrameRate(rateText))86        let total = Int(3 * 3600 * rate.doubleValue)87        var lines = ""88        var frames: [[Int]] = []89        var f = 790        while f + 60 < total { frames.append([f, f + 53]); lines += "{\(f)}{\(f + 53)}Line at \(f)\n"; f += 97 }91        let source = try scratch.file("long.sub", lines)92        let srt = try await convert(source, .sub, .srt, options: ["fps": .string(rateText)], in: scratch)93        let back = try await convert(srt.url, .srt, .sub, options: ["fps.output": .string(rateText)], in: scratch)94        let doc = try back.document(.sub, rate: rate)95        #expect(doc.cues.count == frames.count)96        #expect(doc.cues.map { [$0.frames?.lowerBound ?? -1, $0.frames?.upperBound ?? -1] } == frames)97        #expect(back.text == lines)98        // The SRT times are the exact frame times, including the very last one after three hours.99        let last = try #require(try srt.document(.srt).cues.last)100        #expect(last.startMs == rate.milliseconds(forFrame: frames[frames.count - 1][0]))101        #expect(!back.warnings.has("timing-rounded"))102    }103104    @Test func microDVDReadsItsHeaderAndWarnsWhenTheRateIsAssumed() async throws {105        let scratch = try Scratch(); defer { scratch.cleanUp() }106        let withHeader = try SubtitleParser.parse(data: Data("{1}{1}29.970\n{30}{60}a\n".utf8), format: .sub)107        #expect(withHeader.frameRate?.description == "30000/1001" && withHeader.frameRateFromHeader && withHeader.cues.count == 1)108        #expect(withHeader.cues[0].startMs == 1001)109        let source = try scratch.file("n.sub", "{24}{48}a\n{50}{}b\n{100}{}c\n")110        let noHeader = try await convert(source, .sub, .srt, in: scratch)111        #expect(noHeader.warnings.has("framerate-assumed") && noHeader.warnings.has("ends-derived"))112        #expect(try noHeader.document(.srt).cues.map(\.startMs) == [1001, 2085, 4171])113        let given = try await convert(source, .sub, .srt, options: ["fps": .string("24")], in: scratch)114        #expect(!given.warnings.has("framerate-assumed"))115        #expect(try given.document(.srt).cues.map { [$0.startMs, $0.endMs] } == [[1000, 2000], [2083, 4167], [4167, 7167]])116        let toSub = try await convert(try scratch.file("a.srt", Self.srt([(1000, 2000)])), .srt, .sub, in: scratch)117        #expect(toSub.warnings.has("framerate-assumed-output") && toSub.text == "{24}{48}Line 1\n")118        #expect(toSub.warnings.has("timing-rounded"))119    }120121    @Test func shiftMovesEveryCueAndDropsWhatFallsBeforeZero() async throws {122        let scratch = try Scratch(); defer { scratch.cleanUp() }123        let source = try scratch.file("a.srt", Self.srt([(500, 900), (1000, 3000), (4000, 5000)]))124        let later = try await convert(source, .srt, .srt, operation: SubtitleEngine.retimeOperation, options: ["shift.ms": .int(1234)], in: scratch)125        #expect(try later.document(.srt).cues.map { [$0.startMs, $0.endMs] } == [[1734, 2134], [2234, 4234], [5234, 6234]])126        let earlier = try await convert(source, .srt, .srt, operation: SubtitleEngine.retimeOperation, options: ["shift.ms": .int(-1500)], in: scratch)127        #expect(try earlier.document(.srt).cues.map { [$0.startMs, $0.endMs] } == [[0, 1500], [2500, 3500]])128        #expect(earlier.warnings.has("cues-before-zero") && earlier.warnings.has("cues-clamped"))129        for check in earlier.checks { #expect(check.passed, "\(check.name) \(check.detail)") }130    }131132    @Test func frameRateConversionUsesExactRationals() throws {133        // 25 → 23.976: every time is multiplied by 25 / (24000/1001) = 1001/960 exactly.134        var settings = SubtitleSettings()135        settings.rateFrom = FrameRate("25"); settings.rateTo = FrameRate("23.976")136        let map = TimeMap(settings)137        #expect(map.apply(960) == 1001)138        #expect(map.apply(3 * 3_600_000) == 11_261_250)            // 10 800 000 × 1001 / 960, exact139        #expect(map.apply(1) == 1 && map.apply(480) == 501)         // 500.52 → 501 (nearest)140        // And back: the composition is the identity on values that are exact both ways.141        settings.rateFrom = FrameRate("23.976"); settings.rateTo = FrameRate("25")142        #expect(TimeMap(settings).apply(11_261_250) == 10_800_000)143        // PAL speed-up 24 → 25.144        settings.rateFrom = FrameRate("24"); settings.rateTo = FrameRate("25")145        #expect(TimeMap(settings).apply(3_600_000) == 3_456_000)146    }147148    @Test func twoPointSyncMapsBothAnchorsExactly() async throws {149        let scratch = try Scratch(); defer { scratch.cleanUp() }150        let source = try scratch.file("a.srt", Self.srt([(60_000, 62_000), (1_800_000, 1_803_000), (3_600_000, 3_601_000)]))151        let options: [String: OptionValue] = ["sync.source1": .string("00:01:00.000"), "sync.target1": .string("00:01:02.500"),152                                              "sync.source2": .string("01:00:00,000"), "sync.target2": .string("01:00:06.040")]153        let out = try await convert(source, .srt, .vtt, options: options, in: scratch)154        let cues = try out.document(.vtt).cues155        #expect(cues[0].startMs == 62_500 && cues[2].startMs == 3_606_040)156        // Midpoint: 62 500 + (1 800 000 − 60 000) × 3 543 540 / 3 540 000 = 1 804 240.157        #expect(cues[1].startMs == 1_804_240)158        var s = SubtitleSettings()159        s.sync = .init(source1: 60_000, target1: 62_500, source2: 3_600_000, target2: 3_606_040); s.shiftMs = 10160        s.rateFrom = FrameRate("25"); s.rateTo = FrameRate("25")161        #expect(TimeMap(s).apply(60_000) == 62_510)162        #expect(TimeMap(SubtitleSettings()).isIdentity)163    }164165    @Test func repairsSortFixOverlapsAndClampDurations() async throws {166        let scratch = try Scratch(); defer { scratch.cleanUp() }167        let source = try scratch.file("a.srt", Self.srt([(5000, 9000), (1000, 6000), (8000, 8000), (12_000, 11_000), (20_000, 20_100), (30_000, 95_000)]))168        let untouched = try await convert(source, .srt, .srt, operation: SubtitleEngine.retimeOperation, in: scratch)169        #expect(try untouched.document(.srt).cues.map(\.startMs) == [5000, 1000, 8000, 12_000, 20_000, 30_000])   // nothing fixed unless asked170        let fixed = try await convert(source, .srt, .srt, operation: SubtitleEngine.retimeOperation,171                                      options: ["fix.sort": .bool(true), "fix.overlaps": .bool(true), "fix.durations": .bool(true),172                                                "duration.min": .int(700), "duration.max": .int(7000)], in: scratch)173        let cues = try fixed.document(.srt).cues174        #expect(cues.map { [$0.startMs, $0.endMs] } == [[1000, 5000], [5000, 8000], [8000, 8700], [11_000, 12_000], [20_000, 20_700], [30_000, 37_000]])175        #expect(fixed.text.hasPrefix("1\n00:00:01,000 --> 00:00:05,000\nLine 2\n\n2\n"))            // renumbered176        #expect(fixed.warnings.warnings.filter { $0.code == "cues-edited" }.count == 4)177        for check in fixed.checks { #expect(check.passed, "\(check.name) \(check.detail)") }178    }179180    @Test func invalidTimingOptionsAreRefused() {181        func settings(_ o: [String: OptionValue]) throws -> SubtitleSettings { try SubtitleEngine.settings(from: ConversionOptions(o)) }182        #expect(throws: ConversionError.self) { try settings(["fps": .string("fast")]) }183        #expect(throws: ConversionError.self) { try settings(["rate.from": .string("25")]) }184        #expect(throws: ConversionError.self) { try settings(["sync.source1": .string("00:01:00.000")]) }185        #expect(throws: ConversionError.self) { try settings(["sync.source1": .string("1:00"), "sync.target1": .string("1:01"), "sync.source2": .string("1:00"), "sync.target2": .string("2:00")]) }186        #expect(throws: ConversionError.self) { try settings(["sync.source1": .string("1:00"), "sync.target1": .string("9:00"), "sync.source2": .string("2:00"), "sync.target2": .string("3:00")]) }187        #expect(throws: ConversionError.self) { try settings(["encoding.input": .string("klingon")]) }188        #expect(throws: ConversionError.self) { try settings(["duration.min": .int(5000), "duration.max": .int(1000)]) }189        #expect(throws: ConversionError.self) { try settings(["wrap.length": .int(3)]) }190        #expect((try? settings(["fps": .double(25)]))?.inputFrameRate?.description == "25")191    }192}193194@Suite struct MeasurementTests {195    /// Not an assertion about speed: prints the numbers quoted in docs/compatibility/engines/subtitle.md.196    @Test func measureLargeFileThroughput() async throws {197        let scratch = try Scratch(); defer { scratch.cleanUp() }198        var cues: [(Int, Int)] = []199        for i in 0..<100_000 { cues.append((i * 3000, i * 3000 + 2500)) }200        let source = try scratch.file("big.srt", TimingTests.srt(cues))201        let size = try #require(try source.resourceValues(forKeys: [.fileSizeKey]).fileSize)202        var lines: [String] = []203        for destination in [FormatID.vtt, .ass, .sub] {204            let work = try scratch.work()205            let request = ConversionRequest(source: source, sourceFormat: .srt, destinationFormat: destination, options: ConversionOptions(["fps.output": .string("25")]))206            let clock = ContinuousClock()207            var output: ConversionOutput?208            let convert = try await clock.measure { output = try await SubtitleEngine().convert(request, context: .init(workDirectory: work)) }209            let validate = try await clock.measure { _ = try await SubtitleEngine().validate(try #require(output), request: request, source: nil) }210            lines.append("srt→\(destination.rawValue): convert \(convert), validate \(validate)")211        }212        print("SUBTITLE-PERF 100000 cues, \(size) bytes — " + lines.joined(separator: "; "))213    }214}215
Files main
Menu

Theme