SPB Git

Repository Public License

WaveformView.swift 10.2 KB 209 lines swift

1// ORIX Convert — App/Sources/Features/QualityLab/WaveformView.swift2// Description: Two waveforms stacked on one time axis (source above, result below), drawn from the min/max peaks3//              measured by the media engine. Horizontal zoom (pinch, ⌘-scroll, buttons) and scroll, shared by both.4// Author: Simon-Pierre Boucher — contact@spboucher.ai5import AppKit6import EngineMedia7import Observation8import SwiftUI910@Observable final class WaveViewport {11    /// 1 shows the whole duration; `n` shows 1/n of it.12    var zoom = 1.013    /// Start of the visible window, 0…1 of the duration.14    var start = 0.01516    static let range: ClosedRange<Double> = 1...2561718    func set(zoom value: Double, anchor: Double = 0.5) {19        let old = zoom20        let next = min(Self.range.upperBound, max(Self.range.lowerBound, value))21        // Keep the time under the anchor where it is.22        let time = start + anchor / old23        zoom = next24        start = min(max(0, 1 - 1 / next), max(0, time - anchor / next))25    }2627    func scroll(by fraction: Double) { start = min(max(0, 1 - 1 / zoom), max(0, start + fraction / zoom)) }28    func zoomIn() { set(zoom: zoom * 2) }29    func zoomOut() { set(zoom: zoom / 2) }30    func fit() { zoom = 1; start = 0 }31}3233struct WaveformCompare: NSViewRepresentable {34    var top: AudioWaveform?35    var bottom: AudioWaveform?36    var topLabel: String37    var bottomLabel: String38    var viewport: WaveViewport3940    func makeNSView(context: Context) -> WaveformNSView {41        let view = WaveformNSView()42        apply(to: view)43        return view44    }4546    func updateNSView(_ view: WaveformNSView, context: Context) {47        _ = (viewport.zoom, viewport.start)48        apply(to: view)49    }5051    private func apply(to view: WaveformNSView) {52        view.top = top; view.bottom = bottom53        view.topLabel = topLabel; view.bottomLabel = bottomLabel54        view.viewport = viewport55        view.needsDisplay = true56    }57}5859final class WaveformNSView: NSView {60    var top: AudioWaveform?61    var bottom: AudioWaveform?62    var topLabel = ""63    var bottomLabel = ""64    var viewport = WaveViewport()65    private var lastDragX: CGFloat?6667    override var isFlipped: Bool { true }68    override var acceptsFirstResponder: Bool { true }6970    private var duration: Double { max(top?.durationSeconds ?? 0, bottom?.durationSeconds ?? 0) }71    private var plot: CGRect { bounds.insetBy(dx: 16, dy: 0) }7273    override func draw(_ dirtyRect: NSRect) {74        guard let context = NSGraphicsContext.current?.cgContext else { return }75        let dark = effectiveAppearance.bestMatch(from: [.darkAqua, .aqua]) == .darkAqua76        context.setFillColor((dark ? NSColor(hex: 0x0F1322) : NSColor(hex: 0xF0F1F7)).cgColor)77        context.fill(bounds)78        let axisHeight: CGFloat = 2679        let laneHeight = (bounds.height - axisHeight - 12) / 280        let lanes = [CGRect(x: plot.minX, y: 6, width: plot.width, height: laneHeight), CGRect(x: plot.minX, y: 6 + laneHeight + axisHeight, width: plot.width, height: laneHeight)]81        let total = duration82        guard total > 0, plot.width > 10, laneHeight > 10 else { return }83        let visibleStart = viewport.start * total, visibleLength = total / viewport.zoom84        drawAxis(in: CGRect(x: plot.minX, y: lanes[0].maxY, width: plot.width, height: axisHeight), start: visibleStart, length: visibleLength, context: context, dark: dark)85        let colors = [dark ? NSColor(hex: 0xFDBA4D) : NSColor(hex: 0xC2410C), dark ? NSColor(hex: 0x7CB0FF) : NSColor(hex: 0x4338CA)]86        for (index, wave) in [top, bottom].enumerated() {87            let lane = lanes[index]88            context.setFillColor((dark ? NSColor(hex: 0x141828) : NSColor(hex: 0xFFFFFF)).cgColor)89            let box = CGPath(roundedRect: lane, cornerWidth: 8, cornerHeight: 8, transform: nil)90            context.addPath(box); context.fillPath()91            context.setStrokeColor((dark ? NSColor(hex: 0x262C44) : NSColor(hex: 0xE3E6EF)).cgColor)92            context.setLineWidth(1)93            context.addPath(box); context.strokePath()94            context.move(to: CGPoint(x: lane.minX, y: lane.midY)); context.addLine(to: CGPoint(x: lane.maxX, y: lane.midY)); context.strokePath()95            if let wave { drawWave(wave, in: lane, start: visibleStart, length: visibleLength, color: colors[index].cgColor, context: context) }96            drawLabel(index == 0 ? topLabel : bottomLabel, at: CGPoint(x: lane.minX + 8, y: lane.minY + 6), dark: dark)97        }98    }99100    /// One vertical line per device column, from the lowest to the highest sample of the buckets it covers.101    private func drawWave(_ wave: AudioWaveform, in lane: CGRect, start: Double, length: Double, color: CGColor, context: CGContext) {102        let count = min(wave.minimums.count, wave.maximums.count)103        guard count > 0, wave.durationSeconds > 0 else { return }104        let scale = window?.backingScaleFactor ?? 2105        let columns = Int(lane.width * scale)106        let perSecond = Double(count) / wave.durationSeconds107        let half = lane.height / 2 - 4108        context.saveGState()109        context.clip(to: lane)110        context.setStrokeColor(color)111        context.setLineWidth(1 / scale)112        for column in 0..<columns {113            let t0 = start + length * Double(column) / Double(columns), t1 = start + length * Double(column + 1) / Double(columns)114            if t0 >= wave.durationSeconds { break }115            let first = max(0, Int(t0 * perSecond)), last = min(count - 1, max(first, Int(t1 * perSecond)))116            var low = Float.greatestFiniteMagnitude, high = -Float.greatestFiniteMagnitude117            for bucket in first...last { low = min(low, wave.minimums[bucket]); high = max(high, wave.maximums[bucket]) }118            let x = lane.minX + (CGFloat(column) + 0.5) / scale119            let y0 = lane.midY - CGFloat(max(-1, min(1, high))) * half, y1 = lane.midY - CGFloat(max(-1, min(1, low))) * half120            context.move(to: CGPoint(x: x, y: y0))121            context.addLine(to: CGPoint(x: x, y: max(y1, y0 + 1 / scale)))122        }123        context.strokePath()124        context.restoreGState()125    }126127    private func drawAxis(in rect: CGRect, start: Double, length: Double, context: CGContext, dark: Bool) {128        let candidates: [Double] = [0.001, 0.002, 0.005, 0.01, 0.02, 0.05, 0.1, 0.2, 0.5, 1, 2, 5, 10, 15, 30, 60, 120, 300, 600, 1800, 3600]129        let step = candidates.first { length / $0 <= Double(rect.width / 90) } ?? 3600130        let color = dark ? NSColor(hex: 0x7A829D) : NSColor(hex: 0x767C90)131        let attributes: [NSAttributedString.Key: Any] = [.font: NSFont.monospacedDigitSystemFont(ofSize: 10, weight: .regular), .foregroundColor: color]132        context.setStrokeColor(color.withAlphaComponent(0.5).cgColor)133        context.setLineWidth(1)134        var tick = (start / step).rounded(.up) * step135        while tick <= start + length + step * 0.001 {136            let x = rect.minX + CGFloat((tick - start) / length) * rect.width137            context.move(to: CGPoint(x: x, y: rect.minY + 2)); context.addLine(to: CGPoint(x: x, y: rect.minY + 7)); context.strokePath()138            let text = NSAttributedString(string: Self.timeText(tick, step: step), attributes: attributes)139            let size = text.size()140            text.draw(at: CGPoint(x: min(rect.maxX - size.width, max(rect.minX, x - size.width / 2)), y: rect.minY + 9))141            tick += step142        }143    }144145    static func timeText(_ seconds: Double, step: Double) -> String {146        let decimals = step >= 1 ? 0 : (step >= 0.1 ? 1 : (step >= 0.01 ? 2 : 3))147        if seconds >= 60 {148            let minutes = Int(seconds) / 60149            let rest = seconds - Double(minutes * 60)150            return "\(minutes):" + (rest < 10 ? "0" : "") + rest.formatted(.number.precision(.fractionLength(decimals)))151        }152        return Measurement(value: seconds, unit: UnitDuration.seconds).formatted(.measurement(width: .narrow, usage: .asProvided, numberFormatStyle: .number.precision(.fractionLength(decimals))))153    }154155    private func drawLabel(_ text: String, at point: CGPoint, dark: Bool) {156        guard !text.isEmpty else { return }157        let string = NSAttributedString(string: text, attributes: [.font: NSFont.systemFont(ofSize: 11, weight: .semibold), .foregroundColor: dark ? NSColor(hex: 0xA3ABC2) : NSColor(hex: 0x555B6E)])158        string.draw(at: point)159    }160161    private func anchor(for event: NSEvent) -> Double {162        let x = convert(event.locationInWindow, from: nil).x163        return Double(min(1, max(0, (x - plot.minX) / max(1, plot.width))))164    }165166    override func scrollWheel(with event: NSEvent) {167        if event.modifierFlags.contains(.command) || (!event.hasPreciseScrollingDeltas && abs(event.scrollingDeltaY) > abs(event.scrollingDeltaX)) {168            let delta = event.hasPreciseScrollingDeltas ? event.scrollingDeltaY / 120 : event.scrollingDeltaY / 12169            viewport.set(zoom: viewport.zoom * pow(2, Double(delta)), anchor: anchor(for: event))170        } else {171            let delta = abs(event.scrollingDeltaX) > abs(event.scrollingDeltaY) ? event.scrollingDeltaX : event.scrollingDeltaY172            viewport.scroll(by: -Double(delta / max(1, plot.width)))173        }174        needsDisplay = true175    }176177    override func magnify(with event: NSEvent) {178        viewport.set(zoom: viewport.zoom * (1 + Double(event.magnification)), anchor: anchor(for: event))179        needsDisplay = true180    }181182    override func mouseDown(with event: NSEvent) {183        window?.makeFirstResponder(self)184        lastDragX = convert(event.locationInWindow, from: nil).x185    }186187    override func mouseDragged(with event: NSEvent) {188        let x = convert(event.locationInWindow, from: nil).x189        if let lastDragX { viewport.scroll(by: -Double((x - lastDragX) / max(1, plot.width))) }190        lastDragX = x191        needsDisplay = true192    }193194    override func keyDown(with event: NSEvent) {195        switch event.keyCode {196        case 123: viewport.scroll(by: -0.1)197        case 124: viewport.scroll(by: 0.1)198        default:199            switch event.charactersIgnoringModifiers {200            case "+", "=": viewport.zoomIn()201            case "-": viewport.zoomOut()202            case "0": viewport.fit()203            default: super.keyDown(with: event); return204            }205        }206        needsDisplay = true207    }208}209
Files main
Menu

Theme