SPB Git

Repository Public

CoreTests.swift 17.9 KB 305 lines swift

1// SP Lecture Studio — Tests2// File: Tests/Unit/CoreTests.swift3// Description: Unit tests of the domain layer: timebase, ink codec, timeline index, edit decision list, time mapping, analysis, auto-pause, captions.4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai7import XCTest8@testable import LectureCore910func T(_ s: Double) -> MediaTime { MediaTime(seconds: s) }1112final class MediaTimeTests: XCTestCase {13    func testExactArithmeticOverNinetyMinutes() {14        // 162 000 frames at 30 fps accumulated one by one must land exactly on 5400 s (no floating point drift).15        var t = MediaTime.zero16        for i in 0..<162_000 { t = MediaTime(ns: Int64(i + 1) * 1_000_000_000 / 30) }17        XCTAssertEqual(t, T(5400))18        XCTAssertEqual(MediaTime(frames: 48_000 * 5400, sampleRate: 48_000), T(5400))19        XCTAssertEqual(T(5400).frames(atSampleRate: 44_100), 238_140_000)20    }2122    func testClockAndRanges() {23        XCTAssertEqual(MediaTime.clock(T(3725)), "1:02:05")24        XCTAssertEqual(MediaTime.clock(T(65.4), tenths: true), "1:05.4")25        let merged = TimeRange.merged([TimeRange(seconds: 5, 8), TimeRange(seconds: 1, 3), TimeRange(seconds: 2.5, 4), TimeRange(seconds: 8, 9)])26        XCTAssertEqual(merged, [TimeRange(seconds: 1, 4), TimeRange(seconds: 5, 9)])27        XCTAssertNil(TimeRange(seconds: 1, 2).intersection(TimeRange(seconds: 2, 3)))28    }29}3031final class InkTests: XCTestCase {32    func testStrokeRoundTripAndProgress() throws {33        let s = Stroke(page: 3, tool: .marker, color: RGBAColor(hex: "#FFDB00CC")!, width: 0.02, begin: T(12.5),34                       points: (0..<50).map { StrokePoint(x: Double($0) / 100, y: 0.5, dt: Int64($0) * 20_000_000, w: 1) })35        let data = try EventCoding.encoder().encode(s)36        let back = try EventCoding.decoder().decode(Stroke.self, from: data)37        XCTAssertEqual(back, s)38        XCTAssertEqual(s.pointCount(at: T(12.4)), 0)39        XCTAssertEqual(s.pointCount(at: T(12.5)), 1)40        XCTAssertEqual(s.pointCount(at: T(12.5 + 0.5)), 26)       // points at 0…500 ms41        XCTAssertEqual(s.pointCount(at: T(20)), 50)42        XCTAssertEqual(s.end, T(12.5 + 0.98))43        XCTAssertEqual(RGBAColor(hex: "#FF000080")?.a ?? 0, 128.0 / 255, accuracy: 0.001)44    }4546    func testEventLogToleratesDamage() throws {47        var data = Data()48        data.append(try EventCoding.line(for: TimelineEvent(seq: 1, t: T(0), e: .page(index: 0))))49        data.append(Data("{\"seq\":2,\"t\":5,\"wall\":0,\"e\":{\"fromTheFuture\":{}}}\n".utf8))50        data.append(try EventCoding.line(for: TimelineEvent(seq: 3, t: T(2), e: .marker(Marker(kind: .retake)))))51        data.append(Data("{\"seq\":4,\"t\":".utf8))                    // crash in the middle of a line52        let r = EventCoding.parse(data)53        XCTAssertEqual(r.events.map(\.seq), [1, 3])54        XCTAssertEqual(r.skippedLines, 2)55        XCTAssertTrue(r.truncatedTail)56    }57}5859final class TimelineIndexTests: XCTestCase {60    func stroke(_ page: Int, begin: Double, seconds: Double, n: Int = 11) -> Stroke {61        Stroke(page: page, tool: .pen, color: .black, width: 0.004, begin: T(begin),62               points: (0..<n).map { StrokePoint(x: Double($0) / Double(n), y: 0.2, dt: Int64(seconds * 1e9 * Double($0) / Double(n - 1))) })63    }6465    func testStateAtTime() {66        let a = stroke(0, begin: 2, seconds: 1), b = stroke(0, begin: 5, seconds: 2), c = stroke(1, begin: 12, seconds: 0, n: 2)67        var seq: Int64 = 068        func ev(_ t: Double, _ e: EventPayload) -> TimelineEvent { seq += 1; return TimelineEvent(seq: seq, t: T(t), e: e) }69        let events = [ev(0, .page(index: 0)), ev(3, .strokeAdded(a)), ev(7, .strokeAdded(b)), ev(8, .strokesRemoved(ids: [a.id])),70                      ev(9, .strokesRestored(ids: [a.id])), ev(10, .page(index: 1)), ev(12, .strokeAdded(c)),71                      ev(13, .pointer(x: 0.5, y: 0.5)), ev(13.5, .pointerHidden), ev(14, .strokesRemoved(ids: [c.id])),72                      ev(15, .marker(Marker(kind: .retake))), ev(16, .viewport(Viewport(zoom: 2, cx: 0.3, cy: 0.3)))]73        let idx = TimelineIndex(events: events)74        XCTAssertEqual(idx.page(at: T(9.99)), 0); XCTAssertEqual(idx.page(at: T(10)), 1)75        XCTAssertEqual(idx.visibleStrokes(page: 0, at: T(1)).count, 0)76        let mid = idx.visibleStrokes(page: 0, at: T(2.5))77        XCTAssertEqual(mid.count, 1); XCTAssertFalse(mid[0].complete); XCTAssertEqual(mid[0].pointCount, 6)78        XCTAssertEqual(idx.visibleStrokes(page: 0, at: T(7.5)).map(\.stroke.id), [a.id, b.id])79        XCTAssertEqual(idx.visibleStrokes(page: 0, at: T(8.5)).map(\.stroke.id), [b.id])            // erased80        XCTAssertEqual(idx.visibleStrokes(page: 0, at: T(9.5)).map(\.stroke.id), [a.id, b.id])      // restored81        XCTAssertEqual(idx.finalStrokes(page: 0).count, 2)82        XCTAssertEqual(idx.finalStrokes(page: 1).count, 0)                                          // removed at the end83        XCTAssertNotNil(idx.pointer(at: T(13.2))); XCTAssertNil(idx.pointer(at: T(13.6)))84        XCTAssertEqual(idx.viewport(at: T(20)).zoom, 2)85        XCTAssertEqual(idx.markers.count, 1)86        // Signatures: identical while nothing changes, different while a stroke is being drawn.87        XCTAssertEqual(idx.signature(at: T(3.5)), idx.signature(at: T(4.5)))88        XCTAssertNotEqual(idx.signature(at: T(5.2)), idx.signature(at: T(5.9)))89        XCTAssertNotEqual(idx.signature(at: T(7.5)), idx.signature(at: T(8.5)))90    }9192    func testAdjustments() {93        let a = stroke(0, begin: 4, seconds: 1)94        let events = [TimelineEvent(seq: 1, t: T(5), e: .strokeAdded(a))]95        let shifted = TimelineIndex(events: events, adjustments: InkAdjustments(offsets: [a.id: -2_000_000_000]))96        XCTAssertEqual(shifted.visibleStrokes(page: 0, at: T(3.1)).count, 1)97        let hidden = TimelineIndex(events: events, adjustments: InkAdjustments(hidden: [a.id]))98        XCTAssertTrue(hidden.finalStrokes(page: 0).isEmpty)99    }100}101102final class EditTests: XCTestCase {103    func testTimeMapRoundTrip() {104        let map = TimeMap(duration: T(100), cuts: [TimeRange(seconds: 10, 20), TimeRange(seconds: 15, 30), TimeRange(seconds: 90, 120)])105        XCTAssertEqual(map.kept, [TimeRange(seconds: 0, 10), TimeRange(seconds: 30, 90)])106        XCTAssertEqual(map.outputDuration, T(70))107        XCTAssertEqual(map.toSource(T(5)), T(5)); XCTAssertEqual(map.toSource(T(10)), T(30)); XCTAssertEqual(map.toSource(T(69)), T(89))108        XCTAssertEqual(map.toOutput(T(25)), T(10))                    // inside a cut → the join109        XCTAssertEqual(map.toOutput(T(45)), T(25)); XCTAssertEqual(map.toOutput(T(95)), T(70))110        XCTAssertEqual(map.joins, [T(10)])111        XCTAssertEqual(map.outputRanges(for: TimeRange(seconds: 8, 32)), [TimeRange(seconds: 8, 10), TimeRange(seconds: 10, 12)])112        for s in stride(from: 0.0, to: 70.0, by: 0.37) { XCTAssertEqual(map.toOutput(map.toSource(T(s))), T(s)) }113        XCTAssertTrue(TimeMap(duration: T(10), cuts: []).isIdentity)114    }115116    func testHistoryIsReversible() {117        var h = EditHistory()118        h.apply { $0.addCut(TimeRange(seconds: 1, 2)) }119        h.apply { $0.addCut(TimeRange(seconds: 5, 6)) }120        h.apply { $0.normalizeLoudness = true }121        XCTAssertEqual(h.current.cuts.count, 2)122        h.undo(); h.undo()123        XCTAssertEqual(h.current.cuts.count, 1); XCTAssertFalse(h.current.normalizeLoudness)124        h.redo()125        XCTAssertEqual(h.current.cuts.count, 2)126        h.revertToOriginal()127        XCTAssertEqual(h.current, EditDecisionList())128        h.undo()129        XCTAssertEqual(h.current.cuts.count, 2)                       // the originals of every decision are recoverable130        let before = h131        h.apply { _ in }                                              // no-op does not pollute the history132        XCTAssertEqual(h, before)133    }134135    func testSuggestionsNeverAffectOutputUntilApproved() {136        var e = EditDecisionList()137        let s = Cut(range: TimeRange(seconds: 10, 20), origin: .silence, confidence: 0.9)138        e.setSuggestions([s], origin: .silence)139        XCTAssertEqual(e.timeMap(duration: T(60)).outputDuration, T(60))140        e.approve(s.id)141        XCTAssertEqual(e.timeMap(duration: T(60)).outputDuration, T(50))142        e.setSuggestions([s, Cut(range: TimeRange(seconds: 30, 35), origin: .silence)], origin: .silence)143        XCTAssertEqual(e.suggestions.count, 1)                        // the already applied one is not proposed again144        e.reject(e.suggestions[0].id)145        XCTAssertTrue(e.suggestions.isEmpty)146    }147148    func testClipsAndTrim() {149        var e = EditDecisionList()150        e.split(at: T(10)); e.split(at: T(20)); e.addCut(TimeRange(seconds: 10, 20))151        e.trimStart(to: T(2)); e.trimEnd(from: T(55), duration: T(60))152        let clips = e.clips(duration: T(60))153        XCTAssertEqual(clips.map(\.isCut), [true, false, true, false, true])154        XCTAssertEqual(e.timeMap(duration: T(60)).outputDuration, T(43))155        e.trimStart(to: .zero)156        XCTAssertEqual(e.timeMap(duration: T(60)).outputDuration, T(45))157    }158}159160final class AnalysisTests: XCTestCase {161    /// 10 ms hops: speech at -20 dB, room noise at -62 dB.162    func envelope(_ plan: [(seconds: Double, db: Float)]) -> Envelope {163        var e = Envelope()164        for p in plan { let n = Int(p.seconds * 100); e.rms += [Float](repeating: p.db, count: n); e.peak += [Float](repeating: p.db > -40 ? 0.3 : 0.001, count: n) }165        return e166    }167168    func testLongSilenceIsSuggestedNaturalPauseIsNot() {169        let env = envelope([(8, -20), (0.9, -62), (6, -20), (7, -62), (5, -20), (2.2, -62), (9, -20)])170        let r = SilenceDetector.detect(env)171        XCTAssertTrue(r.reliable)172        XCTAssertEqual(r.silences.count, 1)                           // only the 7 s silence; 0.9 s and 2.2 s are natural pauses173        XCTAssertEqual(r.silences[0].range.start.seconds, 14.9, accuracy: 0.02)174        XCTAssertEqual(r.silences[0].range.duration.seconds, 7, accuracy: 0.03)175        let cuts = SilenceDetector.suggestions(env)176        XCTAssertEqual(cuts.count, 1)177        XCTAssertEqual(cuts[0].range.start.seconds, 15.3, accuracy: 0.03)          // 0.4 s of padding kept on each side178        XCTAssertEqual(cuts[0].range.end.seconds, 21.5, accuracy: 0.03)179        XCTAssertGreaterThan(cuts[0].confidence ?? 0, 0.7)180    }181182    func testUnreliableWhenNoSeparationAndClickBridging() {183        XCTAssertFalse(SilenceDetector.detect(envelope([(30, -50), (30, -47)])).reliable)184        XCTAssertTrue(SilenceDetector.suggestions(envelope([(30, -50), (30, -47)])).isEmpty)185        // A 50 ms click inside a long silence does not split it.186        let r = SilenceDetector.detect(envelope([(5, -20), (3, -62), (0.05, -25), (3, -62), (5, -20)]))187        XCTAssertEqual(r.silences.count, 1)188        XCTAssertEqual(r.silences[0].range.duration.seconds, 6.05, accuracy: 0.05)189    }190191    func testRetakeSuggestion() {192        // Speech, 2 s pause at 20–22, failed sentence 22–30, retake marker at 30.5 during a 2 s pause 30–32, then the good take.193        let env = envelope([(20, -20), (2, -62), (8, -20), (2, -62), (20, -20)])194        let events = [TimelineEvent(seq: 1, t: T(0), e: .page(index: 0)), TimelineEvent(seq: 2, t: T(30.5), e: .marker(Marker(kind: .retake)))]195        let cuts = RetakeSuggester.suggestions(index: TimelineIndex(events: events), envelope: env, duration: T(52))196        XCTAssertEqual(cuts.count, 1)197        XCTAssertEqual(cuts[0].range.start.seconds, 21.8, accuracy: 0.05)198        XCTAssertEqual(cuts[0].range.end.seconds, 31.8, accuracy: 0.05)199        XCTAssertEqual(cuts[0].origin, .retake)200    }201202    func testChaptersFromSlides() {203        let events = [TimelineEvent(seq: 1, t: T(0), e: .page(index: 0)), TimelineEvent(seq: 2, t: T(60), e: .page(index: 1)),204                      TimelineEvent(seq: 3, t: T(62), e: .page(index: 2)), TimelineEvent(seq: 4, t: T(200), e: .page(index: 3))]205        let ch = ChapterGenerator.fromSlides(index: TimelineIndex(events: events), duration: T(300), title: { "Page \($0 + 1)" })206        XCTAssertEqual(ch.map(\.title), ["Page 1", "Page 3", "Page 4"])                 // page 2 was only flipped through207        let map = TimeMap(duration: T(300), cuts: [TimeRange(seconds: 50, 100)])208        XCTAssertEqual(ChapterGenerator.mapped(ch, map: map).map(\.time), [T(0), T(50), T(150)])209    }210}211212final class AutoPauseTests: XCTestCase {213    func run(_ engine: inout AutoPauseEngine, from: Double, to: Double, level: Double, recordedOffset: Double = 0) -> [AutoPauseEngine.Output] {214        var out: [AutoPauseEngine.Output] = []215        var t = from216        while t < to { engine.ingest(levelDB: level, now: t); out += engine.tick(now: t, recordedSeconds: t + recordedOffset, wall: Date(timeIntervalSince1970: t)); t += 0.1 }217        return out218    }219220    func testAllPoliciesAreOptIn() {221        var e = AutoPauseEngine(policy: AutoPausePolicy(), now: 0)222        XCTAssertTrue(run(&e, from: 0, to: 4000, level: -90).isEmpty)223    }224225    func testSilenceSuggestsAndWithdraws() {226        var p = AutoPausePolicy(); p.silenceEnabled = true; p.silenceSeconds = 20227        var e = AutoPauseEngine(policy: p, now: 0)228        XCTAssertTrue(run(&e, from: 0, to: 30, level: -20).isEmpty)229        let quiet = run(&e, from: 30, to: 55, level: -70)230        XCTAssertEqual(quiet, [.suggestPause(.silence)])                               // a suggestion, once, never an action231        XCTAssertEqual(run(&e, from: 55, to: 56, level: -20), [.withdrawSuggestion])232    }233234    func testQuietSpeechInsideHysteresisIsNotSilence() {235        var p = AutoPausePolicy(); p.silenceEnabled = true; p.silenceSeconds = 5236        var e = AutoPauseEngine(policy: p, now: 0)237        var out: [AutoPauseEngine.Output] = []238        var t = 0.0239        while t < 30 {                                                                 // soft voice with word gaps shorter than the hangover240            e.ingest(levelDB: Int(t * 10) % 5 == 0 ? -40 : -46, now: t); out += e.tick(now: t, recordedSeconds: t, wall: Date()); t += 0.1241        }242        XCTAssertTrue(out.isEmpty)243    }244245    func testInactivityCountdownCancelledByInteractionThenPauses() {246        var p = AutoPausePolicy(); p.inactivityEnabled = true; p.inactivitySeconds = 60; p.countdownSeconds = 10247        var e = AutoPauseEngine(policy: p, now: 0)248        XCTAssertEqual(run(&e, from: 0, to: 61, level: -70), [.countdownStarted(.inactivity, seconds: 10)])249        e.noteInteraction(now: 62)250        XCTAssertEqual(run(&e, from: 62, to: 63, level: -70), [.countdownCancelled(.inactivity)])251        let later = run(&e, from: 63, to: 140, level: -70)252        XCTAssertEqual(later, [.countdownStarted(.inactivity, seconds: 10), .countdownFinished(.inactivity, stop: false)])   // default: pause, not stop253        XCTAssertTrue(run(&e, from: 140, to: 300, level: -70).isEmpty)                 // does not fire again until activity returns254    }255256    func testMaxDurationAndManualControlWins() {257        var p = AutoPausePolicy(); p.maxDurationEnabled = true; p.maxDurationSeconds = 100; p.countdownSeconds = 10; p.stopWhenCountdownEnds = true258        var e = AutoPauseEngine(policy: p, now: 0)259        XCTAssertEqual(run(&e, from: 0, to: 91, level: -20), [.countdownStarted(.maxDuration, seconds: 10)])260        XCTAssertEqual(e.userContinued(now: 92, recordedSeconds: 92, wall: Date()), [.countdownCancelled(.maxDuration)])261        XCTAssertTrue(run(&e, from: 92, to: 400, level: -20).isEmpty)                  // snoozed 15 min262        var e2 = AutoPauseEngine(policy: p, now: 0)263        _ = run(&e2, from: 0, to: 91, level: -20)264        XCTAssertEqual(run(&e2, from: 91, to: 102, level: -20), [.countdownFinished(.maxDuration, stop: true)])265        var e3 = AutoPauseEngine(policy: p, now: 0)266        _ = run(&e3, from: 0, to: 91, level: -20)267        XCTAssertEqual(e3.userPaused(), [.countdownCancelled(.maxDuration)])268        XCTAssertTrue(run(&e3, from: 91, to: 500, level: -90).isEmpty)                 // manual pause freezes every timer269    }270}271272final class CaptionTests: XCTestCase {273    func testSRTAndVTTOnEditedTimeline() {274        let tr = Transcript(locale: "fr-CA", provider: "test", segments: [275            TranscriptSegment(range: TimeRange(seconds: 1, 4), text: "Bonjour à tous."),276            TranscriptSegment(range: TimeRange(seconds: 10, 14), text: "Ceci sera coupé."),277            TranscriptSegment(range: TimeRange(seconds: 21, 25.5), text: "On reprend la méthode du coût."),278        ])279        let map = TimeMap(duration: T(30), cuts: [TimeRange(seconds: 8, 20)])280        let caps = CaptionWriter.captions(tr, map: map)281        XCTAssertEqual(caps.map(\.text), ["Bonjour à tous.", "On reprend la méthode du coût."])282        XCTAssertEqual(caps[1].range, TimeRange(seconds: 9, 13.5))283        let srt = CaptionWriter.srt(caps)284        XCTAssertTrue(srt.hasPrefix("1\n00:00:01,000 --> 00:00:04,000\nBonjour à tous.\n\n2\n00:00:09,000 --> 00:00:13,500\n"))285        XCTAssertTrue(CaptionWriter.vtt(caps).hasPrefix("WEBVTT\n\n00:00:01.000 --> 00:00:04.000\n"))286    }287288    func testLongSegmentIsSplitWithoutOverlap() {289        let text = (1...40).map { "mot\($0)" }.joined(separator: " ")290        let tr = Transcript(locale: "fr", provider: "t", segments: [TranscriptSegment(range: TimeRange(seconds: 0, 20), text: text)])291        let caps = CaptionWriter.captions(tr, map: TimeMap(duration: T(20), cuts: []))292        XCTAssertGreaterThanOrEqual(caps.count, 3)293        XCTAssertEqual(caps.map(\.text).joined(separator: " "), text)294        for (a, b) in zip(caps, caps.dropFirst()) { XCTAssertLessThanOrEqual(a.range.end, b.range.start) }295        XCTAssertEqual(caps.last?.range.end, T(20))296    }297298    func testChaptersJSON() throws {299        let data = try CaptionWriter.chaptersJSON(title: "Séance 8", chapters: [Chapter(time: T(0), title: "Intro"), Chapter(time: T(75), title: "Cas")],300                                                  map: TimeMap(duration: T(100), cuts: [TimeRange(seconds: 10, 20)]))301        let f = try JSONDecoder().decode(CaptionWriter.ChapterFile.self, from: data)302        XCTAssertEqual(f.chapters.map(\.start), [0, 65]); XCTAssertEqual(f.duration, 90); XCTAssertEqual(f.chapters[1].timestamp, "1:05")303    }304}305
Files main
Menu

Theme