Repository Public
1// SP Lecture Studio — LectureCore2// File: Packages/LectureCore/Sources/Edits.swift3// Description: Nondestructive edit decision list, source/output time mapping, and undoable edit history.4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai7import Foundation89public enum CutOrigin: String, Codable, Sendable { case manual, trim, silence, retake, transcript }1011/// A range of the source timeline left out of the output. Source media is never touched.12public struct Cut: Hashable, Sendable, Codable, Identifiable {13 public var id: UUID14 public var range: TimeRange15 public var origin: CutOrigin16 public var note: String17 /// 0…1 for automatically suggested cuts, nil for manual ones.18 public var confidence: Double?19 public init(id: UUID = UUID(), range: TimeRange, origin: CutOrigin, note: String = "", confidence: Double? = nil) {20 self.id = id; self.range = range; self.origin = origin; self.note = note; self.confidence = confidence21 }22}2324public struct Chapter: Hashable, Sendable, Codable, Identifiable {25 public var id: UUID26 /// Source timeline time.27 public var time: MediaTime28 public var title: String29 public init(id: UUID = UUID(), time: MediaTime, title: String) { self.id = id; self.time = time; self.title = title }30}3132public struct EditDecisionList: Hashable, Sendable, Codable {33 /// Approved cuts: applied to preview and export.34 public var cuts: [Cut] = []35 /// Suggestions waiting for review. They never affect the output until approved.36 public var suggestions: [Cut] = []37 /// Clip boundaries created by "split" (source time).38 public var splits: [MediaTime] = []39 public var muted: [TimeRange] = []40 public var fadeIn: MediaTime = .zero41 public var fadeOut: MediaTime = .zero42 /// Length of the audio crossfade centred on every cut join.43 public var crossfade: MediaTime = MediaTime(milliseconds: 30)44 public var gainDB: Double = 045 public var normalizeLoudness = false46 public var noiseReduction = false47 public var chapters: [Chapter] = []48 public var ink = InkAdjustments()49 public var cameraPlacement: CameraPlacement?50 public var cameraHidden = false5152 public init() {}5354 public func timeMap(duration: MediaTime) -> TimeMap { TimeMap(duration: duration, cuts: cuts.map(\.range)) }5556 // MARK: Editing operations (pure; callers push the result on an EditHistory)5758 public mutating func addCut(_ range: TimeRange, origin: CutOrigin = .manual, note: String = "") {59 guard !range.isEmpty else { return }60 cuts.append(Cut(range: range, origin: origin, note: note))61 }62 public mutating func removeCut(_ id: UUID) { cuts.removeAll { $0.id == id } }6364 public mutating func approve(_ id: UUID) {65 guard let i = suggestions.firstIndex(where: { $0.id == id }) else { return }66 cuts.append(suggestions.remove(at: i))67 }68 public mutating func reject(_ id: UUID) { suggestions.removeAll { $0.id == id } }6970 /// Replaces the pending suggestions of one origin (re-running a detector must not duplicate them) and71 /// drops the ones already covered by an approved cut.72 public mutating func setSuggestions(_ new: [Cut], origin: CutOrigin) {73 suggestions.removeAll { $0.origin == origin }74 let applied = TimeRange.merged(cuts.map(\.range))75 suggestions.append(contentsOf: new.filter { s in76 !applied.contains { ($0.intersection(s.range)?.duration ?? .zero).ns * 10 >= s.range.duration.ns * 9 }77 })78 suggestions.sort { $0.range.start < $1.range.start }79 }8081 public mutating func split(at t: MediaTime) { if !splits.contains(t) { splits.append(t); splits.sort() } }8283 /// Clips of the source timeline delimited by splits and by cut edges, with their kept / cut status.84 public func clips(duration: MediaTime) -> [(range: TimeRange, isCut: Bool)] {85 let cutRanges = TimeRange.merged(cuts.map(\.range))86 var bounds = Set<MediaTime>([.zero, duration])87 for s in splits where s > .zero && s < duration { bounds.insert(s) }88 for c in cutRanges { bounds.insert(max(.zero, c.start)); bounds.insert(min(duration, c.end)) }89 let sorted = bounds.sorted()90 return zip(sorted, sorted.dropFirst()).map { a, b in91 let r = TimeRange(start: a, end: b)92 return (r, cutRanges.contains { $0.start <= a && $0.end >= b })93 }94 }9596 public mutating func trimStart(to t: MediaTime) {97 cuts.removeAll { $0.origin == .trim && $0.range.start == .zero }98 if t > .zero { cuts.append(Cut(range: TimeRange(start: .zero, end: t), origin: .trim)) }99 }100 public mutating func trimEnd(from t: MediaTime, duration: MediaTime) {101 cuts.removeAll { $0.origin == .trim && $0.range.end >= duration }102 if t < duration { cuts.append(Cut(range: TimeRange(start: t, end: duration), origin: .trim)) }103 }104}105106/// Mapping between the source (recorded) timeline and the output (edited) timeline.107public struct TimeMap: Sendable, Hashable {108 public let duration: MediaTime109 /// Kept source ranges, sorted and disjoint.110 public let kept: [TimeRange]111 /// Output start time of each kept range.112 public let outputStarts: [MediaTime]113 public let outputDuration: MediaTime114115 public init(duration: MediaTime, cuts: [TimeRange]) {116 self.duration = duration117 let full = TimeRange(start: .zero, end: duration)118 let merged = TimeRange.merged(cuts.compactMap { $0.intersection(full) })119 var kept: [TimeRange] = []120 var cursor = MediaTime.zero121 for c in merged {122 if c.start > cursor { kept.append(TimeRange(start: cursor, end: c.start)) }123 cursor = max(cursor, c.end)124 }125 if cursor < duration { kept.append(TimeRange(start: cursor, end: duration)) }126 self.kept = kept127 var starts: [MediaTime] = []; var acc = MediaTime.zero128 for k in kept { starts.append(acc); acc += k.duration }129 outputStarts = starts; outputDuration = acc130 }131132 public var isIdentity: Bool { kept.count == 1 && kept[0].start == .zero && kept[0].end == duration }133134 /// Output times where two kept ranges meet (a cut was removed there).135 public var joins: [MediaTime] { Array(outputStarts.dropFirst()) }136137 /// Source time shown at output time `t` (clamped to the output duration).138 public func toSource(_ t: MediaTime) -> MediaTime {139 guard !kept.isEmpty else { return .zero }140 if t <= .zero { return kept[0].start }141 var lo = 0, hi = outputStarts.count142 while lo < hi { let mid = (lo + hi) / 2; if outputStarts[mid] <= t { lo = mid + 1 } else { hi = mid } }143 let i = max(0, lo - 1)144 return min(kept[i].start + (t - outputStarts[i]), kept[i].end)145 }146147 /// Output time of a source time. A time inside a cut maps to the join that replaces the cut.148 public func toOutput(_ s: MediaTime) -> MediaTime {149 for (i, k) in kept.enumerated() {150 if s < k.start { return outputStarts[i] }151 if s < k.end { return outputStarts[i] + (s - k.start) }152 }153 return outputDuration154 }155156 public func isKept(_ s: MediaTime) -> Bool { kept.contains { $0.contains(s) } }157158 /// Output ranges covered by a source range (it may be split by cuts).159 public func outputRanges(for source: TimeRange) -> [TimeRange] {160 kept.enumerated().compactMap { i, k in161 k.intersection(source).map { TimeRange(start: outputStarts[i] + ($0.start - k.start), end: outputStarts[i] + ($0.end - k.start)) }162 }163 }164}165166/// Undo / redo stack of edit decision lists. Persisted with the project so that edits stay reversible across launches.167public struct EditHistory: Sendable, Codable, Hashable {168 public private(set) var current: EditDecisionList169 public private(set) var undoStack: [EditDecisionList]170 public private(set) var redoStack: [EditDecisionList]171 public static let limit = 200172173 public init(current: EditDecisionList = EditDecisionList()) { self.current = current; undoStack = []; redoStack = [] }174175 public var canUndo: Bool { !undoStack.isEmpty }176 public var canRedo: Bool { !redoStack.isEmpty }177178 public mutating func apply(_ change: (inout EditDecisionList) -> Void) {179 var next = current; change(&next)180 guard next != current else { return }181 undoStack.append(current); if undoStack.count > Self.limit { undoStack.removeFirst() }182 redoStack.removeAll(); current = next183 }184 public mutating func undo() { guard let p = undoStack.popLast() else { return }; redoStack.append(current); current = p }185 public mutating func redo() { guard let n = redoStack.popLast() else { return }; undoStack.append(current); current = n }186 /// Back to the unedited recording (itself undoable).187 public mutating func revertToOriginal() { apply { $0 = EditDecisionList() } }188}189