Repository Public License
1//2// ORIX Audio3// File: ORIXAudio/Features/Detail/AnalysisPanel.swift4// Description: Analysis dashboard: levels, loudness, spectral descriptors, band energy, speech activity (estimates) and findings.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8//9import ORIXAudioCore10import SwiftUI1112enum FindingText {13 static func title(_ f: DiagnosticFinding) -> String {14 switch f.kind {15 case .clipping: String(localized: "Clipping detected")16 case .lowLevel: String(localized: "Low recording level")17 case .elevatedNoise: String(localized: "Little contrast between quiet and loud parts")18 case .longSilence: String(localized: "Long silence detected")19 case .possibleDistortion: String(localized: "Potential distortion")20 case .narrowSpectrum: String(localized: "Unusual frequency concentration")21 case .dcOffset: String(localized: "DC offset present")22 case .limitedBandwidth: String(localized: "Limited bandwidth")23 case .healthy: String(localized: "No issues found")24 }25 }26 static func detail(_ f: DiagnosticFinding) -> String {27 let v = f.values28 switch f.kind {29 case .clipping: return String(localized: "\(Int(v["events"] ?? 0)) runs of full-scale samples (\(Int(v["samples"] ?? 0)) samples in total).")30 case .lowLevel: return String(localized: "Peak \(Formatters.dB(v["peakDBFS"] ?? 0, unit: "dBFS")), RMS \(Formatters.dB(v["rmsDBFS"] ?? 0, unit: "dBFS")). Normalizing can raise the level but also raises the noise.")31 case .elevatedNoise: return String(localized: "The quietest tenth of the recording sits at \(Formatters.dB(v["floorDBFS"] ?? 0, unit: "dBFS")), only \(Formatters.dB(v["spreadDB"] ?? 0)) below the loud parts. In a speech recording this usually means background noise; in music it can be normal.")32 case .longSilence: return String(localized: "Longest silence \(Timecode.clock(v["seconds"] ?? 0)); \(Timecode.clock(v["total"] ?? 0)) of silence in total.")33 case .possibleDistortion: return String(localized: "Clipping together with a crest factor of only \(Formatters.dB(v["crestDB"] ?? 0)) suggests sustained overload.")34 case .narrowSpectrum: return String(localized: "\(Int((v["fraction"] ?? 0) * 100)) % of the energy lies between \(Formatters.frequency(v["lowerHz"] ?? 0)) and \(Formatters.frequency(v["upperHz"] ?? 0)).")35 case .dcOffset: return String(localized: "The waveform is shifted by \(String(format: "%.3f", v["offset"] ?? 0)) of full scale. A high-pass filter removes it.")36 case .limitedBandwidth: return String(localized: "Almost no energy above 4 kHz (85 % is below \(Formatters.frequency(v["rolloffHz"] ?? 0))). The source may be band-limited: telephone, Bluetooth headset or a low bit rate.")37 case .healthy: return String(localized: "Levels, noise floor and spectrum are within ordinary ranges.")38 }39 }40 static func symbol(_ f: DiagnosticFinding) -> (String, Color) {41 switch f.severity {42 case .warning: ("exclamationmark.triangle.fill", ORIX.Palette.record)43 case .notice: ("exclamationmark.circle.fill", ORIX.Palette.warning)44 case .info: (f.kind == .healthy ? "checkmark.seal.fill" : "info.circle.fill", f.kind == .healthy ? ORIX.Palette.good : ORIX.Palette.cyan)45 }46 }47}4849struct AnalysisPanel: View {50 @Environment(AppModel.self) private var model51 let store: DetailStore52 let onSeek: (Double) -> Void53 private let grid = [GridItem(.adaptive(minimum: 140), spacing: 8)]5455 var body: some View {56 let id = store.recording.id57 if let job = model.processing.job(id, .analysis) {58 ORIXCard { ProgressRow(title: "Analyzing…", progress: job.progress) { model.processing.cancel(id, .analysis) } }59 } else if let r = store.report {60 VStack(spacing: ORIX.Space.m) {61 findings(r)62 ORIXCard {63 VStack(alignment: .leading, spacing: 10) {64 SectionTitle("Levels", symbol: "gauge.with.dots.needle.50percent")65 LazyVGrid(columns: grid, spacing: 8) {66 MetricTile(label: "Sample peak", value: fmt(r.time.peakDBFS), unit: "dBFS", tint: r.time.clippingEvents > 0 ? ORIX.Palette.record : ORIX.Palette.text)67 MetricTile(label: "True peak", value: r.loudness.truePeakDBTP.map { fmt(Float($0)) } ?? "—", unit: "dBTP")68 MetricTile(label: "RMS level", value: fmt(r.time.rmsDBFS), unit: "dBFS")69 MetricTile(label: "Crest factor", value: fmt(r.time.crestFactorDB), unit: "dB")70 MetricTile(label: "Background level", value: fmt(r.time.noiseFloorDBFS), unit: "dBFS")71 MetricTile(label: "Dynamic spread", value: fmt(r.time.dynamicSpreadDB), unit: "dB")72 MetricTile(label: "Clipped samples", value: "\(r.time.clippedSamples)", tint: r.time.clippedSamples > 0 ? ORIX.Palette.record : ORIX.Palette.text)73 MetricTile(label: "Zero crossings", value: String(format: "%.0f", r.time.zeroCrossingRate), unit: "/s")74 MetricTile(label: "DC offset", value: String(format: "%.4f", r.time.dcOffset), unit: "FS")75 MetricTile(label: "Silence", value: Timecode.clock(r.time.silentDuration))76 }77 }78 }79 ORIXCard {80 VStack(alignment: .leading, spacing: 10) {81 SectionTitle("Loudness · ITU-R BS.1770-4", symbol: "speaker.wave.3.fill")82 LazyVGrid(columns: grid, spacing: 8) {83 MetricTile(label: "Integrated", value: r.loudness.integratedLUFS.map { fmt(Float($0)) } ?? "—", unit: "LUFS")84 MetricTile(label: "Loudness range", value: r.loudness.loudnessRangeLU.map { fmt(Float($0)) } ?? "—", unit: "LU")85 MetricTile(label: "Max short-term", value: r.loudness.maxShortTermLUFS.map { fmt(Float($0)) } ?? "—", unit: "LUFS")86 MetricTile(label: "Max momentary", value: r.loudness.maxMomentaryLUFS.map { fmt(Float($0)) } ?? "—", unit: "LUFS")87 }88 if r.loudness.shortTermSeries.count > 2 {89 PlotFrame { LoudnessChart(series: r.loudness.shortTermSeries, duration: r.time.duration, onSeek: onSeek) }.frame(height: 110)90 Text("Short-term loudness (3 s window), one point per second. Tap to jump there.").font(.caption).foregroundStyle(ORIX.Palette.textSecondary)91 }92 Text("Loudness and levels describe the digital file relative to full scale. They are not sound pressure levels.").font(.caption).foregroundStyle(ORIX.Palette.textSecondary)93 }94 }95 ORIXCard {96 VStack(alignment: .leading, spacing: 10) {97 SectionTitle("Spectrum", symbol: "chart.bar.xaxis")98 LazyVGrid(columns: grid, spacing: 8) {99 MetricTile(label: "Dominant frequency", value: r.spectral.dominantFrequencyHz.map { Formatters.frequency($0) } ?? "—")100 MetricTile(label: "Centroid", value: Formatters.frequency(r.spectral.centroidHz))101 MetricTile(label: "Bandwidth", value: Formatters.frequency(r.spectral.bandwidthHz))102 MetricTile(label: "Rolloff (85 %)", value: Formatters.frequency(r.spectral.rolloffHz))103 MetricTile(label: "Flatness", value: String(format: "%.3f", r.spectral.flatness))104 MetricTile(label: "Flux", value: String(format: "%.3f", r.spectral.flux))105 }106 if !r.spectral.averageSpectrum.isEmpty {107 PlotFrame { AverageSpectrumChart(values: r.spectral.averageSpectrum, sampleRate: r.sampleRate) }.frame(height: 130)108 Text("Long-term average spectrum, amplitude in dBFS, 20 Hz to \(Formatters.frequency(min(20_000, r.sampleRate / 2))) on a logarithmic axis.").font(.caption).foregroundStyle(ORIX.Palette.textSecondary)109 }110 ForEach(Array(r.spectral.bands.enumerated()), id: \.offset) { i, band in111 HStack(spacing: 8) {112 RoundedRectangle(cornerRadius: 2).fill(ORIX.bandColors[min(i, 6)]).frame(width: 10, height: 10)113 Text(CoreText.bandName(i)).font(.caption).frame(width: 74, alignment: .leading)114 GeometryReader { geo in115 ZStack(alignment: .leading) {116 Capsule().fill(ORIX.Palette.raised)117 Capsule().fill(ORIX.bandColors[min(i, 6)]).frame(width: max(2, geo.size.width * CGFloat(band.fraction)))118 }119 }.frame(height: 8)120 Text("\(Int((band.fraction * 100).rounded())) %").font(.caption.monospacedDigit()).frame(width: 40, alignment: .trailing)121 Text(fmt(band.decibels)).font(.caption.monospacedDigit()).foregroundStyle(ORIX.Palette.textSecondary).frame(width: 52, alignment: .trailing)122 }123 .accessibilityElement(children: .ignore)124 .accessibilityLabel(Text("\(CoreText.bandName(i)), \(Int(band.lowerHz)) to \(Int(band.upperHz)) hertz"))125 .accessibilityValue(Text("\(Int((band.fraction * 100).rounded())) percent of the energy"))126 }127 }128 }129 ORIXCard {130 VStack(alignment: .leading, spacing: 10) {131 HStack { SectionTitle("Speech activity", symbol: "person.wave.2.fill"); Chip(text: String(localized: "Estimate"), tint: ORIX.Palette.warning) }132 LazyVGrid(columns: grid, spacing: 8) {133 MetricTile(label: "Active time", value: Timecode.clock(r.speech.speakingTime))134 MetricTile(label: "Share of recording", value: String(format: "%.0f", r.speech.speechRatio * 100), unit: "%")135 MetricTile(label: "Pauses", value: "\(r.speech.pauses.count)")136 MetricTile(label: "Mean pause", value: String(format: "%.1f", r.speech.meanPause), unit: "s")137 MetricTile(label: "Longest pause", value: String(format: "%.1f", r.speech.longestPause), unit: "s")138 if let transcript = store.transcript, let wpm = r.speech.wordsPerMinute(wordCount: transcript.wordCount) {139 MetricTile(label: "Speaking rate", value: String(format: "%.0f", wpm), unit: String(localized: "words/min"))140 }141 }142 ActivityTimeline(segments: r.speech.segments, duration: r.time.duration, onSeek: onSeek).frame(height: 22)143 Text("Detected from energy in the 300–3400 Hz voice band above the background level. Loud non-speech sounds in that band count as activity. Speaking rate needs a transcript and at least 5 s of activity.")144 .font(.caption).foregroundStyle(ORIX.Palette.textSecondary)145 }146 }147 Button("Analyze again", systemImage: "arrow.clockwise") { model.processing.analyzeInBackground(store.recording) }.buttonStyle(.bordered)148 }149 } else {150 ORIXCard {151 VStack(spacing: 10) {152 EmptyStateView(symbol: "chart.xyaxis.line", title: "Not analyzed yet", message: "Analysis measures levels, loudness, spectrum and speech activity from the file.")153 if let error = model.processing.errors[id] { Text(error).font(.footnote).foregroundStyle(ORIX.Palette.record) }154 Button("Analyze", systemImage: "play.fill") { model.processing.analyzeInBackground(store.recording) }.buttonStyle(.borderedProminent)155 }156 }157 }158 }159160 private func fmt(_ v: Float) -> String { v <= -150 ? "−∞" : String(format: "%.1f", v).replacingOccurrences(of: "-", with: "−") }161162 private func findings(_ r: AnalysisReport) -> some View {163 ORIXCard {164 VStack(alignment: .leading, spacing: 10) {165 SectionTitle("Findings", symbol: "stethoscope")166 ForEach(r.findings) { f in167 let (symbol, tint) = FindingText.symbol(f)168 HStack(alignment: .top, spacing: 10) {169 Image(systemName: symbol).foregroundStyle(tint).frame(width: 22)170 VStack(alignment: .leading, spacing: 2) {171 Text(FindingText.title(f)).font(.subheadline.weight(.semibold))172 Text(FindingText.detail(f)).font(.footnote).foregroundStyle(ORIX.Palette.textSecondary)173 }174 }175 .accessibilityElement(children: .combine)176 }177 Text("Indications derived from the measurements below — not a forensic or medical assessment.").font(.caption2).foregroundStyle(ORIX.Palette.textSecondary)178 }179 }180 }181}182183struct LoudnessChart: View {184 let series: [Float]185 let duration: Double186 let onSeek: (Double) -> Void187 var body: some View {188 GeometryReader { geo in189 Canvas { context, size in190 let lo: Float = -60, hi: Float = 0191 func y(_ v: Float) -> CGFloat { size.height * (1 - CGFloat(max(0, min(1, (v - lo) / (hi - lo))))) }192 for level in [Float(-48), -36, -24, -12] {193 context.stroke(Path { $0.move(to: CGPoint(x: 0, y: y(level))); $0.addLine(to: CGPoint(x: size.width, y: y(level))) }, with: .color(ORIX.Palette.plotGrid), lineWidth: 0.5)194 context.draw(Text("\(Int(level))").font(.system(size: 8, design: .monospaced)).foregroundStyle(ORIX.Palette.plotText), at: CGPoint(x: 3, y: y(level) - 5), anchor: .leading)195 }196 var path = Path()197 for (i, v) in series.enumerated() {198 let p = CGPoint(x: size.width * CGFloat(i) / CGFloat(max(1, series.count - 1)), y: y(v))199 if i == 0 { path.move(to: p) } else { path.addLine(to: p) }200 }201 context.stroke(path, with: .linearGradient(Gradient(colors: [Color(uiColor: UIColor(hex: 0x22D3EE)), Color(uiColor: UIColor(hex: 0x8B5CF6))]), startPoint: .zero, endPoint: CGPoint(x: size.width, y: 0)), lineWidth: 1.5)202 }203 .contentShape(Rectangle())204 .onTapGesture { location in onSeek(duration * Double(location.x / max(1, geo.size.width))) }205 }206 .accessibilityLabel(Text("Short-term loudness over time"))207 }208}209210struct AverageSpectrumChart: View {211 let values: [Float]212 let sampleRate: Double213 var body: some View {214 Canvas { context, size in215 let lo: Float = -120, hi: Float = 0216 var path = Path()217 for (i, v) in values.enumerated() {218 let p = CGPoint(x: size.width * CGFloat(i) / CGFloat(max(1, values.count - 1)), y: size.height * (1 - CGFloat(max(0, min(1, (v - lo) / (hi - lo))))))219 if i == 0 { path.move(to: p) } else { path.addLine(to: p) }220 }221 var fill = path222 fill.addLine(to: CGPoint(x: size.width, y: size.height)); fill.addLine(to: CGPoint(x: 0, y: size.height)); fill.closeSubpath()223 context.fill(fill, with: .linearGradient(Gradient(colors: ORIX.bandColors.map { $0.opacity(0.45) }), startPoint: .zero, endPoint: CGPoint(x: size.width, y: 0)))224 context.stroke(path, with: .linearGradient(Gradient(colors: ORIX.bandColors), startPoint: .zero, endPoint: CGPoint(x: size.width, y: 0)), lineWidth: 1.5)225 let top = min(20_000, sampleRate / 2)226 for f in [100.0, 1000, 10_000] where f < top {227 let x = size.width * CGFloat(log(f / 20) / log(top / 20))228 context.stroke(Path { $0.move(to: CGPoint(x: x, y: 0)); $0.addLine(to: CGPoint(x: x, y: size.height)) }, with: .color(ORIX.Palette.plotGrid), lineWidth: 0.5)229 context.draw(Text(f >= 1000 ? "\(Int(f / 1000))k" : "\(Int(f))").font(.system(size: 8, design: .monospaced)).foregroundStyle(ORIX.Palette.plotText), at: CGPoint(x: x + 3, y: size.height - 7), anchor: .leading)230 }231 }232 .accessibilityLabel(Text("Long-term average spectrum"))233 }234}235236struct ActivityTimeline: View {237 let segments: [TimeInterval2]238 let duration: Double239 let onSeek: (Double) -> Void240 var body: some View {241 GeometryReader { geo in242 Canvas { context, size in243 context.fill(Path(roundedRect: CGRect(origin: .zero, size: size), cornerRadius: 5), with: .color(ORIX.Palette.raised))244 guard duration > 0 else { return }245 for s in segments {246 let x = size.width * CGFloat(s.start / duration), w = max(1, size.width * CGFloat(s.duration / duration))247 context.fill(Path(roundedRect: CGRect(x: x, y: 3, width: w, height: size.height - 6), cornerRadius: 2), with: .color(ORIX.Palette.cyan))248 }249 }250 .contentShape(Rectangle())251 .onTapGesture { location in onSeek(duration * Double(location.x / max(1, geo.size.width))) }252 }253 .accessibilityLabel(Text("Speech activity timeline"))254 .accessibilityValue(Text("\(segments.count) active segments"))255 }256}257