SPB Git

Repository Public MIT

GlassWaveform.swift 10.8 KB 247 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : SP GlassKit7// File             : Sources/SPGlassMedia/Media/GlassWaveform.swift8// Module           : SPGlassMedia9// Repository       : https://git.spboucher.ai/sp-glasskit10// Project Website  : https://glass.spboucher.ai11// Created          : 2026-12-0212// Last Modified    : 2026-12-0313//14// Author           : Simon-Pierre Boucher15// Position         : Professor of Finance16// Institution      : Université du Québec en Outaouais (UQO)17// Organization     : SP Boucher18// Website          : https://spboucher.ai19// Git              : https://git.spboucher.ai20//21// Preferred Contact: contact@spboucher.ai22// Development      : dev@spboucher.ai23// Support          : support@spboucher.ai24// Security/Admin   : admin@spboucher.ai25//26// Copyright (c) 202627// Simon-Pierre Boucher28// All rights reserved where applicable. This file is governed by the29// applicable project license, copyright notices and relevant law.30// Existing third-party rights and notices remain unaffected.31//32// License          : MIT33//34// Do not embed credentials, private keys, access tokens,35// certificates or confidential personal information.36//37// =============================================================================38// END OF SP BOUCHER SOURCE HEADER39// =============================================================================4041import SwiftUI42import SPGlassCore43import SPGlassTokens44import SPGlassThemes4546/// How the samples of one bucket are reduced to a single amplitude.47public enum GlassWaveformAggregation: String, CaseIterable, Sendable {48    /// The largest amplitude of the bucket. Keeps transients visible.49    case peak50    /// The root mean square of the bucket. Closer to perceived loudness.51    case rms52}5354/// Aggregates any number of amplitude samples into a bounded number of buckets.55public enum GlassWaveformDownsampler {56    /// Upper limit of `maxBuckets`, whatever the caller asks for.57    public static let bucketLimit = 40965859    /// A drawable amplitude: the magnitude clamped to 0…1. NaN becomes 0 and infinities become 1.60    public static func sanitized(_ sample: Float) -> Float {61        if sample.isNaN { return 0 }62        return min(abs(sample), 1)63    }6465    /// Reduces `samples` to at most `maxBuckets` amplitudes in 0…1.66    ///67    /// Inputs that already fit are only sanitised. The cost is one pass over the input; the output never68    /// exceeds `min(maxBuckets, bucketLimit)` values, and an empty input gives an empty output.69    public static func downsample(_ samples: [Float], maxBuckets: Int, aggregation: GlassWaveformAggregation = .peak) -> [Float] {70        let limit = min(max(maxBuckets, 1), bucketLimit)71        guard !samples.isEmpty else { return [] }72        guard samples.count > limit else { return samples.map(sanitized) }73        var buckets: [Float] = []74        buckets.reserveCapacity(limit)75        let count = samples.count76        for bucket in 0..<limit {77            // Integer bounds so that every sample belongs to exactly one bucket.78            let start = bucket * count / limit79            let end = max((bucket + 1) * count / limit, start + 1)80            var peak: Float = 081            var sumOfSquares: Double = 082            for index in start..<min(end, count) {83                let value = sanitized(samples[index])84                peak = max(peak, value)85                sumOfSquares += Double(value) * Double(value)86            }87            switch aggregation {88            case .peak: buckets.append(peak)89            case .rms: buckets.append(Float((sumOfSquares / Double(min(end, count) - start)).squareRoot()))90            }91        }92        return buckets93    }94}9596/// Samples prepared for drawing: downsampled once, then reused by every frame.97///98/// Build it when the audio is loaded (off the main actor for large inputs: the type is `Sendable`) and keep it99/// in the host's state.100public struct GlassWaveformData: Equatable, Sendable {101    /// Amplitudes in 0…1, at most the requested number of buckets.102    public let buckets: [Float]103    /// Number of samples the data was built from.104    public let sampleCount: Int105    /// Largest amplitude, 0…1.106    public let peak: Float107108    public init(samples: [Float], maxBuckets: Int = 120, aggregation: GlassWaveformAggregation = .peak) {109        buckets = GlassWaveformDownsampler.downsample(samples, maxBuckets: maxBuckets, aggregation: aggregation)110        sampleCount = samples.count111        peak = buckets.max() ?? 0112    }113114    public static let empty = GlassWaveformData(samples: [])115116    public var isEmpty: Bool { buckets.isEmpty }117118    /// Peak level as a whole percentage.119    public var peakPercent: Int { Int((peak * 100).rounded()) }120121    /// The textual description read by assistive technologies.122    public var accessibilitySummary: String {123        isEmpty ? GlassL10n.string(.noData) : GlassL10n.string(.waveformSummary, sampleCount, peakPercent)124    }125126    /// Number of buckets that are entirely before `progress` (0…1).127    public func playedBucketCount(progress: Double?) -> Int {128        guard let progress, !progress.isNaN else { return 0 }129        return Int((min(max(progress, 0), 1) * Double(buckets.count)).rounded(.down))130    }131}132133/// Amplitude bars drawn with `Canvas`.134///135/// ```swift136/// @State private var waveform = GlassWaveformData(samples: samples, maxBuckets: 160)137///138/// GlassWaveform(waveform, progress: playback.currentTime / playback.duration)139/// ```140///141/// The view draws what ``GlassWaveformData`` already aggregated; nothing is recomputed per frame. With a142/// `progress` the bars before that fraction take the theme's primary colour, the others are dimmed, and a143/// playhead marks the position. Assistive technologies get one element with a textual summary (sample count144/// and peak level) and the progress as its value.145public struct GlassWaveform: View {146    @GlassThemed private var theme147    @Environment(\.layoutDirection) private var layoutDirection148    private let data: GlassWaveformData149    private let progress: Double?150    private let minimumHeight: CGFloat151    private let showsPlayhead: Bool152153    /// - Parameters:154    ///   - data: samples aggregated once by the host.155    ///   - progress: played fraction, 0…1; `nil` draws every bar in the same colour.156    ///   - minimumHeight: smallest height of the drawing. The view grows with the space it is given.157    ///   - showsPlayhead: draws a thin vertical marker at `progress`. Ignored without a progress.158    public init(_ data: GlassWaveformData, progress: Double? = nil, minimumHeight: CGFloat = 48, showsPlayhead: Bool = true) {159        self.data = data160        self.progress = progress161        self.minimumHeight = max(minimumHeight, 8)162        self.showsPlayhead = showsPlayhead163    }164165    /// Convenience for small sample arrays. The samples are aggregated each time the parent view is rebuilt:166    /// for long recordings build a ``GlassWaveformData`` once and use ``init(_:progress:minimumHeight:showsPlayhead:)``.167    public init(168        samples: [Float],169        maxBuckets: Int = 120,170        aggregation: GlassWaveformAggregation = .peak,171        progress: Double? = nil,172        minimumHeight: CGFloat = 48,173        showsPlayhead: Bool = true174    ) {175        self.init(GlassWaveformData(samples: samples, maxBuckets: maxBuckets, aggregation: aggregation), progress: progress, minimumHeight: minimumHeight, showsPlayhead: showsPlayhead)176    }177178    public var body: some View {179        let buckets = data.buckets180        let played = data.playedBucketCount(progress: progress)181        let playedColor = theme.color(.primary)182        let restColor = progress == nil183            ? theme.color(.textPrimary).opacity(0.8)184            : theme.color(.textSecondary).opacity(theme.increasedContrast ? 0.85 : 0.45)185        let playheadColor = theme.color(.textPrimary)186        let fraction = GlassWaveformLayout.clampedProgress(progress)187        let isMirrored = layoutDirection == .rightToLeft188        let drawsPlayhead = showsPlayhead189        Canvas(opaque: false, rendersAsynchronously: false) { context, size in190            guard !buckets.isEmpty, size.width > 0, size.height > 0 else { return }191            if isMirrored {192                context.translateBy(x: size.width, y: 0)193                context.scaleBy(x: -1, y: 1)194            }195            let step = size.width / CGFloat(buckets.count)196            let barWidth = GlassWaveformLayout.barWidth(step: step)197            for (index, amplitude) in buckets.enumerated() {198                let height = GlassWaveformLayout.barHeight(amplitude: amplitude, available: size.height)199                let rect = CGRect(200                    x: CGFloat(index) * step + (step - barWidth) / 2,201                    y: (size.height - height) / 2,202                    width: barWidth,203                    height: height204                )205                context.fill(Path(roundedRect: rect, cornerRadius: barWidth / 2), with: .color(index < played ? playedColor : restColor))206            }207            if drawsPlayhead, let fraction {208                let x = min(max(size.width * fraction, 1), size.width - 1)209                let line = CGRect(x: x - 1, y: 0, width: 2, height: size.height)210                context.fill(Path(roundedRect: line, cornerRadius: 1), with: .color(playheadColor))211            }212        }213        .frame(minHeight: minimumHeight)214        .accessibilityElement()215        .accessibilityLabel(Text(data.accessibilitySummary))216        .accessibilityValue(progressValue)217        .accessibilityAddTraits(.isImage)218    }219220    private var progressValue: Text {221        guard let fraction = GlassWaveformLayout.clampedProgress(progress) else { return Text(verbatim: "") }222        return Text(fraction.formatted(.percent.precision(.fractionLength(0))))223    }224}225226/// Geometry of the bars of a ``GlassWaveform``.227public enum GlassWaveformLayout {228    /// Share of each bucket's width that the bar occupies; the rest is the gap.229    public static let barFill: CGFloat = 0.6230231    /// Width of a bar for a bucket `step` points wide: the fill share, between 1 and 4 points.232    public static func barWidth(step: CGFloat) -> CGFloat {233        min(max(step * barFill, 1), 4)234    }235236    /// Height of a bar: proportional to the amplitude, never below 2 points so that silence stays visible.237    public static func barHeight(amplitude: Float, available: CGFloat) -> CGFloat {238        min(max(CGFloat(GlassWaveformDownsampler.sanitized(amplitude)) * available, 2), max(available, 0))239    }240241    /// A drawable progress: `nil` for missing or NaN values, clamped to 0…1 otherwise.242    public static func clampedProgress(_ progress: Double?) -> Double? {243        guard let progress, !progress.isNaN else { return nil }244        return min(max(progress, 0), 1)245    }246}247
Files main
Menu

Theme