Repository Public License
1//2// ORIX Audio3// File: Core/Sources/ORIXAudioCore/Editing/EditDocument.swift4// Description: Non-destructive edit decision list with undo / redo. Source files are never modified.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8//9import Foundation1011public enum ChannelMode: String, Codable, Sendable, CaseIterable, Identifiable {12 case original, left, right, mono13 public var id: String { rawValue }14}1516/// A piece of the timeline: a range of a source file, or generated silence.17public struct EditClip: Codable, Sendable, Hashable, Identifiable {18 public enum Source: Codable, Sendable, Hashable {19 /// Index into `EditDocument.sources`, and the start offset inside that file (seconds).20 case file(index: Int, start: Double)21 case silence22 }23 public var id = UUID()24 public var source: Source25 public var duration: Double26 public var gainDB: Double = 02728 public init(source: Source, duration: Double, gainDB: Double = 0) { self.source = source; self.duration = duration; self.gainDB = gainDB }2930 /// The part of this clip between local offsets `a` and `b` (seconds from the clip start).31 func slice(_ a: Double, _ b: Double) -> EditClip {32 var c = self33 c.id = UUID()34 c.duration = b - a35 if case .file(let i, let start) = source { c.source = .file(index: i, start: start + a) }36 return c37 }38}3940public struct EditState: Codable, Sendable, Hashable {41 public var clips: [EditClip] = []42 public var fadeIn: Double = 043 public var fadeOut: Double = 044 /// Gain applied to the whole programme, dB.45 public var masterGainDB: Double = 046 public var channelMode: ChannelMode = .original47 public var effects: [AudioEffect] = []4849 public var duration: Double { clips.reduce(0) { $0 + $1.duration } }50}5152/// The editable document. Every mutation pushes the previous state on the undo stack.53public struct EditDocument: Codable, Sendable {54 /// Relative file names of the audio files referenced by clips (index 0 is the original recording).55 public var sources: [String]56 public private(set) var state: EditState57 public private(set) var undoStack: [EditState] = []58 public private(set) var redoStack: [EditState] = []59 public private(set) var actionNames: [String] = []60 public static let historyLimit = 10061 static let epsilon = 1e-66263 public init(sourceName: String, duration: Double) {64 sources = [sourceName]65 state = EditState(clips: [EditClip(source: .file(index: 0, start: 0), duration: duration)])66 }6768 public var duration: Double { state.duration }69 public var canUndo: Bool { !undoStack.isEmpty }70 public var canRedo: Bool { !redoStack.isEmpty }71 public var isEdited: Bool { !undoStack.isEmpty }72 public var lastActionName: String? { actionNames.last }7374 private mutating func mutate(_ name: String, _ body: (inout EditState) -> Void) {75 var next = state76 body(&next)77 guard next != state else { return }78 undoStack.append(state)79 actionNames.append(name)80 if undoStack.count > Self.historyLimit { undoStack.removeFirst(); actionNames.removeFirst() }81 redoStack.removeAll()82 state = next83 }8485 public mutating func undo() { guard let s = undoStack.popLast() else { return }; redoStack.append(state); state = s; if !actionNames.isEmpty { actionNames.removeLast() } }86 public mutating func redo() { guard let s = redoStack.popLast() else { return }; undoStack.append(state); actionNames.append("Redo"); state = s }8788 /// Clips covering [a, b) of the timeline, cut at the boundaries.89 static func slice(_ clips: [EditClip], from a: Double, to b: Double) -> [EditClip] {90 var out: [EditClip] = []91 var t = 0.092 for c in clips {93 let start = t, end = t + c.duration94 t = end95 let lo = max(a, start), hi = min(b, end)96 if hi - lo > epsilon { out.append(c.slice(lo - start, hi - start)) }97 }98 return out99 }100101 private func clamp(_ r: ClosedRange<Double>) -> (Double, Double) { (max(0, min(duration, r.lowerBound)), max(0, min(duration, r.upperBound))) }102103 // MARK: Operations104105 /// Keeps only the selection (crop / trim).106 public mutating func crop(to range: ClosedRange<Double>) {107 let (a, b) = clamp(range)108 guard b - a > Self.epsilon else { return }109 mutate("Crop") { $0.clips = Self.slice($0.clips, from: a, to: b) }110 }111112 /// Removes the selection and closes the gap.113 public mutating func delete(_ range: ClosedRange<Double>) {114 let (a, b) = clamp(range)115 guard b - a > Self.epsilon else { return }116 let total = duration117 mutate("Delete") { $0.clips = Self.slice($0.clips, from: 0, to: a) + Self.slice($0.clips, from: b, to: total) }118 }119120 /// Cuts the clip under `time` in two (no audible change; enables per-part operations).121 public mutating func split(at time: Double) {122 guard time > Self.epsilon, time < duration - Self.epsilon else { return }123 let total = duration124 mutate("Split") { $0.clips = Self.slice($0.clips, from: 0, to: time) + Self.slice($0.clips, from: time, to: total) }125 }126127 public mutating func insertSilence(at time: Double, duration d: Double) {128 guard d > Self.epsilon else { return }129 let t = max(0, min(duration, time)), total = duration130 mutate("Insert silence") {131 $0.clips = Self.slice($0.clips, from: 0, to: t) + [EditClip(source: .silence, duration: d)] + Self.slice($0.clips, from: t, to: total)132 }133 }134135 /// Replaces the selection with silence of the same length.136 public mutating func silence(_ range: ClosedRange<Double>) {137 let (a, b) = clamp(range)138 guard b - a > Self.epsilon else { return }139 let total = duration140 mutate("Silence") {141 $0.clips = Self.slice($0.clips, from: 0, to: a) + [EditClip(source: .silence, duration: b - a)] + Self.slice($0.clips, from: b, to: total)142 }143 }144145 /// Appends another audio file to the end (merge).146 public mutating func append(sourceName: String, duration d: Double) {147 guard d > Self.epsilon else { return }148 let index: Int149 if let existing = sources.firstIndex(of: sourceName) { index = existing } else { sources.append(sourceName); index = sources.count - 1 }150 mutate("Merge") { $0.clips.append(EditClip(source: .file(index: index, start: 0), duration: d)) }151 }152153 /// Adds gain to the selection, or to the whole programme when `range` is nil.154 public mutating func adjustGain(by dB: Double, in range: ClosedRange<Double>? = nil) {155 guard dB != 0 else { return }156 guard let range else { mutate("Gain") { $0.masterGainDB += dB }; return }157 let (a, b) = clamp(range)158 guard b - a > Self.epsilon else { return }159 let total = duration160 mutate("Gain") {161 let middle = Self.slice($0.clips, from: a, to: b).map { c -> EditClip in var c = c; c.gainDB += dB; return c }162 $0.clips = Self.slice($0.clips, from: 0, to: a) + middle + Self.slice($0.clips, from: b, to: total)163 }164 }165166 /// Sets the master gain so that the measured peak lands on `targetPeakDBFS`. `measuredPeakDBFS` comes from a render pass.167 public mutating func normalize(measuredPeakDBFS: Double, targetPeakDBFS: Double = -1) {168 guard measuredPeakDBFS > -120 else { return }169 mutate("Normalize") { $0.masterGainDB += targetPeakDBFS - measuredPeakDBFS }170 }171172 public mutating func setFadeIn(_ seconds: Double) { mutate("Fade in") { $0.fadeIn = max(0, seconds) } }173 public mutating func setFadeOut(_ seconds: Double) { mutate("Fade out") { $0.fadeOut = max(0, seconds) } }174 public mutating func setChannelMode(_ mode: ChannelMode) { mutate("Channels") { $0.channelMode = mode } }175 public mutating func setEffects(_ effects: [AudioEffect]) { mutate("Enhance") { $0.effects = effects } }176177 /// Removes every stretch the supplied silence list marks as silent, keeping `padding` seconds on each side.178 public mutating func removeSilences(_ silences: [TimeInterval2], padding: Double = 0.15) {179 let cuts = silences.map { TimeInterval2(start: $0.start + padding, end: $0.end - padding) }.filter { $0.duration > 0.05 }.sorted { $0.start < $1.start }180 guard !cuts.isEmpty else { return }181 let total = duration182 mutate("Remove silence") {183 var kept: [EditClip] = []184 var cursor = 0.0185 for c in cuts where c.start >= cursor { kept += Self.slice($0.clips, from: cursor, to: c.start); cursor = min(total, c.end) }186 kept += Self.slice($0.clips, from: cursor, to: total)187 $0.clips = kept188 }189 }190191 /// Fade gain (linear) at timeline time `t`: equal-power-free simple raised-cosine ramps.192 public static func fadeGain(at t: Double, state: EditState) -> Double {193 let d = state.duration194 var g = 1.0195 if state.fadeIn > 0, t < state.fadeIn { g *= 0.5 - 0.5 * cos(Double.pi * t / state.fadeIn) }196 if state.fadeOut > 0, t > d - state.fadeOut { g *= 0.5 - 0.5 * cos(Double.pi * max(0, d - t) / state.fadeOut) }197 return g198 }199}200