SPB Git

Repository Public

RecordingView.swift 35.8 KB 555 lines swift

1// ORIX DJ2// File: App/Sources/Features/Recording/RecordingView.swift3// Description: Recording & Export Studio: the explicit Record / Stop control with live status, the list of raw takes4//              and exported files, and the export editor (waveform, trim, fades, gain, format) with the real report.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import ORIXDJCore9import SwiftUI1011struct RecordingView: View {12    @Environment(AppModel.self) private var model13    @State private var controller = RecordingController()1415    var body: some View {16        @Bindable var controller = controller17        HStack(alignment: .top, spacing: ORIX.Space.sm) {18            VStack(spacing: ORIX.Space.sm) {19                RecordingTransportPanel(controller: controller)20                RecordingTakesPanel(controller: controller)21            }22            .frame(width: 430)23            RecordingExportPanel(controller: controller)24        }25        .padding(ORIX.Space.sm)26        .background(ORIX.Palette.canvas)27        .task(id: model.recording.isRecording) {28            await controller.refresh(model: model)29            // Free space is re-read while the screen is open.30            while !Task.isCancelled {31                try? await Task.sleep(nanoseconds: 5_000_000_000)32                await controller.refresh(model: model)33            }34        }35        .task(id: controller.selection) { await controller.loadOverview() }36        .onChange(of: model.recording.isRecording) { old, new in37            // A take that just ended (by Stop or by itself) is closed and selected.38            if old, !new {39                if model.recording.stoppedReason != nil { model.stopRecording() }40                controller.selectNewestAfterScan = true41            }42        }43        .onAppear { runDemoIfRequested() }44        .confirmationDialog("Move this take to the Trash?", isPresented: Binding(get: { controller.deleteRequest != nil }, set: { if !$0 { controller.deleteRequest = nil } })) {45            Button("Move to Trash", role: .destructive) { controller.confirmDelete(model: model) }46            Button("Cancel", role: .cancel) { controller.deleteRequest = nil }47        } message: { Text("\"\(controller.deleteRequest?.name ?? "")\" is the raw recording. Files you exported from it are not touched.") }48        .accessibilityElement(children: .contain).accessibilityIdentifier("recording-root")49    }5051    /// DEBUG: `-ORIXRecordDemo <seconds>` records the engine output for that long, then stops (a real take).52    /// `-ORIXRecordExport YES` then exports the take with the default options into the Recordings folder.53    private func runDemoIfRequested() {54        #if DEBUG55        let seconds = UserDefaults.standard.double(forKey: "ORIXRecordDemo")56        guard seconds > 0, !controller.demoStarted else { return }57        controller.demoStarted = true58        Task {59            try? await Task.sleep(nanoseconds: 1_500_000_000)60            model.startRecording()61            try? await Task.sleep(nanoseconds: UInt64(seconds * 1_000_000_000))62            model.stopRecording()63            // The take is selected by the normal "recording ended" path; wait for it.64            for _ in 0 ..< 40 where controller.selectedTake == nil {65                controller.selectNewestAfterScan = true66                await controller.refresh(model: model)67                try? await Task.sleep(nanoseconds: 100_000_000)68            }69            if UserDefaults.standard.bool(forKey: "ORIXRecordExport"), let take = controller.selectedTake {70                controller.normalize = true71                controller.fadeIn = 0.5; controller.fadeOut = 172                let url = model.session.directories.recordings.appendingPathComponent(take.name).appendingPathExtension(controller.format.fileExtension)73                controller.export(to: url, model: model)74            }75        }76        #endif77    }78}7980enum RecordingFormat {81    static func bytes(_ n: Int64) -> String { ByteCountFormatter.string(fromByteCount: n, countStyle: .file) }82    static func seconds(_ s: Double) -> String { String(format: "%.2f s", s) }83    static let date: Date.FormatStyle = .dateTime.year().month(.abbreviated).day().hour().minute()84}8586// MARK: - Record control8788private struct RecordingTransportPanel: View {89    @Environment(AppModel.self) private var model90    var controller: RecordingController9192    var body: some View {93        let rec = model.recording94        let low = !rec.isRecording && controller.freeBytes > 0 && controller.freeBytes < Recorder.minimumFreeBytes95        Panel(padding: ORIX.Space.md) {96            VStack(alignment: .leading, spacing: ORIX.Space.sm) {97                HStack(alignment: .center, spacing: ORIX.Space.md) {98                    Button { if rec.isRecording { model.stopRecording() } else { model.startRecording() } } label: {99                        ZStack {100                            Circle().fill(ORIX.Palette.surfaceRaised)101                            Circle().strokeBorder(rec.isRecording ? ORIX.Palette.danger : ORIX.Palette.hairline, lineWidth: 2)102                            if rec.isRecording {103                                RoundedRectangle(cornerRadius: 5, style: .continuous).fill(ORIX.Palette.danger).frame(width: 28, height: 28)104                            } else {105                                Circle().fill(ORIX.Palette.danger).frame(width: 36, height: 36)106                            }107                        }108                        .frame(width: 84, height: 84).contentShape(Circle())109                    }110                    .buttonStyle(.plain)111                    .keyboardShortcut("r", modifiers: [.command, .shift])112                    .help(rec.isRecording ? "Stop recording (⇧⌘R)" : "Record the master output (⇧⌘R)")113                    .accessibilityLabel(rec.isRecording ? Text("Stop recording") : Text("Record"))114                    .accessibilityValue(rec.isRecording ? Text("recording, \(formatTime(rec.duration, tenths: false))") : Text("not recording"))115                    .accessibilityIdentifier("recording-toggle")116117                    VStack(alignment: .leading, spacing: 4) {118                        HStack(spacing: 6) {119                            Image(systemName: rec.isRecording ? "record.circle.fill" : "record.circle").foregroundStyle(rec.isRecording ? ORIX.Palette.danger : ORIX.Palette.textTertiary)120                            Text(rec.isRecording ? "RECORDING" : "READY").font(.system(size: 11, weight: .heavy)).foregroundStyle(rec.isRecording ? ORIX.Palette.danger : ORIX.Palette.textSecondary)121                        }122                        .accessibilityElement(children: .combine).accessibilityIdentifier("recording-state")123                        Text(verbatim: formatTime(rec.isRecording ? rec.duration : 0)).font(ORIX.Typeface.readout(34)).foregroundStyle(ORIX.Palette.textPrimary)124                            .accessibilityLabel("Elapsed time").accessibilityIdentifier("recording-elapsed")125                        Text("Recording starts only from this button or its shortcut. It captures the master output as 32-bit float audio.")126                            .font(.system(size: 10.5)).foregroundStyle(ORIX.Palette.textTertiary).fixedSize(horizontal: false, vertical: true)127                    }128                }129130                VStack(spacing: 4) {131                    meter("L", model.render.masterPeakL)132                    meter("R", model.render.masterPeakR)133                }134                .accessibilityElement(children: .contain).accessibilityIdentifier("recording-meters")135136                Grid(alignment: .leading, horizontalSpacing: ORIX.Space.md, verticalSpacing: 5) {137                    GridRow {138                        fact("File size", rec.isRecording ? RecordingFormat.bytes(rec.bytesWritten) : "–", id: "recording-size")139                        fact("Free disk space", RecordingFormat.bytes(rec.isRecording && rec.freeDiskBytes > 0 ? rec.freeDiskBytes : controller.freeBytes), id: "recording-free")140                        fact("Gaps", rec.isRecording || rec.overruns > 0 ? "\(rec.overruns)" : "–", id: "recording-overruns")141                            .help("Blocks the audio thread could not hand to the writer. Each one is an audible gap in the take.")142                    }143                }144                if rec.overruns > 0 {145                    Label("\(rec.overruns) gaps in this take: the disk could not keep up.", systemImage: "exclamationmark.triangle.fill")146                        .font(.system(size: 11)).foregroundStyle(ORIX.Palette.warning)147                }148                if let reason = rec.stoppedReason, !rec.isRecording {149                    Label { Text(verbatim: reason) } icon: { Image(systemName: "exclamationmark.octagon.fill") }150                        .font(.system(size: 11, weight: .medium)).foregroundStyle(ORIX.Palette.danger).fixedSize(horizontal: false, vertical: true)151                        .accessibilityIdentifier("recording-stopped-reason")152                }153                if low {154                    Label("Less than \(RecordingFormat.bytes(Recorder.minimumFreeBytes)) is free on the destination disk. ORIX DJ will not start a recording until space is freed.", systemImage: "externaldrive.badge.exclamationmark")155                        .font(.system(size: 11, weight: .medium)).foregroundStyle(ORIX.Palette.warning).fixedSize(horizontal: false, vertical: true)156                        .accessibilityIdentifier("recording-low-space")157                }158                Divider().overlay(ORIX.Palette.hairline)159                HStack(spacing: 6) {160                    VStack(alignment: .leading, spacing: 1) {161                        Text("Destination").font(.system(size: 10.5)).foregroundStyle(ORIX.Palette.textTertiary)162                        Text(verbatim: model.session.directories.recordings.path).font(.system(size: 10.5, design: .monospaced)).foregroundStyle(ORIX.Palette.textSecondary)163                            .lineLimit(2).truncationMode(.middle).textSelection(.enabled)164                    }165                    Spacer()166                    Button { controller.revealFolder(model: model) } label: { Label("Show in Finder", systemImage: "folder") }167                        .controlSize(.small).accessibilityIdentifier("recording-reveal-folder")168                }169            }170        }171        .accessibilityElement(children: .contain).accessibilityIdentifier("recording-transport")172    }173174    private func meter(_ channel: String, _ level: Float) -> some View {175        HStack(spacing: 6) {176            Text(verbatim: channel).font(.system(size: 10, weight: .bold, design: .rounded)).foregroundStyle(ORIX.Palette.textTertiary).frame(width: 10)177            LevelMeter(label: channel == "L" ? "Master left" : "Master right", level: level, clipped: level >= 1, horizontal: true).frame(height: 8)178            Text(verbatim: level > 0.001 ? String(format: "%.1f dB", linearToDB(level)) : "-∞ dB").font(ORIX.Typeface.caption).foregroundStyle(level >= 1 ? ORIX.Palette.danger : ORIX.Palette.textSecondary)179                .frame(width: 58, alignment: .trailing)180        }181    }182183    private func fact(_ label: LocalizedStringKey, _ value: String, id: String) -> some View {184        VStack(alignment: .leading, spacing: 1) {185            Text(label).font(.system(size: 10.5)).foregroundStyle(ORIX.Palette.textTertiary)186            Text(verbatim: value).font(ORIX.Typeface.readout(14)).foregroundStyle(ORIX.Palette.textPrimary)187        }188        .frame(maxWidth: .infinity, alignment: .leading)189        .accessibilityElement(children: .combine).accessibilityIdentifier(id)190    }191}192193// MARK: - Takes194195private struct RecordingTakesPanel: View {196    @Environment(AppModel.self) private var model197    var controller: RecordingController198199    var body: some View {200        Panel(padding: 0) {201            VStack(spacing: 0) {202                HStack {203                    SectionLabel("Takes")204                    Text(verbatim: "\(controller.takes.count)").font(ORIX.Typeface.caption).foregroundStyle(ORIX.Palette.textTertiary)205                    Spacer()206                    Button { Task { await controller.refresh(model: model) } } label: { Image(systemName: "arrow.clockwise") }207                        .controlSize(.small).accessibilityLabel("Refresh the list").accessibilityIdentifier("recording-refresh")208                }209                .padding(.horizontal, ORIX.Space.sm).frame(height: 34)210                Divider().overlay(ORIX.Palette.hairline)211                if controller.takes.isEmpty, controller.exports.isEmpty {212                    EmptyState(symbol: "waveform.circle", title: "No recording yet",213                               message: "Press Record to capture the master output. The raw take appears here, ready to trim and export.")214                } else {215                    ScrollView {216                        LazyVStack(alignment: .leading, spacing: 2) {217                            ForEach(controller.takes) { take in takeRow(take) }218                            if !controller.exports.isEmpty {219                                SectionLabel("Exported files in the folder").padding(.horizontal, 8).padding(.top, 10).padding(.bottom, 2)220                                ForEach(controller.exports) { file in exportRow(file) }221                            }222                        }223                        .padding(6)224                    }225                    .accessibilityIdentifier("recording-takes")226                }227            }228        }229        .frame(maxHeight: .infinity)230    }231232    private func takeRow(_ take: RecordingTake) -> some View {233        let selected = controller.selection == take.url234        return Button { controller.select(take, defaultFormat: model.settings.exportFormat) } label: {235            HStack(spacing: 8) {236                Image(systemName: take.recovered ? "bandage" : "waveform").font(.system(size: 12, weight: .medium))237                    .foregroundStyle(take.recovered ? ORIX.Palette.warning : (selected ? ORIX.Palette.accent : ORIX.Palette.textSecondary)).frame(width: 18)238                VStack(alignment: .leading, spacing: 1) {239                    HStack(spacing: 6) {240                        Text(verbatim: take.name).font(.system(size: 12, weight: selected ? .semibold : .medium)).foregroundStyle(ORIX.Palette.textPrimary).lineLimit(1)241                        if take.recovered {242                            Text("recovered").font(.system(size: 9.5, weight: .bold)).foregroundStyle(ORIX.Palette.warning)243                                .padding(.horizontal, 5).frame(height: 14).overlay(Capsule().strokeBorder(ORIX.Palette.warning))244                                .help("This take was left by a session that ended unexpectedly. It is readable up to its last write.")245                        }246                    }247                    Text(verbatim: "\(take.date.formatted(RecordingFormat.date)) · \(formatTime(take.duration)) · \(RecordingFormat.bytes(take.size))")248                        .font(ORIX.Typeface.caption).foregroundStyle(ORIX.Palette.textTertiary).lineLimit(1)249                }250                Spacer(minLength: 0)251            }252            .padding(.horizontal, 8).frame(height: 40)253            .background(selected ? ORIX.Palette.surfaceRaised : .clear, in: RoundedRectangle(cornerRadius: ORIX.Radius.control, style: .continuous))254            .contentShape(Rectangle())255        }256        .buttonStyle(.plain)257        .accessibilityLabel(Text(verbatim: take.name))258        .accessibilityValue(Text("\(formatTime(take.duration, tenths: false)) long") + (take.recovered ? Text(", recovered take") : Text(verbatim: "")))259        .accessibilityAddTraits(selected ? [.isSelected] : [])260        .accessibilityIdentifier("recording-take-\(take.name)")261        .contextMenu {262            Button("Show in Finder") { controller.reveal(take.url) }263            Button("Move to Trash…", role: .destructive) { controller.deleteRequest = take }264        }265    }266267    private func exportRow(_ file: ExportedFile) -> some View {268        HStack(spacing: 8) {269            Image(systemName: "doc.badge.arrow.up").font(.system(size: 12)).foregroundStyle(ORIX.Palette.textSecondary).frame(width: 18)270            VStack(alignment: .leading, spacing: 1) {271                Text(verbatim: file.url.lastPathComponent).font(.system(size: 12)).foregroundStyle(ORIX.Palette.textPrimary).lineLimit(1)272                Text(verbatim: "\(file.date.formatted(RecordingFormat.date)) · \(formatTime(file.duration)) · \(RecordingFormat.bytes(file.size))")273                    .font(ORIX.Typeface.caption).foregroundStyle(ORIX.Palette.textTertiary).lineLimit(1)274            }275            Spacer(minLength: 0)276            Button { controller.reveal(file.url) } label: { Image(systemName: "magnifyingglass") }.buttonStyle(.plain).foregroundStyle(ORIX.Palette.textSecondary)277                .help("Show in Finder").accessibilityLabel(Text("Show \(file.url.lastPathComponent) in Finder"))278            Button { model.importURLs([file.url]) } label: { Image(systemName: "plus.rectangle.on.folder") }.buttonStyle(.plain).foregroundStyle(ORIX.Palette.textSecondary)279                .help("Add to the library").accessibilityLabel(Text("Add \(file.url.lastPathComponent) to the library"))280        }281        .padding(.horizontal, 8).frame(height: 36)282        .accessibilityElement(children: .contain)283    }284}285286// MARK: - Export editor287288private struct RecordingExportPanel: View {289    @Environment(AppModel.self) private var model290    var controller: RecordingController291292    var body: some View {293        @Bindable var controller = controller294        Panel(padding: ORIX.Space.md) {295            if let take = controller.selectedTake {296                ScrollView {297                    VStack(alignment: .leading, spacing: ORIX.Space.sm) {298                        HStack(alignment: .firstTextBaseline) {299                            Text(verbatim: take.name).font(ORIX.Typeface.title).foregroundStyle(ORIX.Palette.textPrimary).lineLimit(1)300                            Text(verbatim: "\(formatTime(take.duration)) · \(String(format: "%.1f kHz", take.sampleRate / 1000)) · 32-bit float CAF · \(RecordingFormat.bytes(take.size))")301                                .font(ORIX.Typeface.caption).foregroundStyle(ORIX.Palette.textTertiary)302                            Spacer()303                            Button { controller.reveal(take.url) } label: { Label("Show in Finder", systemImage: "folder") }.controlSize(.small)304                                .accessibilityIdentifier("recording-take-reveal")305                            Button(role: .destructive) { controller.deleteRequest = take } label: { Label("Delete Take…", systemImage: "trash") }.controlSize(.small)306                                .accessibilityIdentifier("recording-take-delete")307                        }308                        if take.recovered {309                            Label("Recovered take: the session that recorded it ended unexpectedly. Everything written before that moment is here; export it to keep it.", systemImage: "bandage")310                                .font(.system(size: 11)).foregroundStyle(ORIX.Palette.warning).fixedSize(horizontal: false, vertical: true)311                        }312313                        RecordingTrimWaveform(controller: controller, duration: take.duration)314                            .frame(height: 150)315316                        HStack(spacing: ORIX.Space.md) {317                            secondsField("Start", value: Binding(get: { controller.trimStart }, set: { controller.setTrim(start: $0) }), id: "recording-trim-start")318                            secondsField("End", value: Binding(get: { controller.trimEnd }, set: { controller.setTrim(end: $0) }), id: "recording-trim-end")319                            VStack(alignment: .leading, spacing: 2) {320                                Text("Selection").font(.system(size: 10.5)).foregroundStyle(ORIX.Palette.textTertiary)321                                Text(verbatim: formatTime(controller.selectionLength)).font(ORIX.Typeface.readout(14)).foregroundStyle(ORIX.Palette.textPrimary)322                            }323                            .accessibilityElement(children: .combine).accessibilityIdentifier("recording-trim-length")324                            Button("Whole Take") { controller.trimStart = 0; controller.trimEnd = take.duration }.controlSize(.small)325                                .accessibilityIdentifier("recording-trim-reset")326                            Spacer()327                            if let o = controller.overview {328                                VStack(alignment: .trailing, spacing: 2) {329                                    Text("Peak of the take").font(.system(size: 10.5)).foregroundStyle(ORIX.Palette.textTertiary)330                                    Text(verbatim: o.peak > 0 ? String(format: "%.1f dBFS", 20 * log10(Double(o.peak))) : "silent").font(ORIX.Typeface.readout(14)).foregroundStyle(ORIX.Palette.textPrimary)331                                }332                                .accessibilityElement(children: .combine).accessibilityIdentifier("recording-take-peak")333                            }334                        }335336                        Divider().overlay(ORIX.Palette.hairline)337338                        HStack(alignment: .top, spacing: ORIX.Space.lg) {339                            VStack(alignment: .leading, spacing: ORIX.Space.xs) {340                                SectionLabel("Fades")341                                HStack(spacing: ORIX.Space.md) {342                                    secondsField("Fade in", value: $controller.fadeIn, id: "recording-fade-in")343                                    secondsField("Fade out", value: $controller.fadeOut, id: "recording-fade-out")344                                }345                            }346                            VStack(alignment: .leading, spacing: ORIX.Space.xs) {347                                SectionLabel("Level")348                                Toggle("Normalise the peak to −1 dBFS", isOn: $controller.normalize).toggleStyle(.checkbox).font(.system(size: 12))349                                    .accessibilityIdentifier("recording-normalize")350                                HStack(spacing: 6) {351                                    Text("Gain").font(.system(size: 12)).foregroundStyle(controller.normalize ? ORIX.Palette.textTertiary : ORIX.Palette.textPrimary)352                                    Slider(value: $controller.gainDB, in: -24 ... 12, step: 0.5).frame(width: 150).disabled(controller.normalize)353                                        .accessibilityLabel("Gain").accessibilityValue(Text(verbatim: String(format: "%+.1f decibels", controller.gainDB)))354                                        .accessibilityIdentifier("recording-gain")355                                    Text(verbatim: String(format: "%+.1f dB", controller.gainDB)).font(ORIX.Typeface.value).foregroundStyle(controller.normalize ? ORIX.Palette.textTertiary : ORIX.Palette.textPrimary)356                                        .frame(width: 58, alignment: .trailing)357                                }358                            }359                            VStack(alignment: .leading, spacing: ORIX.Space.xs) {360                                SectionLabel("File")361                                Picker("Format", selection: $controller.format) {362                                    ForEach(AudioFileFormat.allCases) { f in Text(verbatim: f.displayName).tag(f) }363                                }364                                .labelsHidden().frame(width: 200).accessibilityLabel("Format").accessibilityIdentifier("recording-format")365                                HStack(spacing: 4) {366                                    TextField("File name", text: $controller.fileName).textFieldStyle(.roundedBorder).frame(width: 200)367                                        .accessibilityLabel("File name").accessibilityIdentifier("recording-file-name")368                                    Text(verbatim: "." + controller.format.fileExtension).font(ORIX.Typeface.value).foregroundStyle(ORIX.Palette.textTertiary)369                                }370                                Text(controller.format.isLossless ? "Lossless." : "Lossy: smaller, not bit-exact.").font(.system(size: 10.5)).foregroundStyle(ORIX.Palette.textTertiary)371                            }372                            Spacer(minLength: 0)373                        }374                        .controlSize(.small)375376                        HStack(spacing: ORIX.Space.sm) {377                            Button { controller.chooseDestinationAndExport(model: model) } label: {378                                Label("Export…", systemImage: "square.and.arrow.up").font(.system(size: 13, weight: .semibold)).padding(.horizontal, 6).frame(height: 24)379                            }380                            .buttonStyle(.borderedProminent).tint(ORIX.Palette.accent).disabled(controller.exporting)381                            .keyboardShortcut("e", modifiers: [.command])382                            .accessibilityIdentifier("recording-export")383                            if controller.exporting {384                                ProgressView(value: controller.exportProgress).frame(width: 220).accessibilityLabel("Export progress")385                                    .accessibilityIdentifier("recording-export-progress")386                                Text(verbatim: String(format: "%.0f %%", controller.exportProgress * 100)).font(ORIX.Typeface.value).foregroundStyle(ORIX.Palette.textSecondary)387                            }388                            if let error = controller.exportError {389                                Label { Text(verbatim: error) } icon: { Image(systemName: "xmark.octagon.fill") }.font(.system(size: 11)).foregroundStyle(ORIX.Palette.danger)390                                    .accessibilityIdentifier("recording-export-error")391                            }392                            Spacer()393                        }394395                        if let report = controller.report { RecordingReportView(report: report, format: controller.reportFormat, controller: controller) }396                    }397                }398            } else {399                EmptyState(symbol: "scissors", title: "Select a take",400                           message: "Choose a take on the left to see its waveform, trim it, set fades and level, and export it as WAV, AIFF, FLAC, Apple Lossless or AAC.")401            }402        }403        .frame(maxWidth: .infinity, maxHeight: .infinity)404        .accessibilityElement(children: .contain).accessibilityIdentifier("recording-export-panel")405    }406407    private func secondsField(_ label: LocalizedStringKey, value: Binding<Double>, id: String) -> some View {408        VStack(alignment: .leading, spacing: 2) {409            Text(label).font(.system(size: 10.5)).foregroundStyle(ORIX.Palette.textTertiary)410            HStack(spacing: 3) {411                TextField("0", value: value, format: .number.precision(.fractionLength(2))).textFieldStyle(.roundedBorder).frame(width: 72).controlSize(.small)412                    .accessibilityLabel(label).accessibilityIdentifier(id)413                Text("s").font(.system(size: 11)).foregroundStyle(ORIX.Palette.textTertiary)414            }415        }416    }417}418419/// The export result exactly as `AudioExporter` reported it.420private struct RecordingReportView: View {421    var report: ExportReport422    var format: AudioFileFormat?423    var controller: RecordingController424425    var body: some View {426        VStack(alignment: .leading, spacing: ORIX.Space.xs) {427            HStack {428                SectionLabel("Export report")429                Image(systemName: report.validated ? "checkmark.seal.fill" : "exclamationmark.triangle.fill").foregroundStyle(report.validated ? ORIX.Palette.success : ORIX.Palette.warning)430                Text(report.validated ? "Validated: the file was reopened and its length matches." : "Not validated: the file could not be reopened with the expected length.")431                    .font(.system(size: 11, weight: .medium)).foregroundStyle(report.validated ? ORIX.Palette.success : ORIX.Palette.warning)432                    .accessibilityIdentifier("recording-report-validated")433                Spacer()434                Button { controller.reveal(report.url) } label: { Label("Show in Finder", systemImage: "folder") }.controlSize(.small)435                    .accessibilityIdentifier("recording-report-reveal")436            }437            Text(verbatim: report.url.path).font(.system(size: 10.5, design: .monospaced)).foregroundStyle(ORIX.Palette.textSecondary).lineLimit(2).truncationMode(.middle).textSelection(.enabled)438            HStack(alignment: .top, spacing: ORIX.Space.lg) {439                item("Format", format?.displayName ?? report.url.pathExtension.uppercased(), id: "format")440                item("Duration", formatTime(report.duration) + String(format: "  (%d frames)", report.frames), id: "duration")441                item("Sample rate", String(format: "%.0f Hz", report.sampleRate), id: "sample-rate")442                item("Peak", String(format: "%.2f dBFS", report.peakDB), id: "peak")443                item("Clipped samples", "\(report.clippedSamples)", id: "clipped", warn: report.clippedSamples > 0)444                item("Applied gain", String(format: "%+.2f dB", report.appliedGainDB), id: "gain")445                item("File size", RecordingFormat.bytes(report.fileSize), id: "size")446            }447            if report.clippedSamples > 0 {448                Label("\(report.clippedSamples) samples reached full scale and are clipped in the file. Lower the gain or use Normalise, then export again.", systemImage: "exclamationmark.triangle.fill")449                    .font(.system(size: 11, weight: .medium)).foregroundStyle(ORIX.Palette.warning).fixedSize(horizontal: false, vertical: true)450                    .accessibilityIdentifier("recording-report-clip-warning")451            }452        }453        .padding(ORIX.Space.sm)454        .background(ORIX.Palette.surfaceRaised.opacity(0.6), in: RoundedRectangle(cornerRadius: ORIX.Radius.control, style: .continuous))455        .overlay(RoundedRectangle(cornerRadius: ORIX.Radius.control, style: .continuous).strokeBorder(ORIX.Palette.hairline))456        .accessibilityIdentifier("recording-report")457    }458459    private func item(_ label: LocalizedStringKey, _ value: String, id: String, warn: Bool = false) -> some View {460        VStack(alignment: .leading, spacing: 2) {461            Text(label).font(.system(size: 10.5)).foregroundStyle(ORIX.Palette.textTertiary)462            HStack(spacing: 3) {463                if warn { Image(systemName: "exclamationmark.triangle.fill").font(.system(size: 9)).foregroundStyle(ORIX.Palette.warning) }464                Text(verbatim: value).font(ORIX.Typeface.value).foregroundStyle(warn ? ORIX.Palette.warning : ORIX.Palette.textPrimary)465            }466        }467        .accessibilityElement(children: .combine).accessibilityIdentifier("recording-report-\(id)")468    }469}470471// MARK: - Waveform with trim handles472473private struct RecordingTrimWaveform: View {474    var controller: RecordingController475    var duration: Double476    @State private var dragging: Handle?477478    private enum Handle { case start, end }479480    var body: some View {481        GeometryReader { geo in482            let width = geo.size.width, height = geo.size.height483            let x0 = duration > 0 ? CGFloat(controller.trimStart / duration) * width : 0484            let x1 = duration > 0 ? CGFloat(controller.trimEnd / duration) * width : width485            ZStack(alignment: .topLeading) {486                ORIX.Palette.waveformWell487                if let overview = controller.overview, !overview.peaks.isEmpty {488                    Canvas(rendersAsynchronously: true) { context, size in489                        let n = overview.peaks.count490                        let columns = max(1, Int(size.width))491                        let mid = size.height / 2492                        var inside = Path(), outside = Path()493                        for c in 0 ..< columns {494                            let a = c * n / columns, b = max(a + 1, (c + 1) * n / columns)495                            var p: Float = 0496                            for i in a ..< min(b, n) where overview.peaks[i] > p { p = overview.peaks[i] }497                            let t = (Double(c) + 0.5) / Double(columns) * duration498                            // The drawing shows the fades as they will be applied.499                            var g = 1.0500                            if t >= controller.trimStart, t <= controller.trimEnd {501                                if controller.fadeIn > 0 { g = min(g, (t - controller.trimStart) / controller.fadeIn) }502                                if controller.fadeOut > 0 { g = min(g, (controller.trimEnd - t) / controller.fadeOut) }503                            }504                            let h = max(0.5, CGFloat(min(1, Double(p) * max(0, g))) * (mid - 4))505                            let rect = CGRect(x: CGFloat(c), y: mid - h, width: 1, height: h * 2)506                            if t >= controller.trimStart, t <= controller.trimEnd { inside.addRect(rect) } else { outside.addRect(rect) }507                        }508                        context.fill(outside, with: .color(Color(hex: 0x6E7592, opacity: 0.55)))509                        context.fill(inside, with: .color(Color(hex: 0x9B7CFF)))510                        context.fill(Path(CGRect(x: 0, y: mid, width: size.width, height: 0.5)), with: .color(Color.white.opacity(0.18)))511                    }512                } else {513                    Text(controller.overviewLoading ? "Reading the take…" : "The take could not be read.").font(.system(size: 11)).foregroundStyle(Color(hex: 0xA3AAC2))514                        .frame(maxWidth: .infinity, maxHeight: .infinity)515                }516                // Dimmed regions outside the selection.517                Rectangle().fill(Color.black.opacity(0.45)).frame(width: max(0, x0), height: height)518                Rectangle().fill(Color.black.opacity(0.45)).frame(width: max(0, width - x1), height: height).offset(x: x1)519                handle(at: x0, height: height, label: "Trim start", value: controller.trimStart, leading: true)520                handle(at: x1, height: height, label: "Trim end", value: controller.trimEnd, leading: false)521            }522            .clipShape(RoundedRectangle(cornerRadius: ORIX.Radius.control, style: .continuous))523            .contentShape(Rectangle())524            .gesture(DragGesture(minimumDistance: 0).onChanged { g in525                guard duration > 0, width > 0 else { return }526                if dragging == nil { dragging = abs(g.startLocation.x - x0) <= abs(g.startLocation.x - x1) ? .start : .end }527                let t = Double(min(max(0, g.location.x), width) / width) * duration528                if dragging == .start { controller.setTrim(start: t) } else { controller.setTrim(end: t) }529            }.onEnded { _ in dragging = nil })530        }531        .accessibilityElement(children: .contain)532        .accessibilityLabel("Take waveform with trim handles")533        .accessibilityIdentifier("recording-waveform")534    }535536    private func handle(at x: CGFloat, height: CGFloat, label: LocalizedStringKey, value: Double, leading: Bool) -> some View {537        ZStack(alignment: leading ? .topLeading : .topTrailing) {538            Rectangle().fill(Color(hex: 0xFBBF24)).frame(width: 2, height: height)539            UnevenRoundedRectangle(topLeadingRadius: leading ? 0 : 4, bottomLeadingRadius: leading ? 0 : 4, bottomTrailingRadius: leading ? 4 : 0, topTrailingRadius: leading ? 4 : 0)540                .fill(Color(hex: 0xFBBF24)).frame(width: 10, height: 22)541                .overlay(Image(systemName: leading ? "chevron.compact.right" : "chevron.compact.left").font(.system(size: 9, weight: .bold)).foregroundStyle(Color.black.opacity(0.8)))542        }543        .frame(width: 10, height: height, alignment: leading ? .topLeading : .topTrailing)544        .offset(x: leading ? x : x - 10)545        .accessibilityElement(children: .ignore)546        .accessibilityLabel(label)547        .accessibilityValue(Text(verbatim: formatTime(value)))548        .accessibilityAdjustableAction { direction in549            let step = max(0.05, duration / 200)550            let delta = direction == .increment ? step : -step551            if leading { controller.setTrim(start: value + delta) } else { controller.setTrim(end: value + delta) }552        }553    }554}555
Files main
Menu

Theme