Repository Public
1// ORIX DJ2// File: App/Sources/Features/Settings/AudioSettingsTab.swift3// Description: Settings → Audio: output device, sample rate, buffer size and the latency they give, master and cue4// output pairs, split cue, and the engine's own render measurements.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import ORIXDJCore9import SwiftUI1011struct AudioSettingsTab: View {12 @Environment(AppModel.self) private var model13 @Environment(AppSettings.self) private var settings14 @State private var devices: [AudioDeviceInfo] = []1516 private var device: AudioDeviceInfo? {17 devices.first { $0.uid == settings.deviceUID } ?? devices.first { $0.isDefault } ?? devices.first18 }1920 private static let bufferSizes = [64, 128, 256, 512, 1024, 2048]2122 private func rateLabel(_ rate: Double) -> String {23 let k = rate / 100024 return (k == k.rounded() ? String(format: "%.0f", k) : String(format: "%.1f", k)) + " kHz"25 }2627 private func milliseconds(_ x: Double) -> String { String(format: "%.1f ms", x) }2829 var body: some View {30 @Bindable var settings = settings31 SettingsPage {32 SettingsCard(title: "Output device") {33 SettingsRow(title: "Device", detail: "The system default follows the output chosen in macOS.") {34 Picker("Device", selection: Binding(get: { settings.deviceUID ?? "" }, set: { settings.deviceUID = $0.isEmpty ? nil : $0; fit() })) {35 Text("System default").tag("")36 ForEach(devices) { d in37 Text(verbatim: "\(d.name) — \(d.transport), \(d.outputChannels) ch").tag(d.uid)38 }39 if let uid = settings.deviceUID, !devices.contains(where: { $0.uid == uid }) {40 Text("Stored device (not connected)").tag(uid)41 }42 }43 .labelsHidden().frame(width: 330, alignment: .trailing)44 .accessibilityLabel("Output device").accessibilityIdentifier("settings-audio-device")45 }46 if let d = device {47 SettingsRow(title: "Sample rate", detail: "Only the rates this device offers are listed.") {48 Picker("Sample rate", selection: $settings.sampleRate) {49 ForEach(d.sampleRates, id: \.self) { Text(verbatim: rateLabel($0)).tag($0) }50 if !d.sampleRates.contains(settings.sampleRate) { Text(verbatim: "\(rateLabel(settings.sampleRate)) (not offered by this device)").tag(settings.sampleRate) }51 }52 .labelsHidden().frame(width: 330, alignment: .trailing)53 .accessibilityLabel("Sample rate").accessibilityIdentifier("settings-audio-rate")54 }55 let sizes = Self.bufferSizes.filter { d.bufferFrameRange.contains($0) }56 SettingsRow(title: "Buffer size", detail: "Smaller buffers respond faster and leave less time to render each block.") {57 Picker("Buffer size", selection: $settings.bufferFrames) {58 ForEach(sizes, id: \.self) { Text(verbatim: "\($0) frames").tag($0) }59 if !sizes.contains(settings.bufferFrames) { Text(verbatim: "\(settings.bufferFrames) frames (outside this device's range)").tag(settings.bufferFrames) }60 }61 .labelsHidden().frame(width: 330, alignment: .trailing)62 .accessibilityLabel("Buffer size").accessibilityIdentifier("settings-audio-buffer")63 }64 let bufferMS = Double(settings.bufferFrames) / settings.sampleRate * 100065 let deviceMS = Double(d.latencyFrames) / (d.currentSampleRate > 0 ? d.currentSampleRate : settings.sampleRate) * 100066 HStack(spacing: ORIX.Space.md) {67 SettingsReadout(label: "Buffer latency", value: milliseconds(bufferMS))68 SettingsReadout(label: "Device latency (reported)", value: milliseconds(deviceMS))69 SettingsReadout(label: "Total output latency", value: milliseconds(bufferMS + deviceMS))70 }71 .padding(.horizontal, 14).padding(.vertical, 10)72 .accessibilityIdentifier("settings-audio-latency")73 Rectangle().fill(ORIX.Palette.hairline).frame(height: 1).padding(.leading, 14)74 SettingsNote("Total latency is the device's reported latency plus one buffer. Bluetooth devices add latency of their own that the system does not report.",75 symbol: d.transport.localizedCaseInsensitiveContains("bluetooth") ? "exclamationmark.triangle" : "info.circle",76 tint: d.transport.localizedCaseInsensitiveContains("bluetooth") ? ORIX.Palette.warning : ORIX.Palette.textSecondary)77 } else {78 SettingsNote("No audio output device was found.", symbol: "exclamationmark.triangle", tint: ORIX.Palette.warning)79 }80 }8182 if let d = device {83 SettingsCard(title: "Routing") {84 let pairs = Array(stride(from: 0, to: max(0, d.outputChannels - 1), by: 2))85 SettingsRow(title: "Master output", detail: "The pair of device channels that carries the mix.") {86 Picker("Master output", selection: $settings.masterLeft) {87 ForEach(pairs, id: \.self) { Text(verbatim: "Channels \($0 + 1)–\($0 + 2)").tag($0) }88 if !pairs.contains(settings.masterLeft) { Text(verbatim: "Channels \(settings.masterLeft + 1)–\(settings.masterLeft + 2) (not on this device)").tag(settings.masterLeft) }89 }90 .labelsHidden().frame(width: 260, alignment: .trailing)91 .accessibilityLabel("Master output pair").accessibilityIdentifier("settings-audio-master")92 }93 SettingsRow(title: "Headphone cue output", detail: "A second pair for pre-listening, on interfaces with four or more channels.", divider: d.outputChannels == 2 || settings.cueLeft == settings.masterLeft) {94 Picker("Headphone cue output", selection: $settings.cueLeft) {95 Text("None").tag(-1)96 ForEach(pairs, id: \.self) { Text(verbatim: "Channels \($0 + 1)–\($0 + 2)").tag($0) }97 if settings.cueLeft >= 0, !pairs.contains(settings.cueLeft) { Text(verbatim: "Channels \(settings.cueLeft + 1)–\(settings.cueLeft + 2) (not on this device)").tag(settings.cueLeft) }98 }99 .labelsHidden().frame(width: 260, alignment: .trailing)100 .accessibilityLabel("Headphone cue output pair").accessibilityIdentifier("settings-audio-cue")101 }102 if settings.cueLeft == settings.masterLeft {103 SettingsNote("The cue output uses the same channels as the master: the cue signal would be heard in the room.", symbol: "exclamationmark.triangle", tint: ORIX.Palette.warning)104 }105 if d.outputChannels == 2 {106 SettingsRow(title: "Split cue", detail: "For stereo devices without a separate cue output: the master is sent in mono to the left channel and the cue in mono to the right, for use with a splitter cable.", divider: false) {107 Toggle("Split cue", isOn: $settings.splitCue).labelsHidden().toggleStyle(.switch)108 .accessibilityLabel("Split cue").accessibilityIdentifier("settings-audio-split")109 }110 }111 }112 }113114 HStack(spacing: ORIX.Space.sm) {115 Button("Apply") { model.applyAudioSettings(); refresh() }116 .keyboardShortcut(.defaultAction)117 .accessibilityIdentifier("settings-audio-apply")118 Button("Refresh Devices") { refresh() }.accessibilityIdentifier("settings-audio-refresh")119 engineState120 Spacer()121 }122 SettingsNote("Changes on this page take effect when you press Apply. The decks pause while the audio engine restarts.")123 .padding(.horizontal, -14).padding(.vertical, -6)124125 RenderReadouts()126 }127 .onAppear { refresh() }128 .accessibilityIdentifier("settings-audio")129 }130131 @ViewBuilder private var engineState: some View {132 if let e = model.audioError {133 Label { Text(verbatim: e) } icon: { Image(systemName: "exclamationmark.triangle.fill") }.foregroundStyle(ORIX.Palette.warning).font(.system(size: 11.5)).lineLimit(2)134 } else if model.audioRunning, let d = model.audioDevice {135 Label { Text(verbatim: "Running on \(d.name) · \(rateLabel(model.engine.core.sampleRate)) · \(d.bufferFrames) frames") } icon: { Image(systemName: "checkmark.circle.fill") }136 .foregroundStyle(ORIX.Palette.success).font(.system(size: 11.5).monospacedDigit()).lineLimit(1)137 } else if model.options.silent {138 Label("Silent mode: no audio device is open", systemImage: "speaker.slash").foregroundStyle(ORIX.Palette.textSecondary).font(.system(size: 11.5))139 } else {140 Label("Audio is stopped", systemImage: "exclamationmark.triangle.fill").foregroundStyle(ORIX.Palette.warning).font(.system(size: 11.5))141 }142 }143144 private func refresh() { devices = AudioDevices.outputs(); model.refreshNow() }145146 /// After the device changed: keep the rate, buffer and channel pairs within what the new device offers.147 private func fit() {148 guard let d = device else { return }149 if !d.sampleRates.contains(settings.sampleRate), let nearest = d.sampleRates.min(by: { abs($0 - settings.sampleRate) < abs($1 - settings.sampleRate) }) { settings.sampleRate = nearest }150 let sizes = Self.bufferSizes.filter { d.bufferFrameRange.contains($0) }151 if !sizes.contains(settings.bufferFrames), let nearest = sizes.min(by: { abs($0 - settings.bufferFrames) < abs($1 - settings.bufferFrames) }) { settings.bufferFrames = nearest }152 if settings.masterLeft + 1 >= d.outputChannels { settings.masterLeft = 0 }153 if settings.cueLeft + 1 >= d.outputChannels { settings.cueLeft = -1 }154 if d.outputChannels != 2 { settings.splitCue = false }155 }156}157158/// The engine's measurements of its own render callback, refreshed with the interface.159private struct RenderReadouts: View {160 @Environment(AppModel.self) private var model161162 var body: some View {163 let r = model.render164 SettingsCard(title: "Engine measurements") {165 HStack(spacing: ORIX.Space.md) {166 SettingsReadout(label: "Render time, last", value: String(format: "%.0f µs", Double(r.lastRenderNanos) / 1000))167 SettingsReadout(label: "Render time, max", value: String(format: "%.0f µs", Double(r.maxRenderNanos) / 1000))168 SettingsReadout(label: "Load", value: String(format: "%.0f %%", model.renderLoad * 100), tint: model.renderLoad > 0.7 ? ORIX.Palette.warning : ORIX.Palette.textPrimary)169 SettingsReadout(label: "Overloads", value: "\(r.overloads)", tint: r.overloads > 0 ? ORIX.Palette.warning : ORIX.Palette.textPrimary)170 SettingsReadout(label: "Clipped blocks", value: "\(r.clippedBlocks)", tint: r.clippedBlocks > 0 ? ORIX.Palette.danger : ORIX.Palette.textPrimary)171 }172 .padding(.horizontal, 14).padding(.vertical, 10)173 Rectangle().fill(ORIX.Palette.hairline).frame(height: 1).padding(.leading, 14)174 SettingsNote("An overload is a render call that took longer than the buffer it produced; raise the buffer size if the count grows. A clipped block is one where the master exceeded full scale. The counters accumulate while ORIX DJ runs; this version has no command to reset them.")175 }176 .accessibilityIdentifier("settings-audio-measurements")177 }178}179