SPB Git

Repository Public License

RecorderView.swift 20.8 KB 393 lines swift

1//2//  ORIX Audio3//  File: ORIXAudio/Features/Recorder/RecorderView.swift4//  Description: Recording screen: timer, status, live frequency-coloured waveform, spectrum / spectrogram, meters, markers and transport.5//6//  Author: Simon-Pierre Boucher7//  Contact: contact@spboucher.ai8//9import ORIXAudioCore10import SwiftUI1112enum LivePanel: String, CaseIterable, Identifiable {13    case spectrum, spectrogram, transcript, none14    var id: String { rawValue }15    var symbol: String {16        switch self { case .spectrum: "chart.bar.xaxis"; case .spectrogram: "square.grid.3x3.fill"; case .transcript: "text.quote"; case .none: "rectangle.slash" }17    }18    var title: LocalizedStringKey {19        switch self { case .spectrum: "Spectrum"; case .spectrogram: "Spectrogram"; case .transcript: "Live text"; case .none: "Waveform only" }20    }21}2223struct RecorderView: View {24    @Environment(AppModel.self) private var model25    @Environment(AppSettings.self) private var settings26    @Environment(\.horizontalSizeClass) private var sizeClass27    @AppStorage("livePanel") private var panelRaw = LivePanel.spectrum.rawValue28    @State private var showConsent = false29    @State private var showMarkers = false30    @State private var showSetup = false3132    private var recorder: RecorderController { model.recorder }33    private var panel: LivePanel { LivePanel(rawValue: panelRaw) ?? .spectrum }3435    var body: some View {36        @Bindable var settings = settings37        GeometryReader { geo in38            let wide = geo.size.width > 76039            VStack(spacing: ORIX.Space.m) {40                if !model.recoverable.isEmpty && !recorder.isActive { RecoveryBanner() }41                header42                if wide {43                    HStack(spacing: ORIX.Space.m) { waveformPanel; secondaryPanel.frame(width: geo.size.width * 0.42) }44                } else {45                    waveformPanel46                    if panel != .none { secondaryPanel.frame(height: max(120, geo.size.height * 0.24)) }47                }48                meters49                transport50            }51            .padding(.horizontal, ORIX.Space.l).padding(.bottom, ORIX.Space.m)52        }53        .orixScreenBackground()54        .navigationTitle("ORIX Audio")55        .navigationBarTitleDisplayMode(.inline)56        .toolbar {57            ToolbarItem(placement: .topBarLeading) {58                Menu {59                    Picker("Waveform", selection: $settings.waveformStyle) {60                        Label("Frequency colours", systemImage: "paintpalette").tag(WaveformStyle.spectral)61                        Label("Band shares", systemImage: "chart.bar.fill").tag(WaveformStyle.bands)62                        Label("Amplitude", systemImage: "waveform").tag(WaveformStyle.amplitude)63                        Label("RMS and peak envelope", systemImage: "waveform.path").tag(WaveformStyle.envelope)64                    }65                    Picker("Second panel", selection: $panelRaw) { ForEach(LivePanel.allCases) { Label($0.title, systemImage: $0.symbol).tag($0.rawValue) } }66                } label: { Label("Display", systemImage: "square.stack.3d.up") }67            }68            ToolbarItem(placement: .topBarTrailing) {69                if panel == .spectrum {70                    SpectrumSettingsMenu(configuration: $settings.spectrumConfiguration, axis: $settings.spectrumAxis)71                }72            }73        }74        .onChange(of: settings.spectrumConfiguration) { _, new in recorder.engine?.spectrumConfiguration.withLock { $0 = new } }75        .sheet(isPresented: $showMarkers) { MarkersSheet() }76        .sheet(isPresented: $showSetup) { RecordingSetupSheet().presentationDetents([.medium, .large]) }77        .alert("Before you record", isPresented: $showConsent) {78            Button("I understand") { settings.hasAcknowledgedConsent = true; Task { await recorder.start() } }79            Button("Cancel", role: .cancel) {}80        } message: {81            Text("Recording people without their knowledge can be illegal. Tell everyone present that you are recording, and get their consent where the law requires it.")82        }83        .alert("Recording", isPresented: Binding(get: { recorder.lastError != nil }, set: { if !$0 { recorder.lastError = nil } })) {84            Button("OK", role: .cancel) {}85        } message: { Text(recorder.lastError ?? "") }86    }8788    // MARK: Header8990    private var header: some View {91        VStack(spacing: 6) {92            HStack(spacing: 8) {93                statusChip94                if let format = recorder.captureFormat, recorder.isActive {95                    Chip(text: "\(Formatters.sampleRate(format.sampleRate)) · \(format.channels == 2 ? String(localized: "Stereo") : String(localized: "Mono")) · \(recorder.preset.format.codecName)", symbol: "waveform")96                }97                Spacer(minLength: 0)98                if recorder.isActive { Chip(text: Formatters.bytes(recorder.capturedBytes), symbol: "internaldrive") }99            }100            Text(Timecode.precise(recorder.elapsed))101                .font(.system(size: sizeClass == .regular ? 76 : 60, weight: .ultraLight, design: .rounded)).monospacedDigit()102                .foregroundStyle(recorder.state == .recording ? ORIX.Palette.text : ORIX.Palette.textSecondary)103                .contentTransition(.numericText()).minimumScaleFactor(0.5).lineLimit(1)104                .accessibilityLabel(Text("Recording duration")).accessibilityValue(Text(Timecode.clock(recorder.elapsed)))105                .accessibilityIdentifier("recordingTimer")106            if recorder.isActive {107                HStack(spacing: 6) {108                    Image(systemName: recorder.route?.isBluetoothInput == true ? "headphones" : "mic.fill").imageScale(.small)109                    Text(recorder.route?.inputName ?? "—").lineLimit(1)110                    Image(systemName: "lock.fill").imageScale(.small).padding(.leading, 6)111                    Text("Continues when the screen is locked").lineLimit(2).minimumScaleFactor(0.7)112                }113                .font(.caption).foregroundStyle(ORIX.Palette.textSecondary)114            } else {115                Button { showSetup = true } label: {116                    HStack(spacing: 6) {117                        Image(systemName: recorder.preset.symbol)118                        Text(PresetText.name(recorder.preset)).fontWeight(.semibold)119                        Text(PresetText.summary(recorder.preset)).lineLimit(2).minimumScaleFactor(0.7).multilineTextAlignment(.leading)120                        Image(systemName: "chevron.down").imageScale(.small)121                    }122                    .font(.caption).foregroundStyle(ORIX.Palette.textSecondary)123                    .padding(.horizontal, 12).padding(.vertical, 7).background(ORIX.Palette.raised, in: Capsule())124                }125                .buttonStyle(.plain).accessibilityIdentifier("presetButton")126                .accessibilityLabel(Text("Recording setup")).accessibilityValue(Text(PresetText.name(recorder.preset)))127            }128            if let message = recorder.statusMessage {129                Label(message, systemImage: "exclamationmark.triangle.fill").font(.caption).foregroundStyle(ORIX.Palette.warning).multilineTextAlignment(.center)130            }131            if recorder.droppedSamples > 0 {132                Label("Audio was dropped (\(recorder.droppedSamples) samples): storage could not keep up.", systemImage: "exclamationmark.octagon.fill")133                    .font(.caption).foregroundStyle(ORIX.Palette.record)134            }135        }136    }137138    private var statusChip: some View {139        Group {140            switch recorder.state {141            case .idle: Chip(text: String(localized: "Ready"), symbol: "circle", tint: ORIX.Palette.textSecondary)142            case .recording: Chip(text: String(localized: "Recording"), symbol: "record.circle.fill", tint: ORIX.Palette.record)143            case .paused: Chip(text: String(localized: "Paused"), symbol: "pause.fill", tint: ORIX.Palette.warning)144            case .interrupted: Chip(text: String(localized: "Interrupted"), symbol: "exclamationmark.triangle.fill", tint: ORIX.Palette.warning)145            case .finishing: Chip(text: String(localized: "Saving…"), symbol: "arrow.down.circle.fill", tint: ORIX.Palette.cyan)146            }147        }148        .accessibilityIdentifier("recordingStatus")149    }150151    // MARK: Panels152153    private var waveformPanel: some View {154        PlotFrame {155            ZStack(alignment: .bottomLeading) {156                if let engine = recorder.engine {157                    LiveWaveformView(visuals: engine.visuals, style: settings.waveformStyle, isActive: recorder.state == .recording)158                } else {159                    IdleWaveformPlaceholder()160                }161                if settings.waveformStyle == .spectral || settings.waveformStyle == .bands { BandLegend(compact: true).padding(8) }162            }163        }164        .frame(maxHeight: .infinity)165    }166167    @ViewBuilder private var secondaryPanel: some View {168        switch panel {169        case .none: EmptyView()170        case .spectrum:171            PlotFrame {172                if let engine = recorder.engine {173                    TimelineView(.animation(minimumInterval: 1.0 / 30, paused: recorder.state != .recording)) { _ in174                        SpectrumPlot(frame: engine.visuals.read { $0.spectrum }, axis: settings.spectrumAxis)175                    }176                } else { SpectrumPlot(frame: nil, axis: settings.spectrumAxis) }177            }178        case .spectrogram:179            PlotFrame {180                if let engine = recorder.engine {181                    LiveSpectrogramView(visuals: engine.visuals, display: SpectrogramDisplay(palette: settings.palette, fftSize: 1024), isActive: recorder.state == .recording)182                } else { ORIX.Palette.plot }183            }184        case .transcript:185            ORIXCard(padding: ORIX.Space.m) {186                ScrollView {187                    if !settings.liveTranscription {188                        Text("Live text is off. Turn it on in Settings. The full transcript is always produced after recording, from the saved file.")189                            .font(.footnote).foregroundStyle(ORIX.Palette.textSecondary)190                    } else if recorder.isActive && !recorder.liveTranscriptionActive {191                        Text("Live text isn't available for this language on this device right now. Recording is unaffected.")192                            .font(.footnote).foregroundStyle(ORIX.Palette.textSecondary)193                    } else {194                        (Text(recorder.liveTranscript) + Text(recorder.liveTranscriptVolatile).foregroundStyle(ORIX.Palette.textSecondary))195                            .font(.callout).frame(maxWidth: .infinity, alignment: .leading)196                    }197                }198            }199        }200    }201202    private var meters: some View {203        Group {204            if let engine = recorder.engine {205                TimelineView(.animation(minimumInterval: 1.0 / 30, paused: !recorder.isActive)) { _ in206                    let levels = engine.visuals.read { $0.levels }207                    VStack(spacing: 4) {208                        LevelMeter(levels: levels)209                        HStack {210                            Text("RMS \(Formatters.dB(Double(levels.rmsDB), unit: "dBFS"))")211                            Spacer()212                            if let lufs = levels.momentaryLUFS, lufs > -70 { Text("Momentary \(Formatters.dB(lufs, unit: "LUFS"))") }213                        }214                        .font(.system(.caption2, design: .monospaced)).foregroundStyle(Color.white.opacity(0.75)).lineLimit(1).minimumScaleFactor(0.6)215                    }216                }217            } else {218                LevelMeter(levels: LiveLevels())219            }220        }221        .padding(ORIX.Space.m)222        .background(ORIX.Palette.plot, in: RoundedRectangle(cornerRadius: ORIX.Radius.control, style: .continuous))223    }224225    // MARK: Transport226227    private var transport: some View {228        HStack(spacing: 28) {229            CircleIconButton(symbol: "flag.fill", label: "Add marker", tint: ORIX.Palette.cyan) { recorder.addMarker() }230                .disabled(!recorder.isActive || recorder.state == .finishing).opacity(recorder.isActive ? 1 : 0.35)231                .overlay(alignment: .topTrailing) {232                    let count = recorder.markers.count233                    if count > 0 { Text("\(count)").font(.caption2.weight(.bold)).padding(5).background(ORIX.Palette.cyan, in: Circle()).foregroundStyle(.black).offset(x: 6, y: -6) }234                }235                .accessibilityIdentifier("markerButton")236                .simultaneousGesture(LongPressGesture().onEnded { _ in if recorder.isActive { showMarkers = true } })237238            if recorder.state == .finishing {239                ProgressView(value: recorder.finishingProgress).progressViewStyle(.circular).controlSize(.large).frame(width: 84, height: 84)240                    .accessibilityLabel(Text("Saving recording"))241            } else {242                RecordButton(isRecording: recorder.isActive) {243                    if recorder.isActive { Task { await recorder.stop() } }244                    else if !settings.hasAcknowledgedConsent { showConsent = true }245                    else { Task { await recorder.start() } }246                }247            }248249            CircleIconButton(symbol: recorder.state == .recording ? "pause.fill" : "play.fill",250                             label: recorder.state == .recording ? "Pause recording" : "Resume recording") { recorder.togglePause() }251                .disabled(!(recorder.state == .recording || recorder.state == .paused || recorder.state == .interrupted))252                .opacity(recorder.state == .recording || recorder.state == .paused || recorder.state == .interrupted ? 1 : 0.35)253                .accessibilityIdentifier("pauseButton")254        }255        .padding(.top, 4)256    }257}258259/// Idle state of the waveform panel: a flat centre line. No simulated signal is ever drawn.260struct IdleWaveformPlaceholder: View {261    var body: some View {262        ZStack {263            Canvas { context, size in264                context.stroke(Path { $0.move(to: CGPoint(x: 0, y: size.height / 2)); $0.addLine(to: CGPoint(x: size.width, y: size.height / 2)) }, with: .color(ORIX.Palette.plotGrid), lineWidth: 1)265            }266            VStack(spacing: 6) {267                Image(systemName: "waveform").font(.title).foregroundStyle(ORIX.Palette.plotText)268                Text("The waveform appears when you start recording").font(.footnote).foregroundStyle(Color.white.opacity(0.8)).multilineTextAlignment(.center).fixedSize(horizontal: false, vertical: true)269            }.padding()270        }271    }272}273274enum PresetText {275    static func name(_ p: RecordingPreset) -> String {276        switch p {277        case .voice: String(localized: "Voice")278        case .meeting: String(localized: "Meeting")279        case .lecture: String(localized: "Lecture")280        case .interview: String(localized: "Interview")281        case .highQuality: String(localized: "High Quality")282        case .lossless: String(localized: "Lossless")283        }284    }285    /// What the saved file will be. Sample rate and channel count follow the hardware and are shown once recording starts.286    static func summary(_ p: RecordingPreset) -> String {287        switch p {288        case .voice: String(localized: "AAC 64 kbps · 24 kHz · mono")289        case .meeting: String(localized: "AAC 96 kbps · mono")290        case .lecture: String(localized: "AAC 80 kbps · mono")291        case .interview: String(localized: "AAC 96 kbps per channel · stereo if available")292        case .highQuality: String(localized: "WAV · PCM 24-bit · uncompressed")293        case .lossless: String(localized: "Apple Lossless · 24-bit")294        }295    }296    static func detail(_ p: RecordingPreset) -> String {297        switch p {298        case .voice: String(localized: "Smallest files. Lossy. Good for notes and reminders.")299        case .meeting: String(localized: "Lossy, tuned for long sessions with several voices.")300        case .lecture: String(localized: "Lossy, for one main speaker at a distance.")301        case .interview: String(localized: "Lossy. Uses two channels when the input provides them.")302        case .highQuality: String(localized: "Uncompressed. About 17 MB per minute in stereo at 48 kHz.")303        case .lossless: String(localized: "Bit-exact and roughly half the size of WAV.")304        }305    }306}307308struct RecordingSetupSheet: View {309    @Environment(AppModel.self) private var model310    @Environment(\.dismiss) private var dismiss311    var body: some View {312        @Bindable var recorder = model.recorder313        NavigationStack {314            Form {315                Section("Title") {316                    TextField("Optional title", text: $recorder.title)317                    if recorder.preset.kind == .meeting || recorder.preset.kind == .interview {318                        TextField("Participants (optional, entered by you)", text: $recorder.participants, axis: .vertical)319                    }320                }321                Section {322                    ForEach(RecordingPreset.allCases) { preset in323                        Button { recorder.preset = preset } label: {324                            HStack(spacing: 12) {325                                Image(systemName: preset.symbol).frame(width: 28).foregroundStyle(ORIX.Palette.cyan)326                                VStack(alignment: .leading, spacing: 2) {327                                    Text(PresetText.name(preset)).font(.body.weight(.medium)).foregroundStyle(ORIX.Palette.text)328                                    Text(PresetText.summary(preset)).font(.caption).foregroundStyle(ORIX.Palette.textSecondary)329                                    Text(PresetText.detail(preset)).font(.caption2).foregroundStyle(ORIX.Palette.textSecondary)330                                }331                                Spacer()332                                if recorder.preset == preset { Image(systemName: "checkmark").foregroundStyle(ORIX.Palette.cyan) }333                            }334                        }335                        .accessibilityAddTraits(recorder.preset == preset ? .isSelected : [])336                    }337                } header: { Text("Quality") } footer: {338                    Text("The sample rate and the number of channels depend on the microphone in use. ORIX Audio shows the real values while recording and never labels lossy audio as lossless.")339                }340            }341            .navigationTitle("Recording setup").navigationBarTitleDisplayMode(.inline)342            .toolbar { ToolbarItem(placement: .confirmationAction) { Button("Done") { dismiss() } } }343        }344    }345}346347struct MarkersSheet: View {348    @Environment(AppModel.self) private var model349    @Environment(\.dismiss) private var dismiss350    var body: some View {351        NavigationStack {352            List {353                ForEach(model.recorder.markers) { marker in354                    HStack {355                        Text(Timecode.precise(marker.time)).font(.orixReadout).foregroundStyle(ORIX.Palette.cyan)356                        TextField("Label", text: Binding(get: { marker.label }, set: { model.recorder.renameMarker(marker.id, to: $0) }))357                    }358                }359                if model.recorder.markers.isEmpty { Text("No markers yet").foregroundStyle(ORIX.Palette.textSecondary) }360            }361            .navigationTitle("Markers").navigationBarTitleDisplayMode(.inline)362            .toolbar { ToolbarItem(placement: .confirmationAction) { Button("Done") { dismiss() } } }363        }364        .presentationDetents([.medium])365    }366}367368struct RecoveryBanner: View {369    @Environment(AppModel.self) private var model370    @State private var working: UUID?371    var body: some View {372        ORIXCard(padding: ORIX.Space.m) {373            VStack(alignment: .leading, spacing: 8) {374                Label("Interrupted recording found", systemImage: "arrow.counterclockwise.circle.fill").font(.subheadline.weight(.semibold)).foregroundStyle(ORIX.Palette.warning)375                ForEach(model.recoverable) { capture in376                    HStack {377                        VStack(alignment: .leading, spacing: 2) {378                            Text(capture.sidecar.title).font(.footnote.weight(.medium)).lineLimit(1)379                            Text("\(Timecode.clock(capture.duration)) · \(Formatters.bytes(capture.bytes)) · \(Formatters.date(capture.sidecar.startedAt))").font(.caption2).foregroundStyle(ORIX.Palette.textSecondary)380                        }381                        Spacer()382                        if working == capture.id { ProgressView() } else {383                            Button("Recover") { working = capture.id; Task { await model.recover(capture); working = nil } }.buttonStyle(.borderedProminent).controlSize(.small)384                            Button("Discard", role: .destructive) { model.discard(capture) }.buttonStyle(.bordered).controlSize(.small)385                        }386                    }387                }388            }389        }390        .accessibilityIdentifier("recoveryBanner")391    }392}393
Files main
Menu

Theme