SPB Git

Repository Public License

WaveformRendering.swift 10.3 KB 201 lines swift

1//2//  ORIX Audio3//  File: ORIXAudio/Features/Visuals/WaveformRendering.swift4//  Description: Waveform drawing from measured buckets (four styles), shared by the live view, the file view, thumbnails and image export.5//6//  Author: Simon-Pierre Boucher7//  Contact: contact@spboucher.ai8//9import CoreGraphics10import ORIXAudioCore11import SwiftUI12import UIKit1314enum WaveformRendering {15    /// Merges `buckets` into exactly `count` bars (min of mins, max of maxes, RMS and band power averaged).16    static func rebin(_ buckets: ArraySlice<WaveformBucket>, to count: Int) -> [WaveformBucket] {17        guard count > 0, !buckets.isEmpty else { return [] }18        if buckets.count <= count { return Array(buckets) }19        var out: [WaveformBucket] = []20        out.reserveCapacity(count)21        let base = buckets.startIndex, n = buckets.count22        for i in 0..<count {23            let a = base + i * n / count, b = max(a + 1, base + (i + 1) * n / count)24            var mn: Float = .greatestFiniteMagnitude, mx: Float = -.greatestFiniteMagnitude, ms: Float = 025            var bands = SIMD8<Float>.zero26            for j in a..<b { let k = buckets[j]; mn = min(mn, k.min); mx = max(mx, k.max); ms += k.rms * k.rms; bands += k.bands }27            let c = Float(b - a)28            out.append(WaveformBucket(min: mn, max: mx, rms: (ms / c).squareRoot(), bands: bands / c))29        }30        return out31    }3233    /// Draws bars into `rect`. `barWidth` points per bar including the gap. Amplitude ±1 maps to the full height.34    static func draw(_ bars: [WaveformBucket], in rect: CGRect, context: inout GraphicsContext, style: WaveformStyle, barWidth: CGFloat,35                     alignTrailing: Bool = false, gain: CGFloat = 1, dimmed: Bool = false) {36        guard !bars.isEmpty else { return }37        let mid = rect.midY, half = rect.height / 238        let width = max(1, barWidth - (barWidth >= 3 ? 1 : 0))39        let originX = alignTrailing ? rect.maxX - CGFloat(bars.count) * barWidth : rect.minX40        let opacity = dimmed ? 0.35 : 1.041        for (i, bar) in bars.enumerated() {42            let x = originX + CGFloat(i) * barWidth43            if x + width < rect.minX { continue }44            let top = mid - min(1, CGFloat(bar.max) * gain) * half, bottom = mid - max(-1, CGFloat(bar.min) * gain) * half45            let barRect = CGRect(x: x, y: min(top, bottom), width: width, height: max(1, abs(bottom - top)))46            switch style {47            case .amplitude:48                context.fill(Path(roundedRect: barRect, cornerRadius: width / 2), with: .color(Color(uiColor: UIColor(hex: 0x22D3EE)).opacity(opacity)))49            case .envelope:50                context.fill(Path(roundedRect: barRect, cornerRadius: width / 2), with: .color(Color(uiColor: UIColor(hex: 0x8B5CF6)).opacity(0.45 * opacity)))51                let r = min(1, CGFloat(bar.rms) * gain) * half52                context.fill(Path(roundedRect: CGRect(x: x, y: mid - r, width: width, height: max(1, 2 * r)), cornerRadius: width / 2),53                             with: .color(Color(uiColor: UIColor(hex: 0x22D3EE)).opacity(opacity)))54            case .spectral:55                context.fill(Path(roundedRect: barRect, cornerRadius: width / 2), with: .color(ORIX.blend(bar.bandAmplitudeFractions).opacity(opacity)))56            case .bands:57                // The bar is split bottom → top into the measured share of each band (sub-bass at the bottom).58                let fractions = bar.bandAmplitudeFractions59                var y = barRect.maxY60                if fractions.allSatisfy({ $0 == 0 }) {61                    context.fill(Path(barRect), with: .color(ORIX.Palette.plotText.opacity(0.4 * opacity)))62                } else {63                    for (b, f) in fractions.enumerated() where f > 0 {64                        let h = barRect.height * CGFloat(f)65                        context.fill(Path(CGRect(x: x, y: y - h, width: width, height: h)), with: .color(ORIX.bandColors[b].opacity(opacity)))66                        y -= h67                    }68                }69            }70        }71    }7273    /// Renders a whole summary to a bitmap (image export). The legend states what the colours mean.74    @MainActor75    static func image(summary: WaveformSummary, style: WaveformStyle, size: CGSize, title: String) -> CGImage? {76        let view = ZStack(alignment: .topLeading) {77            ORIX.Palette.plot78            Canvas { context, canvasSize in79                let rect = CGRect(origin: .zero, size: canvasSize).insetBy(dx: 24, dy: 60)80                let count = Int(rect.width / 3)81                let view = summary.buckets(for: 0...max(summary.duration, 0.001), points: count)82                let bars = rebin(view.buckets, to: count)83                var c = context84                c.stroke(Path { $0.move(to: CGPoint(x: rect.minX, y: rect.midY)); $0.addLine(to: CGPoint(x: rect.maxX, y: rect.midY)) }, with: .color(ORIX.Palette.plotGrid), lineWidth: 1)85                draw(bars, in: rect, context: &c, style: style, barWidth: rect.width / CGFloat(max(1, bars.count)))86            }87            VStack(alignment: .leading, spacing: 4) {88                Text(title).font(.system(size: 22, weight: .semibold)).foregroundStyle(.white)89                Text("ORIX Audio · \(Timecode.clock(summary.duration)) · amplitude ±1.0 FS")90                    .font(.system(size: 13)).foregroundStyle(.white.opacity(0.6))91            }.padding(20)92            if style == .spectral || style == .bands {93                BandLegend().padding(20).frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .bottomLeading)94            }95        }96        .frame(width: size.width, height: size.height)97        .environment(\.colorScheme, .dark)98        let renderer = ImageRenderer(content: view)99        renderer.scale = 2100        return renderer.cgImage101    }102}103104/// Names each band colour with its frequency range.105struct BandLegend: View {106    var compact = false107    var body: some View {108        FlowLayout(spacing: compact ? 6 : 10) {109            ForEach(Array(FrequencyBandLayout.orix.bands.enumerated()), id: \.offset) { i, band in110                HStack(spacing: 4) {111                    RoundedRectangle(cornerRadius: 2).fill(ORIX.bandColors[i]).frame(width: 10, height: 10)112                    Text(compact ? ORIX.bandShortNames[i] : "\(ORIX.bandShortNames[i]) \(Self.range(band))")113                        .font(.system(.caption2, design: .monospaced).weight(.semibold)).foregroundStyle(Color.white.opacity(0.8))114                }115            }116        }117        .frame(minHeight: 44, alignment: .bottomLeading)118        .contentShape(Rectangle())119        // Read as one sentence: the legend is a key, not seven separate controls.120        .accessibilityElement(children: .ignore)121        .accessibilityLabel(Text("Colour key, low to high frequency: \(FrequencyBandLayout.orix.bands.indices.map { CoreText.bandName($0) }.joined(separator: ", "))"))122    }123    static func range(_ b: FrequencyBand) -> String {124        func f(_ v: Double) -> String { v >= 1000 ? "\(Int(v / 1000))k" : "\(Int(v))" }125        return "\(f(b.lowerHz))–\(f(b.upperHz))"126    }127}128129/// Scrolling waveform of the audio being captured. Reads the engine's visuals store on the display's schedule; the audio130/// threads are never asked to wait for a frame.131struct LiveWaveformView: View {132    let visuals: LiveVisuals133    let style: WaveformStyle134    var isActive = true135    @Environment(\.accessibilityReduceMotion) private var reduceMotion136137    var body: some View {138        GeometryReader { geo in139            TimelineView(.animation(minimumInterval: reduceMotion ? 0.2 : 1.0 / 60, paused: !isActive)) { timeline in140                // The buckets are fetched here, as view input, so each tick hands the canvas new data and forces a redraw.141                let barWidth: CGFloat = 3142                let bars = visuals.read { Array($0.buckets.suffix(Int(geo.size.width / barWidth) + 1)) }143                LiveWaveformCanvas(bars: bars, style: style, barWidth: barWidth, tick: timeline.date)144            }145        }146        .accessibilityElement(children: .ignore)147        .accessibilityLabel(Text("Live waveform"))148    }149}150151private struct LiveWaveformCanvas: View {152    let bars: [WaveformBucket]153    let style: WaveformStyle154    let barWidth: CGFloat155    let tick: Date156157    var body: some View {158        Canvas { context, size in159            let rect = CGRect(origin: .zero, size: size).insetBy(dx: 0, dy: 10)160            var c = context161            c.stroke(Path { $0.move(to: CGPoint(x: 0, y: rect.midY)); $0.addLine(to: CGPoint(x: size.width, y: rect.midY)) }, with: .color(ORIX.Palette.plotGrid), lineWidth: 1)162            for level in [0.5, 1.0] {163                for sign in [-1.0, 1.0] {164                    let y = rect.midY - sign * level * rect.height / 2165                    c.stroke(Path { $0.move(to: CGPoint(x: 0, y: y)); $0.addLine(to: CGPoint(x: size.width, y: y)) }, with: .color(ORIX.Palette.plotGrid.opacity(0.5)), style: StrokeStyle(lineWidth: 0.5, dash: [2, 4]))166                }167            }168            WaveformRendering.draw(bars, in: rect, context: &c, style: style, barWidth: barWidth, alignTrailing: true)169        }170    }171}172173/// Small static waveform for library rows, drawn from the cached summary's coarsest level.174struct WaveformThumbnail: View {175    let recordingID: UUID176    let revision: Int177    @State private var bars: [WaveformBucket] = []178179    var body: some View {180        Canvas { context, size in181            var c = context182            let rect = CGRect(origin: .zero, size: size)183            if bars.isEmpty {184                c.stroke(Path { $0.move(to: CGPoint(x: 0, y: rect.midY)); $0.addLine(to: CGPoint(x: size.width, y: rect.midY)) }, with: .color(ORIX.Palette.plotGrid), lineWidth: 1)185            } else {186                let peak = bars.map(\.peak).max() ?? 1187                WaveformRendering.draw(bars, in: rect.insetBy(dx: 2, dy: 3), context: &c, style: .spectral, barWidth: (size.width - 4) / CGFloat(bars.count),188                                       gain: peak > 0.01 ? CGFloat(0.95 / peak) : 1)189            }190        }191        .task(id: "\(recordingID)-\(revision)") {192            let id = recordingID193            bars = await Task.detached(priority: .utility) { () -> [WaveformBucket] in194                guard let summary = LibraryFiles.waveform(id), let top = summary.levels.last else { return [] }195                return WaveformRendering.rebin(top[...], to: 40)196            }.value197        }198        .accessibilityHidden(true)199    }200}201
Files main
Menu

Theme