From 231feee8713eae82ad8f4c505de4967006c53efe Mon Sep 17 00:00:00 2001 From: HR0101 Date: Wed, 4 Nov 2026 23:56:21 +0900 Subject: [PATCH 1/7] =?UTF-8?q?feat(ui):=20=E3=82=A2=E3=83=97=E3=83=AA?= =?UTF-8?q?=E5=86=85=E3=81=AE=E9=81=B8=E6=8A=9E=E6=93=8D=E4=BD=9C=E3=82=92?= =?UTF-8?q?=E7=8B=AC=E8=87=AA=E3=83=91=E3=83=8D=E3=83=AB=E3=81=AB=E7=B5=B1?= =?UTF-8?q?=E4=B8=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ArkServer/App/Views/ContentView.swift | 5 +- .../Common/DesignSystem/DesignSystem.swift | 2 +- .../DesignSystem/SettingsComponents.swift | 658 +++++++++++++++++- .../Features/Dashboard/Views/HomeView.swift | 14 +- .../Dashboard/Views/ServerHeroCard.swift | 6 +- .../Library/Views/AlbumDetailView.swift | 20 +- .../Library/Views/AlbumOverviewView.swift | 6 +- .../Library/Views/FolderDetailView.swift | 2 +- .../Library/Views/LibraryCategoryView.swift | 16 +- .../Library/Views/MediaGridControlBar.swift | 10 +- .../Library/Views/MediaGridItem.swift | 4 +- .../Views/SimilarMediaView.swift | 2 +- .../Views/SketchCleanupView.swift | 2 +- .../Views/VariantVideoView.swift | 8 +- .../Views/MusicVideoCutEditorView.swift | 6 +- .../Views/MusicVideoExportAlbumSheet.swift | 4 +- .../Views/MusicVideoMusicPickerView.swift | 4 +- .../Views/MusicVideoSourcePickerView.swift | 16 +- .../MusicVideo/Views/MusicVideoView.swift | 18 +- .../Navigation/Views/MainSidebarView.swift | 55 +- .../Playback/Views/PhotoViewerView.swift | 2 +- .../Playback/Views/SlideshowPlayerView.swift | 2 +- .../Views/VariantSwitchPlayerView.swift | 18 +- .../Playback/Views/VideoPlayerView.swift | 452 ++++++++++-- .../Views/CandidateListView.swift | 2 +- .../Views/SceneExtractionTutorialView.swift | 2 +- .../Views/SceneExtractionView.swift | 8 +- .../Settings/Views/SettingsPageView.swift | 10 +- .../Storage/Views/StorageManagerView.swift | 2 +- 29 files changed, 1186 insertions(+), 170 deletions(-) diff --git a/ArkServer/App/Views/ContentView.swift b/ArkServer/App/Views/ContentView.swift index 7aa0a1e..57e8f58 100644 --- a/ArkServer/App/Views/ContentView.swift +++ b/ArkServer/App/Views/ContentView.swift @@ -80,6 +80,7 @@ struct ContentView: View { WindowChromeConfigurator(isToolbarHidden: isToolbarHidden) ) .tint(NeomorphicTheme.accent) + .toggleStyle(AppToggleStyle()) .preferredColorScheme(appSettings.neomorphicDarkBase ? .dark : .light) .environmentObject(playbackCoordinator) .environmentObject(viewModel.remotePlaybackSession) @@ -96,7 +97,7 @@ struct ContentView: View { .sheet(isPresented: $viewModel.isShowingAccessLog) { AccessLogView(webServerManager: viewModel.webServerManager) } - .alert( + .appAlert( "ファイル操作の結果", isPresented: Binding( get: { dataManager.mediaDeletionNotice != nil }, @@ -109,7 +110,7 @@ struct ContentView: View { } message: { Text(dataManager.mediaDeletionNotice ?? "") } - .alert( + .appAlert( "シーン抽出を開始できません", isPresented: Binding( get: { viewModel.sceneExtractionNavigationError != nil }, diff --git a/ArkServer/Common/DesignSystem/DesignSystem.swift b/ArkServer/Common/DesignSystem/DesignSystem.swift index 85b2ae6..fc1f82e 100644 --- a/ArkServer/Common/DesignSystem/DesignSystem.swift +++ b/ArkServer/Common/DesignSystem/DesignSystem.swift @@ -416,7 +416,7 @@ struct SettingToggleRow: View { Spacer(minLength: 12) Toggle("", isOn: $isOn) .labelsHidden() - .toggleStyle(.switch) + .toggleStyle(AppToggleStyle()) .controlSize(.small) } .contentShape(Rectangle()) diff --git a/ArkServer/Common/DesignSystem/SettingsComponents.swift b/ArkServer/Common/DesignSystem/SettingsComponents.swift index b31450f..3cbb7f4 100644 --- a/ArkServer/Common/DesignSystem/SettingsComponents.swift +++ b/ArkServer/Common/DesignSystem/SettingsComponents.swift @@ -1,5 +1,6 @@ // ArkServer/Common/DesignSystem/SettingsComponents.swift +import AppKit import SwiftUI // 設定画面のような「見出し + 行をまとめた面」で画面を組むための共通部品(一般的な設定画面の見た目に倣う)。 @@ -132,9 +133,660 @@ struct SettingsSwitch: View { @Binding var isOn: Bool var body: some View { - Toggle(title, isOn: $isOn) - .labelsHidden() - .toggleStyle(.switch) + Toggle(isOn: $isOn) { EmptyView() } + .toggleStyle(AppToggleStyle()) + .accessibilityLabel(title) .controlSize(.small) } } + +// MARK: - アプリ共通の選択パネル + +private struct AppChoiceDismissKey: EnvironmentKey { + static let defaultValue: (() -> Void)? = nil +} + +private struct AppChoiceNestedKey: EnvironmentKey { + static let defaultValue = false +} + +private extension EnvironmentValues { + var appChoiceDismiss: (() -> Void)? { + get { self[AppChoiceDismissKey.self] } + set { self[AppChoiceDismissKey.self] = newValue } + } + var appChoiceIsNested: Bool { + get { self[AppChoiceNestedKey.self] } + set { self[AppChoiceNestedKey.self] = newValue } + } +} + +/// 標準メニューの代わりに使う。入れ子は同じパネルの中で展開する。 +struct AppChoiceMenu: View { + var title: String? = nil + @ViewBuilder var content: Content + @ViewBuilder var label: Label + @Environment(\.appChoiceIsNested) private var isNested + @State private var isPresented = false + @State private var isExpanded = false + + var body: some View { + if isNested { + VStack(alignment: .leading, spacing: 4) { + AppChoiceRowButton(action: { isExpanded.toggle() }) { + HStack(spacing: 12) { + label + Spacer(minLength: 8) + Image(systemName: isExpanded ? "chevron.down" : "chevron.right") + .font(.system(size: 10, weight: .medium)) + .foregroundStyle(NeomorphicTheme.muted) + } + } + if isExpanded { + AppChoiceItems(content: { content }) + .padding(.leading, 12) + } + } + } else { + Button { isPresented.toggle() } label: { + HStack(spacing: 8) { + label + Image(systemName: "chevron.down") + .font(.system(size: 8, weight: .medium)) + .foregroundStyle(NeomorphicTheme.muted) + } + } + .buttonStyle(.quiet) + .popover(isPresented: $isPresented, arrowEdge: .bottom) { + AppChoiceSurface(close: { isPresented = false }) { + if let title { Text(title) } else { label } + } content: { + AppChoiceItems(content: { content }) + } + .environment(\.appChoiceDismiss, { isPresented = false }) + .environment(\.appChoiceIsNested, true) + } + } + } +} + +extension AppChoiceMenu where Label == Text { + init(_ title: String, @ViewBuilder content: () -> Content) { + self.title = title + self.content = content() + self.label = Text(title) + } +} + +/// .tagをそのまま使い,既存の選択値・Binding・任意値の選択を保つ。 +struct AppChoicePicker: View { + let title: String + @Binding var selection: SelectionValue + @ViewBuilder var content: Content + @Environment(\.appChoiceIsNested) private var isNested + + init(_ title: String, selection: Binding, @ViewBuilder content: () -> Content) { + self.title = title + self._selection = selection + self.content = content() + } + + var body: some View { + Group(subviews: content) { options in + let selected = options.first { $0.containerValues.hasTag(selection) } + VStack(alignment: .leading, spacing: 4) { + if isNested { + Text(title) + .font(.appCaptionStrong) + .foregroundStyle(NeomorphicTheme.muted) + .padding(.horizontal, 12) + } + AppChoiceMenu(title: title) { + ForEach(options) { option in + if let value = option.containerValues.tag(for: SelectionValue.self) { + AppChoicePickerRow(value: value, selection: $selection) { option } + } + } + } label: { + if let selected { selected } else { Text(title) } + } + } + .accessibilityLabel(title) + } + } +} + +private struct AppChoicePickerRow: View { + let value: Value + @Binding var selection: Value + @ViewBuilder var label: Label + @Environment(\.appChoiceDismiss) private var dismissPanel + + var body: some View { + AppChoiceRowButton(isSelected: selection == value, action: { + selection = value + dismissPanel?() + }) { + HStack(spacing: 12) { + label + Spacer(minLength: 8) + Group { + if selection == value { + Image(systemName: "checkmark") + .font(.system(size: 11, weight: .medium)) + .foregroundStyle(NeomorphicTheme.accent) + } else { + Color.clear + } + } + .frame(width: 16, height: 16) + } + } + .accessibilityAddTraits(selection == value ? .isSelected : []) + } +} + +/// セクション・動的な行・条件付き項目を展開し,見出しの階層を保つ。 +private struct AppChoiceItems: View { + @ViewBuilder var content: Content + + var body: some View { + VStack(alignment: .leading, spacing: 12) { + ForEach(sections: content) { section in + VStack(alignment: .leading, spacing: 4) { + if !section.header.isEmpty { + ForEach(section.header) { header in + header + .font(.appCaptionStrong) + .foregroundStyle(NeomorphicTheme.muted) + .padding(.horizontal, 12) + .padding(.vertical, 4) + .accessibilityAddTraits(.isHeader) + } + } + ForEach(section.content) { item in + item.frame(maxWidth: .infinity, alignment: .leading) + } + if !section.footer.isEmpty { + ForEach(section.footer) { footer in + footer.font(.appCaption).foregroundStyle(NeomorphicTheme.muted) + } + } + } + } + } + .font(.appBody) + .buttonStyle(AppChoiceActionStyle()) + .toggleStyle(AppToggleStyle(isCheckbox: true)) + .labelStyle(.titleAndIcon) + } +} + +private struct AppChoiceSurface: View { + let close: () -> Void + @ViewBuilder var header: Header + @ViewBuilder var content: Content + @State private var contentHeight: CGFloat = 44 + private let maximumHeight: CGFloat = 420 + + var body: some View { + VStack(spacing: 0) { + HStack(spacing: 12) { + header + .font(.appBodyStrong) + .lineLimit(2) + .accessibilityAddTraits(.isHeader) + Spacer(minLength: 8) + Button(action: close) { + Image(systemName: "xmark") + .font(.system(size: 10, weight: .medium)) + .frame(width: 24, height: 24) + } + .buttonStyle(.plain) + .focusable(false) + .accessibilityLabel("選択パネルを閉じる") + } + .padding(16) + Divider().overlay(NeomorphicTheme.separator) + ScrollView { + content + .frame(maxWidth: .infinity, alignment: .leading) + .padding(12) + .onGeometryChange(for: CGFloat.self) { $0.size.height } action: { contentHeight = $0 } + } + .frame(height: min(maximumHeight, max(44, contentHeight))) + .scrollBounceBehavior(.basedOnSize) + } + .frame(width: 340) + .background(NeomorphicTheme.canvas) + .foregroundStyle(NeomorphicTheme.ink) + .tint(NeomorphicTheme.accent) + .environment(\.colorScheme, NeomorphicTheme.isDarkBase ? .dark : .light) + .background(AppChoiceFocusBridge()) + .onKeyPress(.escape) { close(); return .handled } + .onKeyPress(.downArrow) { + NSApp.keyWindow?.selectNextKeyView(nil) + return .handled + } + .onKeyPress(.upArrow) { + NSApp.keyWindow?.selectPreviousKeyView(nil) + return .handled + } + } +} + +/// パネルを閉じてから,元のButtonの処理を一度だけ実行する。 +private struct AppChoiceActionStyle: PrimitiveButtonStyle { + @Environment(\.appChoiceDismiss) private var dismissPanel + + @ViewBuilder + func makeBody(configuration: Configuration) -> some View { + let row = AppChoiceRowButton(role: configuration.role, action: { + dismissPanel?() + DispatchQueue.main.async { configuration.trigger() } + }) { configuration.label } + if configuration.role == .cancel { + row.keyboardShortcut(.cancelAction) + } else { + row + } + } +} + +// MARK: - 右クリックと確認の選択パネル + +extension View { + func appContextMenu(@ViewBuilder content: @escaping () -> Choices) -> some View { + modifier(AppContextChoiceModifier(choices: content)) + } + + func appAlert( + _ title: String, isPresented: Binding, + @ViewBuilder actions: @escaping () -> Actions, + @ViewBuilder message: @escaping () -> Message + ) -> some View { + sheet(isPresented: isPresented) { + AppChoiceDialog(title: title, close: { isPresented.wrappedValue = false }, actions: actions, message: message) + } + } + + func appConfirmationPanel( + _ title: String, isPresented: Binding, titleVisibility: Visibility = .automatic, + @ViewBuilder actions: @escaping () -> Actions, + @ViewBuilder message: @escaping () -> Message + ) -> some View { + appAlert(title, isPresented: isPresented, actions: actions, message: message) + } + + func appConfirmationPanel( + _ title: String, isPresented: Binding, titleVisibility: Visibility = .automatic, + presenting data: Data?, + @ViewBuilder actions: @escaping (Data) -> Actions, + @ViewBuilder message: @escaping (Data) -> Message + ) -> some View { + sheet(isPresented: isPresented) { + if let data { + AppChoiceDialog(title: title, close: { isPresented.wrappedValue = false }) { + actions(data) + } message: { + message(data) + } + } + } + } +} + +private struct AppChoiceDialog: View { + let title: String + let close: () -> Void + @ViewBuilder var actions: Actions + @ViewBuilder var message: Message + + var body: some View { + VStack(alignment: .leading, spacing: 20) { + Text(title) + .font(.appTitle) + .foregroundStyle(NeomorphicTheme.ink) + .accessibilityAddTraits(.isHeader) + message + .font(.appBody) + .foregroundStyle(NeomorphicTheme.muted) + .fixedSize(horizontal: false, vertical: true) + Divider().overlay(NeomorphicTheme.separator) + AppChoiceItems(content: { actions }) + .textFieldStyle(.roundedBorder) + .environment(\.appChoiceDismiss, close) + .environment(\.appChoiceIsNested, true) + } + .padding(24) + .frame(width: 480) + .background(NeomorphicTheme.canvas) + .tint(NeomorphicTheme.accent) + .environment(\.colorScheme, NeomorphicTheme.isDarkBase ? .dark : .light) + .interactiveDismissDisabled() + } +} + +private struct AppContextChoiceModifier: ViewModifier { + @ViewBuilder var choices: Choices + @State private var isPresented = false + @State private var anchor = UnitPoint.center + + func body(content: Content) -> some View { + content + .overlay { + AppRightClickAnchor { point in + anchor = point + isPresented = true + } + } + .popover(isPresented: $isPresented, attachmentAnchor: .point(anchor), arrowEdge: .top) { + AppChoiceSurface(close: { isPresented = false }) { + Text("項目の操作") + } content: { + AppChoiceItems(content: { choices }) + } + .environment(\.appChoiceDismiss, { isPresented = false }) + .environment(\.appChoiceIsNested, true) + } + } +} + +/// 左クリック・ドラッグ・スクロールは元のビューへ渡し,右クリックだけを受け取る。 +private struct AppRightClickAnchor: NSViewRepresentable { + let open: (UnitPoint) -> Void + + func makeNSView(context: Context) -> AnchorView { AnchorView(open: open) } + func updateNSView(_ view: AnchorView, context: Context) { view.open = open } + + final class AnchorView: NSView { + var open: (UnitPoint) -> Void + + init(open: @escaping (UnitPoint) -> Void) { + self.open = open + super.init(frame: .zero) + } + + required init?(coder: NSCoder) { return nil } + + override func hitTest(_ point: NSPoint) -> NSView? { + guard let event = NSApp.currentEvent else { return nil } + let isContextClick = event.type == .rightMouseDown || event.type == .rightMouseUp + || (event.type == .leftMouseDown && event.modifierFlags.contains(.control)) + return isContextClick ? super.hitTest(point) : nil + } + + override func rightMouseDown(with event: NSEvent) { showPanel(for: event) } + override func mouseDown(with event: NSEvent) { + if event.modifierFlags.contains(.control) { showPanel(for: event) } + } + + private func showPanel(for event: NSEvent) { + guard bounds.width > 0, bounds.height > 0 else { return } + let point = convert(event.locationInWindow, from: nil) + let x = min(1, max(0, point.x / bounds.width)) + let y = min(1, max(0, point.y / bounds.height)) + open(UnitPoint(x: x, y: isFlipped ? y : 1 - y)) + } + } +} + +// MARK: - 時刻の選択 + +struct AppTimePicker: View { + let title: String + @Binding var selection: Date + @State private var errorMessage: String? + + init(_ title: String, selection: Binding, displayedComponents: DatePickerComponents = .hourAndMinute) { + self.title = title + self._selection = selection + } + + private var hour: Int { Calendar.current.component(.hour, from: selection) } + private var minute: Int { Calendar.current.component(.minute, from: selection) } + + var body: some View { + AppChoiceMenu(title: title) { + HStack(spacing: 12) { + timeField("時", value: Binding(get: { hour }, set: { setTime(hour: $0, minute: minute) }), range: 0...23) + Text(":").font(.appMonoBody).foregroundStyle(NeomorphicTheme.muted) + timeField("分", value: Binding(get: { minute }, set: { setTime(hour: hour, minute: $0) }), range: 0...59) + } + .padding(8) + if let errorMessage { + Text(errorMessage).font(.appCaption).foregroundStyle(.red) + } + } label: { + HStack(spacing: 12) { + Text(title) + Spacer(minLength: 0) + Text(String(format: "%02d:%02d", hour, minute)).font(.appMonoBody) + } + } + } + + private func timeField(_ label: String, value: Binding, range: ClosedRange) -> some View { + HStack(spacing: 8) { + TextField(label, value: value, format: .number.grouping(.never)) + .textFieldStyle(.plain) + .font(.appTitle.monospacedDigit()) + .multilineTextAlignment(.center) + .frame(width: 44) + .accessibilityLabel(label) + Text(label).font(.appCaption).foregroundStyle(NeomorphicTheme.muted) + VStack(spacing: 4) { + Button { value.wrappedValue = min(range.upperBound, value.wrappedValue + 1) } label: { + Image(systemName: "chevron.up").frame(width: 20, height: 16) + } + .disabled(value.wrappedValue >= range.upperBound) + .accessibilityLabel("\(label)を増やす") + Button { value.wrappedValue = max(range.lowerBound, value.wrappedValue - 1) } label: { + Image(systemName: "chevron.down").frame(width: 20, height: 16) + } + .disabled(value.wrappedValue <= range.lowerBound) + .accessibilityLabel("\(label)を減らす") + } + .font(.system(size: 9, weight: .medium)) + .buttonStyle(.plain) + } + .padding(8) + .background(NeomorphicTheme.control, in: RoundedRectangle(cornerRadius: 8)) + } + + private func setTime(hour: Int, minute: Int) { + guard (0...23).contains(hour), (0...59).contains(minute) else { return } + let second = Calendar.current.component(.second, from: selection) + guard let date = Calendar.current.date(bySettingHour: hour, minute: minute, second: second, of: selection) else { + errorMessage = "時刻を設定できませんでした.別の時刻を選んでください." + return + } + errorMessage = nil + selection = date + } +} + +/// 数値の増減ボタンも共通の面で描く。元のBindingまたは増減コールバックを使う。 +struct AppNumberStepper: View { + let onIncrement: () -> Void + let onDecrement: () -> Void + var canIncrement = true + var canDecrement = true + @ViewBuilder var label: Label + + init(onIncrement: @escaping () -> Void, onDecrement: @escaping () -> Void, @ViewBuilder label: () -> Label) { + self.onIncrement = onIncrement + self.onDecrement = onDecrement + self.label = label() + } + + init(value: Binding, in bounds: ClosedRange, step: Value.Stride = 1, @ViewBuilder label: () -> Label) { + onIncrement = { value.wrappedValue = min(bounds.upperBound, value.wrappedValue.advanced(by: step)) } + onDecrement = { value.wrappedValue = max(bounds.lowerBound, value.wrappedValue.advanced(by: -step)) } + canIncrement = value.wrappedValue < bounds.upperBound + canDecrement = value.wrappedValue > bounds.lowerBound + self.label = label() + } + + var body: some View { + HStack(spacing: 8) { + label + VStack(spacing: 2) { + Button(action: onIncrement) { Image(systemName: "chevron.up").frame(width: 24, height: 16) } + .disabled(!canIncrement) + .accessibilityLabel("値を増やす") + Button(action: onDecrement) { Image(systemName: "chevron.down").frame(width: 24, height: 16) } + .disabled(!canDecrement) + .accessibilityLabel("値を減らす") + } + .font(.system(size: 9, weight: .medium)) + .buttonStyle(.plain) + .background(NeomorphicTheme.control, in: RoundedRectangle(cornerRadius: 4)) + } + } +} + +extension AppNumberStepper where Label == Text { + init(_ title: String, value: Binding, in bounds: ClosedRange, step: Value.Stride = 1) { + self.init(value: value, in: bounds, step: step) { Text(title) } + } +} + +/// パネル以外の決定・キャンセル操作も,同じ面と輪郭で統一する。 +struct AppActionButtonStyle: ButtonStyle { + var isPrimary = false + @Environment(\.isEnabled) private var isEnabled + @State private var isHovering = false + + func makeBody(configuration: Configuration) -> some View { + let isDestructive = configuration.role == .destructive + let foreground: Color = isPrimary + ? (isDestructive ? .white : NeomorphicTheme.canvas) + : (isDestructive ? .red : NeomorphicTheme.ink) + let background: Color = isPrimary + ? (isDestructive ? .red : NeomorphicTheme.ink) + : (isHovering ? NeomorphicTheme.controlSelected : NeomorphicTheme.control) + return configuration.label + .font(.appCaptionStrong) + .foregroundStyle(foreground) + .padding(.horizontal, 12) + .padding(.vertical, 8) + .background(background, in: RoundedRectangle(cornerRadius: 8)) + .overlay { + RoundedRectangle(cornerRadius: 8) + .strokeBorder(NeomorphicTheme.cardBorder, lineWidth: 1) + } + .contentShape(RoundedRectangle(cornerRadius: 8)) + .opacity(isEnabled ? (configuration.isPressed ? 0.75 : 1) : 0.4) + .onHover { isHovering = $0 } + } +} + +private struct AppChoiceRowButton: View { + var role: ButtonRole? = nil + var isSelected = false + let action: () -> Void + @ViewBuilder var label: Label + @Environment(\.isEnabled) private var isEnabled + @State private var isHovering = false + @FocusState private var isFocused: Bool + + var body: some View { + Button(role: role, action: action) { + label + .font(.appBody) + .foregroundStyle(role == .destructive ? Color.red : NeomorphicTheme.ink) + .multilineTextAlignment(.leading) + .frame(maxWidth: .infinity, alignment: .leading) + .padding(.horizontal, 12) + .padding(.vertical, 10) + .frame(minHeight: 36) + .background( + RoundedRectangle(cornerRadius: 8) + .fill(isHovering || isFocused || isSelected ? NeomorphicTheme.control : .clear) + ) + .overlay(alignment: .leading) { + if isHovering || isFocused || isSelected { + RoundedRectangle(cornerRadius: 1) + .fill(NeomorphicTheme.accent) + .frame(width: 2, height: 16) + .padding(.leading, 2) + } + } + .contentShape(RoundedRectangle(cornerRadius: 8)) + .opacity(isEnabled ? 1 : 0.4) + } + .buttonStyle(.plain) + .focusable(isEnabled) + .focusEffectDisabled() + .focused($isFocused) + .onHover { isHovering = $0 } + .onKeyPress(.return) { + guard isEnabled else { return .ignored } + action() + return .handled + } + } +} + +/// 既存のToggleのBindingとラベルを保ち,スイッチとチェックを共通の輪郭で描く。 +struct AppToggleStyle: ToggleStyle { + var isCheckbox = false + + func makeBody(configuration: Configuration) -> some View { + Button { configuration.isOn.toggle() } label: { + HStack(spacing: 8) { + if isCheckbox { indicator(configuration.isOn) } + configuration.label + if !isCheckbox { + Spacer(minLength: 8) + indicator(configuration.isOn) + } + } + .font(.appBody) + .foregroundStyle(NeomorphicTheme.ink) + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + .accessibilityValue(configuration.isOn ? "オン" : "オフ") + } + + private func indicator(_ isOn: Bool) -> some View { + ZStack(alignment: isCheckbox ? .center : (isOn ? .trailing : .leading)) { + RoundedRectangle(cornerRadius: isCheckbox ? 4 : 6) + .fill(isOn ? NeomorphicTheme.ink : NeomorphicTheme.control) + RoundedRectangle(cornerRadius: isCheckbox ? 4 : 6) + .strokeBorder(NeomorphicTheme.cardBorder, lineWidth: 1) + if isCheckbox { + if isOn { + Image(systemName: "checkmark") + .font(.system(size: 10, weight: .semibold)) + .foregroundStyle(NeomorphicTheme.canvas) + } + } else { + RoundedRectangle(cornerRadius: 3) + .fill(isOn ? NeomorphicTheme.canvas : NeomorphicTheme.muted) + .frame(width: 14, height: 14) + .padding(3) + } + } + .frame(width: isCheckbox ? 20 : 36, height: 20) + .accessibilityHidden(true) + } +} + +private struct AppChoiceFocusBridge: NSViewRepresentable { + func makeNSView(context: Context) -> FocusView { FocusView() } + func updateNSView(_ view: FocusView, context: Context) {} + + final class FocusView: NSView { + override func viewDidMoveToWindow() { + super.viewDidMoveToWindow() + guard let window else { return } + DispatchQueue.main.async { [weak window] in + window?.makeKey() + window?.selectNextKeyView(nil) + } + } + } +} diff --git a/ArkServer/Features/Dashboard/Views/HomeView.swift b/ArkServer/Features/Dashboard/Views/HomeView.swift index b91106a..1c6d405 100644 --- a/ArkServer/Features/Dashboard/Views/HomeView.swift +++ b/ArkServer/Features/Dashboard/Views/HomeView.swift @@ -170,7 +170,7 @@ struct HomeView: View { .frame(maxWidth: .infinity) } // 補助の操作は塗りつぶさない(青い全幅ボタンが並ぶと、本当の主役である「開始」が埋もれる)。 - .buttonStyle(.bordered) + .buttonStyle(AppActionButtonStyle()) .tint(NeomorphicTheme.ink) .disabled(duplicateCheckStatus.isAutoChecking || dataManager.isDuplicateCheckRunning || totalCount == 0) .help("自動チェックのオン/オフに関わらず,対象アルバムの重複をまとめて今すぐチェックします.") @@ -226,7 +226,7 @@ struct HomeView: View { .frame(maxWidth: .infinity) } // 補助の操作は塗りつぶさない(青い全幅ボタンが並ぶと、本当の主役である「開始」が埋もれる)。 - .buttonStyle(.bordered) + .buttonStyle(AppActionButtonStyle()) .tint(NeomorphicTheme.ink) .disabled(status.isScanning || count == 0) @@ -332,7 +332,7 @@ struct HomeView: View { } label: { Label("選択", systemImage: "checkmark.circle") } - .buttonStyle(.bordered) + .buttonStyle(AppActionButtonStyle()) .tint(NeomorphicTheme.ink) .controlSize(.small) } @@ -452,16 +452,16 @@ struct HomeView: View { if webServerManager.scheduleEnabled { Divider() - DatePicker("起動時刻", selection: $webServerManager.scheduleStartTime, displayedComponents: .hourAndMinute) + AppTimePicker("起動時刻", selection: $webServerManager.scheduleStartTime, displayedComponents: .hourAndMinute) .font(.appCaption) - DatePicker("停止時刻", selection: $webServerManager.scheduleStopTime, displayedComponents: .hourAndMinute) + AppTimePicker("停止時刻", selection: $webServerManager.scheduleStopTime, displayedComponents: .hourAndMinute) .font(.appCaption) Button(action: { webServerManager.applySchedule() }) { Label("このスケジュールを適用", systemImage: "checkmark.circle") .frame(maxWidth: .infinity) } - .buttonStyle(.bordered) + .buttonStyle(AppActionButtonStyle()) .tint(NeomorphicTheme.ink) Text("適用時に管理者パスワードの入力を求められます(スリープからの自動起床設定のため).停止時刻になるとアプリは完全終了します.") @@ -603,7 +603,7 @@ struct HomeView: View { Label("ストレージ管理を開く", systemImage: "slider.horizontal.3") .frame(maxWidth: .infinity) } - .buttonStyle(.bordered) + .buttonStyle(AppActionButtonStyle()) .tint(NeomorphicTheme.ink) } .dashboardCard() diff --git a/ArkServer/Features/Dashboard/Views/ServerHeroCard.swift b/ArkServer/Features/Dashboard/Views/ServerHeroCard.swift index c175c13..faa345c 100644 --- a/ArkServer/Features/Dashboard/Views/ServerHeroCard.swift +++ b/ArkServer/Features/Dashboard/Views/ServerHeroCard.swift @@ -63,7 +63,7 @@ struct ServerHeroCard: View { .padding(.horizontal, 6) .padding(.vertical, 3) } - .buttonStyle(.bordered) + .buttonStyle(AppActionButtonStyle()) .tint(NeomorphicTheme.ink) .accessibilityLabel("サーバーを停止") } else { @@ -73,7 +73,7 @@ struct ServerHeroCard: View { .padding(.horizontal, 8) .padding(.vertical, 4) } - .buttonStyle(.borderedProminent) + .buttonStyle(AppActionButtonStyle(isPrimary: true)) .accessibilityLabel("サーバーを開始") } } @@ -103,7 +103,7 @@ struct ServerHeroCard: View { Label("開く", systemImage: "arrow.up.forward.app") .font(.appBodyStrong) } - .buttonStyle(.bordered) + .buttonStyle(AppActionButtonStyle()) .tint(NeomorphicTheme.ink) .help("このMacのブラウザで接続先を開く") } diff --git a/ArkServer/Features/Library/Views/AlbumDetailView.swift b/ArkServer/Features/Library/Views/AlbumDetailView.swift index 41c0049..1d4f7f1 100644 --- a/ArkServer/Features/Library/Views/AlbumDetailView.swift +++ b/ArkServer/Features/Library/Views/AlbumDetailView.swift @@ -243,7 +243,7 @@ struct AlbumDetailView: View { // 見分けがつかないため,名前付きの1つのメニューにまとめる。 ToolbarItem(placement: .primaryAction) { if hasOrganizeTools { - Menu { + AppChoiceMenu { // 重複チェックはアルバム単位でのみ意味を持つ(すべての動画/画像には全アルバムのメディアが // 集まっているため、ここで実行すると別アルバム同士のメディアまで重複扱いになってしまう)。 if canRemoveItemsFromCurrentAlbum { @@ -302,7 +302,7 @@ struct AlbumDetailView: View { // ランダム同時再生(本数を選ぶと、このアルバムからその数だけ無作為に選んで並べる) ToolbarItem(placement: .primaryAction) { if videoItems.count >= 2 { - Menu { + AppChoiceMenu { ForEach(2...min(9, videoItems.count), id: \.self) { count in Button("\(count)本") { startMultiPlayback(Array(videoItems.shuffled().prefix(count))) @@ -346,7 +346,7 @@ struct AlbumDetailView: View { // 複数選択時の再生方法は4種類あり,アイコンだけを並べると見分けにくいので1つのメニューにまとめる。 ToolbarItem(placement: .primaryAction) { if selectedItems.count >= 2 { - Menu { + AppChoiceMenu { Button { startMultiPlayback(selectedItems) } label: { @@ -434,7 +434,7 @@ struct AlbumDetailView: View { .onDrop(of: [.fileURL], isTargeted: $isTargeted) { providers in return handleDrop(providers: providers) } - .alert("異なるメディアタイプの混在", isPresented: $showMixedContentAlert) { + .appAlert("異なるメディアタイプの混在", isPresented: $showMixedContentAlert) { Button("現在のアルバムのタイプ (\(album.type.displayName)) としてインポート") { if let url = pendingFolderURL { Task { @@ -452,17 +452,17 @@ struct AlbumDetailView: View { } message: { Text("\(mixedContentInfo)\n指定したタイプ (\(album.type.displayName)) 以外のファイルは無視されます.") } - .alert("重複チェック完了", isPresented: $showDuplicateCheckResultAlert) { + .appAlert("重複チェック完了", isPresented: $showDuplicateCheckResultAlert) { Button("OK", role: .cancel) { } } message: { Text(duplicateCheckResultMessage) } - .alert("エクスポート完了", isPresented: $showExportResultAlert) { + .appAlert("エクスポート完了", isPresented: $showExportResultAlert) { Button("OK", role: .cancel) { } } message: { Text(exportResultMessage) } - .alert("新規アルバムに移動", isPresented: $showMoveToNewAlbumAlert) { + .appAlert("新規アルバムに移動", isPresented: $showMoveToNewAlbumAlert) { TextField("アルバム名", text: $newAlbumNameForMove) Button("作成して移動") { let name = newAlbumNameForMove.trimmingCharacters(in: .whitespaces) @@ -487,7 +487,7 @@ struct AlbumDetailView: View { .foregroundStyle(.secondary) .lineLimit(1) } - Stepper("分割数: \(splitCount)", value: $splitCount, in: 2...9) + AppNumberStepper("分割数: \(splitCount)", value: $splitCount, in: 2...9) .frame(width: 200) Text("動画を\(splitCount)等分して\(splitCount)画面で同時再生します") .font(.appCaption) @@ -502,7 +502,7 @@ struct AlbumDetailView: View { } } .keyboardShortcut(.defaultAction) - .buttonStyle(.borderedProminent) + .buttonStyle(AppActionButtonStyle(isPrimary: true)) } } .padding(30) @@ -785,7 +785,7 @@ struct AlbumDetailView: View { Text("「\(searchText)」に一致するタイトルは見つかりませんでした.") } actions: { Button("検索を解除") { searchText = "" } - .buttonStyle(.borderedProminent) + .buttonStyle(AppActionButtonStyle(isPrimary: true)) } .frame(maxWidth: .infinity, maxHeight: .infinity) } diff --git a/ArkServer/Features/Library/Views/AlbumOverviewView.swift b/ArkServer/Features/Library/Views/AlbumOverviewView.swift index e21d912..64592ac 100644 --- a/ArkServer/Features/Library/Views/AlbumOverviewView.swift +++ b/ArkServer/Features/Library/Views/AlbumOverviewView.swift @@ -160,7 +160,7 @@ struct AlbumOverviewView: View { private var flatToggle: some View { Toggle("フォルダの中も並べる", isOn: $showsAllAlbums) - .toggleStyle(.checkbox) + .toggleStyle(AppToggleStyle(isCheckbox: true)) .lineLimit(1) .fixedSize() .disabled(!trimmedQuery.isEmpty) @@ -171,14 +171,14 @@ struct AlbumOverviewView: View { private var hideEmptyToggle: some View { Toggle("空のアルバムを隠す", isOn: $hidesEmpty) - .toggleStyle(.checkbox) + .toggleStyle(AppToggleStyle(isCheckbox: true)) .lineLimit(1) .fixedSize() .help("中身が0件のアルバムを一覧から外します.オフでも,空のアルバムは各区画の末尾にまとまります.") } private var orderMenu: some View { - Menu { + AppChoiceMenu { ForEach(Order.allCases) { option in Toggle(option.rawValue, isOn: Binding( get: { order == option }, diff --git a/ArkServer/Features/Library/Views/FolderDetailView.swift b/ArkServer/Features/Library/Views/FolderDetailView.swift index ad5326b..48e2da8 100644 --- a/ArkServer/Features/Library/Views/FolderDetailView.swift +++ b/ArkServer/Features/Library/Views/FolderDetailView.swift @@ -102,7 +102,7 @@ struct FolderDetailView: View { } } } - .alert("新規アルバムに移動", isPresented: $showMoveToNewAlbumAlert) { + .appAlert("新規アルバムに移動", isPresented: $showMoveToNewAlbumAlert) { TextField("アルバム名", text: $newAlbumNameForMove) Button("移動", action: moveToNewAlbum) Button("キャンセル", role: .cancel) { diff --git a/ArkServer/Features/Library/Views/LibraryCategoryView.swift b/ArkServer/Features/Library/Views/LibraryCategoryView.swift index 64e5428..671964c 100644 --- a/ArkServer/Features/Library/Views/LibraryCategoryView.swift +++ b/ArkServer/Features/Library/Views/LibraryCategoryView.swift @@ -245,7 +245,7 @@ struct LibraryCategoryView: View { // 複数選択時の再生方法は4種類あり,アイコンだけを並べると見分けにくいので1つのメニューにまとめる。 ToolbarItem(placement: .primaryAction) { if selectedItems.count >= 2 { - Menu { + AppChoiceMenu { Button { startMultiPlayback(selectedItems) } label: { @@ -308,7 +308,7 @@ struct LibraryCategoryView: View { } } } - .confirmationDialog("ゴミ箱を空にする方法を選んでください", isPresented: $showEmptyTrashAlert, titleVisibility: .visible) { + .appConfirmationPanel("ゴミ箱を空にする方法を選んでください", isPresented: $showEmptyTrashAlert, titleVisibility: .visible) { Button("完全に削除", role: .destructive) { dataManager.emptyTrash() } Button("実ファイルをMacのゴミ箱へ移動", role: .destructive) { dataManager.moveMediaFilesToSystemTrash( @@ -319,7 +319,7 @@ struct LibraryCategoryView: View { } message: { Text("完全に削除するとアプリ管理内のファイルは復元できません.Macのゴミ箱へ移動するとFinderから復元できます.") } - .confirmationDialog("再生履歴を消去しますか?", isPresented: $showClearHistoryAlert, titleVisibility: .visible) { + .appConfirmationPanel("再生履歴を消去しますか?", isPresented: $showClearHistoryAlert, titleVisibility: .visible) { Button("消去", role: .destructive) { watchState.clearHistory() selectedVideoIDs.removeAll() @@ -328,7 +328,7 @@ struct LibraryCategoryView: View { } message: { Text("動画そのものと「続きから」の視聴位置は消えません.ブラウザや iPhone の履歴からも消えます.") } - .alert("エクスポート完了", isPresented: $showExportResultAlert) { + .appAlert("エクスポート完了", isPresented: $showExportResultAlert) { Button("OK", role: .cancel) { } } message: { Text(exportResultMessage) @@ -353,7 +353,7 @@ struct LibraryCategoryView: View { } ) } - .alert("新規アルバムに移動", isPresented: $showMoveToNewAlbumAlert) { + .appAlert("新規アルバムに移動", isPresented: $showMoveToNewAlbumAlert) { TextField("アルバム名", text: $newAlbumNameForMove) Button("作成して追加") { let name = newAlbumNameForMove.trimmingCharacters(in: .whitespaces) @@ -377,7 +377,7 @@ struct LibraryCategoryView: View { .foregroundStyle(.secondary) .lineLimit(1) } - Stepper("分割数: \(splitCount)", value: $splitCount, in: 2...9) + AppNumberStepper("分割数: \(splitCount)", value: $splitCount, in: 2...9) .frame(width: 200) Text("動画を\(splitCount)等分して\(splitCount)画面で同時再生します") .font(.appCaption) @@ -392,7 +392,7 @@ struct LibraryCategoryView: View { } } .keyboardShortcut(.defaultAction) - .buttonStyle(.borderedProminent) + .buttonStyle(AppActionButtonStyle(isPrimary: true)) } } .padding(30) @@ -854,7 +854,7 @@ struct LibraryCategoryView: View { Text("「\(searchText)」に一致するタイトルは見つかりませんでした.") } actions: { Button("検索を解除") { searchText = "" } - .buttonStyle(.borderedProminent) + .buttonStyle(AppActionButtonStyle(isPrimary: true)) } .frame(maxWidth: .infinity, maxHeight: .infinity) } else { diff --git a/ArkServer/Features/Library/Views/MediaGridControlBar.swift b/ArkServer/Features/Library/Views/MediaGridControlBar.swift index 51ccc22..a644caa 100644 --- a/ArkServer/Features/Library/Views/MediaGridControlBar.swift +++ b/ArkServer/Features/Library/Views/MediaGridControlBar.swift @@ -56,7 +56,7 @@ struct MediaGridControlBar: View { Rectangle().fill(NeomorphicTheme.separator).frame(height: 0.5) } // メニューのグレーの枠は付けず、文字とアイコンだけの軽い見た目にする。 - .menuStyle(.borderlessButton) + } @ViewBuilder @@ -64,7 +64,7 @@ struct MediaGridControlBar: View { if showsSortControls { // 「短い順」の横に ↓ / ↑ だけのボタンを並べると,矢印が何を指すのか分からない. // 逆順はメニューの中のチェック項目にし,効いているときはラベルに「(逆順)」と出す. - Menu { + AppChoiceMenu { ForEach(SortOrder.allCases) { order in Toggle(order.rawValue, isOn: Binding( get: { appSettings.sortOrder == order }, @@ -91,7 +91,7 @@ struct MediaGridControlBar: View { private var thumbnailControls: some View { HStack(spacing: 6) { - Menu { + AppChoiceMenu { ForEach(ThumbnailOption.allCases) { option in Button(option.rawValue) { appSettings.thumbnailOption = option } } @@ -101,7 +101,7 @@ struct MediaGridControlBar: View { .fixedSize() if appSettings.thumbnailOption == .custom { HStack(spacing: 4) { - Stepper("サムネイルの秒数", value: $appSettings.customThumbnailTime, in: 0...3600, step: 1) + AppNumberStepper(value: $appSettings.customThumbnailTime, in: 0...3600, step: 1) { EmptyView() } .labelsHidden() TextField("秒", value: $appSettings.customThumbnailTime, formatter: Self.secondsFormatter) .frame(width: 46) @@ -114,7 +114,7 @@ struct MediaGridControlBar: View { } private var displayControls: some View { - Menu { + AppChoiceMenu { Toggle("タイトルを表示", isOn: $appSettings.showTitles) Toggle("インポート日を表示", isOn: $appSettings.showImportDates) } label: { diff --git a/ArkServer/Features/Library/Views/MediaGridItem.swift b/ArkServer/Features/Library/Views/MediaGridItem.swift index 0fc65e9..8784fd5 100644 --- a/ArkServer/Features/Library/Views/MediaGridItem.swift +++ b/ArkServer/Features/Library/Views/MediaGridItem.swift @@ -179,7 +179,7 @@ struct MediaGridItem: View { .onTapGesture(count: 1) { onSingleTap(NSApp.currentEvent?.modifierFlags ?? []) } - .contextMenu { + .appContextMenu { Button("開く") { onOpen() } if video.mediaType == .video, !isTrashView, let onAnalyzeScenes { Button("シーン抽出") { onAnalyzeScenes() } @@ -193,7 +193,7 @@ struct MediaGridItem: View { Button("完全に削除…", role: .destructive) { showDeleteConfirmation = true } } else { Button(video.isFavorite ? "お気に入りから外す" : "お気に入りに追加") { onToggleFavorite() } - Menu("アルバムに移動") { + AppChoiceMenu("アルバムに移動") { ForEach(moveTargetAlbums) { album in Button(album.name) { onMoveToAlbum(album.id) } } diff --git a/ArkServer/Features/MediaAnalysis/Views/SimilarMediaView.swift b/ArkServer/Features/MediaAnalysis/Views/SimilarMediaView.swift index ef4288e..88d1625 100644 --- a/ArkServer/Features/MediaAnalysis/Views/SimilarMediaView.swift +++ b/ArkServer/Features/MediaAnalysis/Views/SimilarMediaView.swift @@ -242,7 +242,7 @@ struct SimilarMediaView: View { } label: { Label("選択した\(model.selectedIDs.count)件を削除", systemImage: "trash") } - .buttonStyle(.borderedProminent) + .buttonStyle(AppActionButtonStyle(isPrimary: true)) .disabled(model.selectedIDs.isEmpty || model.isScanning) } } diff --git a/ArkServer/Features/MediaAnalysis/Views/SketchCleanupView.swift b/ArkServer/Features/MediaAnalysis/Views/SketchCleanupView.swift index 5b944bd..74adab0 100644 --- a/ArkServer/Features/MediaAnalysis/Views/SketchCleanupView.swift +++ b/ArkServer/Features/MediaAnalysis/Views/SketchCleanupView.swift @@ -174,7 +174,7 @@ struct SketchCleanupView: View { } label: { Label("選択した\(model.selectedIDs.count)件を削除", systemImage: "trash") } - .buttonStyle(.borderedProminent) + .buttonStyle(AppActionButtonStyle(isPrimary: true)) .disabled(model.selectedIDs.isEmpty || model.isScanning) } } diff --git a/ArkServer/Features/MediaAnalysis/Views/VariantVideoView.swift b/ArkServer/Features/MediaAnalysis/Views/VariantVideoView.swift index a2bc19c..0fa8ee0 100644 --- a/ArkServer/Features/MediaAnalysis/Views/VariantVideoView.swift +++ b/ArkServer/Features/MediaAnalysis/Views/VariantVideoView.swift @@ -93,7 +93,7 @@ struct VariantVideoView: View { .font(.appCaption) .foregroundStyle(.secondary) Spacer() - Picker( + AppChoicePicker( "探索方法", selection: Binding( get: { model.searchMode }, @@ -103,7 +103,7 @@ struct VariantVideoView: View { Text("通常差分").tag(VariantVideoViewModel.SearchMode.normal) Text("一部一致").tag(VariantVideoViewModel.SearchMode.partial) } - .pickerStyle(.segmented) + .tint(NeomorphicTheme.ink) .frame(width: 190) Button { @@ -226,7 +226,7 @@ struct VariantVideoView: View { ) .frame(maxWidth: .infinity) } - .buttonStyle(.borderedProminent) + .buttonStyle(AppActionButtonStyle(isPrimary: true)) .controlSize(.small) .disabled(!isPlayable) .help(isPlayable @@ -282,7 +282,7 @@ struct VariantVideoView: View { HStack(spacing: 10) { Text("最小尺差") .font(.appCaption) - Stepper( + AppNumberStepper( value: $model.minimumPartialDurationDifference, in: 1...120, step: 1 diff --git a/ArkServer/Features/MusicVideo/Views/MusicVideoCutEditorView.swift b/ArkServer/Features/MusicVideo/Views/MusicVideoCutEditorView.swift index d3aa6fb..f84d43c 100644 --- a/ArkServer/Features/MusicVideo/Views/MusicVideoCutEditorView.swift +++ b/ArkServer/Features/MusicVideo/Views/MusicVideoCutEditorView.swift @@ -81,11 +81,11 @@ struct MusicVideoCutEditorView: View { } private var moreMenu: some View { - Menu { + AppChoiceMenu { Button("この動画を使っているカットをすべて差し替え") { viewModel.replaceAllUsesOfSelectedVideo() } Button("この動画を外す(以後も使わない)") { viewModel.excludeSelectedVideo() } Divider() - Menu("指定の動画に差し替え") { + AppChoiceMenu("指定の動画に差し替え") { ForEach(viewModel.poolVideos) { video in Button(video.name) { viewModel.replaceSelectedCut(withVideo: video.id) } } @@ -93,7 +93,7 @@ struct MusicVideoCutEditorView: View { } label: { Text("その他") } - .menuStyle(.button) + .buttonStyle(.quiet) .menuIndicator(.visible) .fixedSize() diff --git a/ArkServer/Features/MusicVideo/Views/MusicVideoExportAlbumSheet.swift b/ArkServer/Features/MusicVideo/Views/MusicVideoExportAlbumSheet.swift index a5e8e05..b18347e 100644 --- a/ArkServer/Features/MusicVideo/Views/MusicVideoExportAlbumSheet.swift +++ b/ArkServer/Features/MusicVideo/Views/MusicVideoExportAlbumSheet.swift @@ -41,7 +41,7 @@ struct MusicVideoExportAlbumSheet: View { HStack(spacing: 12) { TextField("アルバム名で検索", text: $searchText) .textFieldStyle(.roundedBorder) - Picker("並べ替え", selection: $order) { + AppChoicePicker("並べ替え", selection: $order) { ForEach(Order.allCases) { Text($0.rawValue).tag($0) } } .frame(width: 210) @@ -177,7 +177,7 @@ struct MusicVideoExportAlbumSheet: View { .keyboardShortcut(.cancelAction) .accessibilityIdentifier("musicvideo.exportAlbum.cancel") Button("書き出して追加") { confirm() } - .buttonStyle(.borderedProminent) + .buttonStyle(AppActionButtonStyle(isPrimary: true)) .keyboardShortcut(.defaultAction) .disabled(destination == nil) .accessibilityIdentifier("musicvideo.exportAlbum.confirm") diff --git a/ArkServer/Features/MusicVideo/Views/MusicVideoMusicPickerView.swift b/ArkServer/Features/MusicVideo/Views/MusicVideoMusicPickerView.swift index 8ef9304..402c977 100644 --- a/ArkServer/Features/MusicVideo/Views/MusicVideoMusicPickerView.swift +++ b/ArkServer/Features/MusicVideo/Views/MusicVideoMusicPickerView.swift @@ -207,7 +207,7 @@ struct MusicVideoMusicPickerView: View { TextField("曲名で検索", text: $searchText) .textFieldStyle(.roundedBorder) .frame(minWidth: 160) - Picker("並べ替え", selection: $order) { + AppChoicePicker("並べ替え", selection: $order) { ForEach(MusicVideoMusicOrder.allCases) { Text($0.rawValue).tag($0) } } .labelsHidden() @@ -234,7 +234,7 @@ struct MusicVideoMusicPickerView: View { Text("曲を置いてあるフォルダを選んでください") .font(.appBody) Button("フォルダを選ぶ…", action: chooseFolder) - .buttonStyle(.borderedProminent) + .buttonStyle(AppActionButtonStyle(isPrimary: true)) } .foregroundStyle(NeomorphicTheme.muted) .frame(maxWidth: .infinity, maxHeight: .infinity) diff --git a/ArkServer/Features/MusicVideo/Views/MusicVideoSourcePickerView.swift b/ArkServer/Features/MusicVideo/Views/MusicVideoSourcePickerView.swift index da7ed42..6cd5a0a 100644 --- a/ArkServer/Features/MusicVideo/Views/MusicVideoSourcePickerView.swift +++ b/ArkServer/Features/MusicVideo/Views/MusicVideoSourcePickerView.swift @@ -104,7 +104,7 @@ struct MusicVideoSourcePickerView: View { VStack(spacing: 8) { searchField("アルバム名で検索", text: $albumSearch) HStack(spacing: 10) { - Picker("並べ替え", selection: $albumOrder) { + AppChoicePicker("並べ替え", selection: $albumOrder) { ForEach(MusicVideoAlbumOrder.allCases) { Text($0.rawValue).tag($0) } } .labelsHidden() @@ -113,13 +113,13 @@ struct MusicVideoSourcePickerView: View { .fixedSize() .help("動画が1本もないアルバムを一覧から隠します") Spacer(minLength: 0) - Menu { + AppChoiceMenu { Button("表示中のアルバムをすべて選ぶ") { viewModel.selectedAlbumIDs.formUnion(rows.map(\.id)) } Button("表示中のアルバムの選択を外す") { viewModel.selectedAlbumIDs.subtract(rows.map(\.id)) } } label: { Text("まとめて") } - .menuStyle(.button) + .buttonStyle(.quiet) .menuIndicator(.visible) .fixedSize() @@ -287,13 +287,13 @@ struct MusicVideoSourcePickerView: View { Button(isSelected ? "アルバムの選択を外す" : "このアルバムごと選ぶ") { toggleAlbum(id) } .buttonStyle(.quiet) } - Menu { + AppChoiceMenu { Button("表示中の動画をすべて選ぶ") { viewModel.selectedVideoIDs.formUnion(videos.map(\.id)) } Button("表示中の動画の選択を外す") { viewModel.selectedVideoIDs.subtract(videos.map(\.id)) } } label: { Text("まとめて") } - .menuStyle(.button) + .buttonStyle(.quiet) .menuIndicator(.visible) .fixedSize() @@ -351,7 +351,7 @@ struct MusicVideoSourcePickerView: View { } private var videoOrderPicker: some View { - Picker("並べ替え", selection: $videoOrder) { + AppChoicePicker("並べ替え", selection: $videoOrder) { ForEach(MusicVideoVideoOrder.allCases) { Text($0.rawValue).tag($0) } } .labelsHidden() @@ -359,7 +359,7 @@ struct MusicVideoSourcePickerView: View { } private var minimumLengthPicker: some View { - Picker("長さ", selection: $minimumLength) { + AppChoicePicker("長さ", selection: $minimumLength) { Text("すべての長さ").tag(1.0) Text("5秒以上").tag(5.0) Text("10秒以上").tag(10.0) @@ -462,7 +462,7 @@ struct MusicVideoSourcePickerView: View { Button("すべて解除") { viewModel.clearSourceSelection() } .disabled(viewModel.selectedAlbumIDs.isEmpty && viewModel.selectedVideoIDs.isEmpty && !viewModel.includeFavorites) Button("完了", action: close) - .buttonStyle(.borderedProminent) + .buttonStyle(AppActionButtonStyle(isPrimary: true)) .keyboardShortcut(.defaultAction) .accessibilityIdentifier("musicvideo.sourceDone") } diff --git a/ArkServer/Features/MusicVideo/Views/MusicVideoView.swift b/ArkServer/Features/MusicVideo/Views/MusicVideoView.swift index 5241393..d624252 100644 --- a/ArkServer/Features/MusicVideo/Views/MusicVideoView.swift +++ b/ArkServer/Features/MusicVideo/Views/MusicVideoView.swift @@ -79,7 +79,7 @@ struct MusicVideoView: View { viewModel.exportToLibrary(dataManager: dataManager, destination: destination) } } - .alert( + .appAlert( "処理に失敗しました", isPresented: Binding( get: { viewModel.errorMessage != nil }, @@ -90,7 +90,7 @@ struct MusicVideoView: View { } message: { Text(viewModel.errorMessage ?? "不明なエラーです.") } - .alert( + .appAlert( "書き出しが完了しました", isPresented: Binding( get: { viewModel.resultMessage != nil }, @@ -469,14 +469,14 @@ struct MusicVideoView: View { } private var recentMenu: some View { - Menu { + AppChoiceMenu { ForEach(viewModel.recentMusicURLs, id: \.self) { url in Button(url.deletingPathExtension().lastPathComponent) { viewModel.chooseMusic(url) } } } label: { Text("最近") } - .menuStyle(.button) + .buttonStyle(.quiet) .menuIndicator(.visible) .fixedSize() @@ -540,7 +540,7 @@ struct MusicVideoView: View { .fixedSize(horizontal: false, vertical: true) HStack(spacing: 8) { Toggle("お気に入りを含める", isOn: $viewModel.includeFavorites) - .toggleStyle(MusicVideoCheckStyle()) + .toggleStyle(AppToggleStyle(isCheckbox: true)) Spacer(minLength: 0) if !(viewModel.selectedAlbumIDs.isEmpty && viewModel.selectedVideoIDs.isEmpty) { Button("解除") { viewModel.clearSourceSelection() } @@ -626,16 +626,16 @@ struct MusicVideoView: View { HStack(spacing: 8) { if viewModel.isWorking { Button("中止") { viewModel.cancelWork() } - .buttonStyle(MusicVideoActionStyle()) + .buttonStyle(AppActionButtonStyle()) .accessibilityIdentifier("musicvideo.cancel") } else { if viewModel.plan != nil { Button("ファイルに保存…") { saveToFile() } - .buttonStyle(MusicVideoActionStyle()) + .buttonStyle(AppActionButtonStyle()) .disabled(!viewModel.canExport) .accessibilityIdentifier("musicvideo.saveFile") Button("ライブラリに追加…") { isShowingExportAlbumPicker = true } - .buttonStyle(MusicVideoActionStyle()) + .buttonStyle(AppActionButtonStyle()) .disabled(!viewModel.canExport) .help("追加するアルバムを選んで,書き出してライブラリに追加します") .accessibilityIdentifier("musicvideo.exportLibrary") @@ -643,7 +643,7 @@ struct MusicVideoView: View { Button(viewModel.plan == nil ? "映像を作る" : "作り直す") { viewModel.generate(dataManager: dataManager) } - .buttonStyle(MusicVideoActionStyle(isPrimary: true)) + .buttonStyle(AppActionButtonStyle(isPrimary: true)) .disabled(!viewModel.canGenerate) .help(viewModel.plan == nil ? "曲に合わせて映像を作ります" : "別のカット割りで作り直します") .accessibilityIdentifier("musicvideo.generate") diff --git a/ArkServer/Features/Navigation/Views/MainSidebarView.swift b/ArkServer/Features/Navigation/Views/MainSidebarView.swift index 24735a9..dee0c51 100644 --- a/ArkServer/Features/Navigation/Views/MainSidebarView.swift +++ b/ArkServer/Features/Navigation/Views/MainSidebarView.swift @@ -106,7 +106,7 @@ struct MainSidebarView: View { .background(GlassCardSurface()) } } - .alert("エクスポート完了", isPresented: $showSidebarExportResultAlert) { + .appAlert("エクスポート完了", isPresented: $showSidebarExportResultAlert) { Button("OK", role: .cancel) { } } message: { Text(sidebarExportResultMessage) @@ -114,7 +114,7 @@ struct MainSidebarView: View { .onDrop(of: [.fileURL], isTargeted: $isSidebarTargeted) { providers in handleDropOnSidebar(providers: providers) } - .alert("異なるメディアタイプの混在", isPresented: $showSidebarMixedContentAlert) { + .appAlert("異なるメディアタイプの混在", isPresented: $showSidebarMixedContentAlert) { Button("動画アルバムとして作成") { if let url = pendingSidebarFolderURL { Task { await dataManager.importFolder(folderURL: url, as: .video); pendingSidebarFolderURL = nil } @@ -361,7 +361,7 @@ struct MainSidebarView: View { .sheet(isPresented: $isShowingAddAlbumSheet) { addAlbumSheet } - .confirmationDialog( + .appConfirmationPanel( "アルバムの削除", isPresented: albumDeletionDialogBinding, titleVisibility: .visible, @@ -385,14 +385,14 @@ struct MainSidebarView: View { } message: { request in Text(deletionMessage(for: request)) } - .alert("新規フォルダを作成", isPresented: $isShowingCreateFolderFromSelectionAlert) { + .appAlert("新規フォルダを作成", isPresented: $isShowingCreateFolderFromSelectionAlert) { TextField("フォルダ名", text: $newFolderNameForSelection) Button("作成", action: createFolderFromSelection) Button("キャンセル", role: .cancel) { newFolderNameForSelection = "" } } message: { Text("選択した\(selectedAlbumIDs.count)件のアルバムをこのフォルダの中に移動します.") } - .alert("新規アルバムに取り込む", isPresented: $isShowingSidebarFileImportAlbumNameAlert) { + .appAlert("新規アルバムに取り込む", isPresented: $isShowingSidebarFileImportAlbumNameAlert) { TextField("アルバム名", text: $newAlbumNameForSidebarFileImport) Button("作成して取り込む", action: importSidebarDroppedFiles) Button("キャンセル", role: .cancel) { pendingSidebarFileURLs = []; newAlbumNameForSidebarFileImport = "" } @@ -591,7 +591,7 @@ struct MainSidebarView: View { } .buttonStyle(.plain) .draggable(AlbumDragPayload(albumIDs: [album.id], sourceFolderPath: nil)) - .contextMenu { + .appContextMenu { Button("フォルダにエクスポート…") { exportAlbums(albumIDs: [album.id]) } @@ -629,6 +629,25 @@ struct MainSidebarView: View { return AnyView( VStack(alignment: .leading, spacing: 2) { folderRowLabel(node, isPhotoTree: isPhotoTree) + .appContextMenu { + if let album = node.album, album.linkedFolderPath != nil || album.linkedFolderBookmarkData != nil { + Button("紐づけフォルダを更新") { + rescanLinkedFolder(albumID: album.id) + } + } else { + Button("フォルダを紐づけ…") { + linkFolderToNode(node, isPhotoTree: isPhotoTree) + } + } + Divider() + Button("フォルダにエクスポート…") { + exportAlbums(albumIDs: viewModel.albumIDs(in: node)) + } + Divider() + Button("削除", role: .destructive) { + requestAlbumDeletion(albumIDs: viewModel.albumIDs(in: node)) + } + } if expandedFolderIDs.contains(key) { VStack(alignment: .leading, spacing: 2) { @@ -643,25 +662,7 @@ struct MainSidebarView: View { .padding(.leading, 14) } } - .contextMenu { - if let album = node.album, album.linkedFolderPath != nil || album.linkedFolderBookmarkData != nil { - Button("紐づけフォルダを更新") { - rescanLinkedFolder(albumID: album.id) - } - } else { - Button("フォルダを紐づけ…") { - linkFolderToNode(node, isPhotoTree: isPhotoTree) - } - } - Divider() - Button("フォルダにエクスポート…") { - exportAlbums(albumIDs: viewModel.albumIDs(in: node)) - } - Divider() - Button("削除", role: .destructive) { - requestAlbumDeletion(albumIDs: viewModel.albumIDs(in: node)) - } - } + ) } } @@ -1020,7 +1021,7 @@ struct MainSidebarView: View { newAlbumName = "" newAlbumType = .video } - .buttonStyle(.borderedProminent) + .buttonStyle(AppActionButtonStyle(isPrimary: true)) .keyboardShortcut(.defaultAction) .disabled(newAlbumName.isEmpty || newAlbumName == LibraryViewModel.allVideosAlbumName || newAlbumName == LibraryViewModel.allPhotosAlbumName) } @@ -1032,7 +1033,7 @@ struct MainSidebarView: View { Label("フォルダをインポートして作成", systemImage: "folder.badge.plus") .frame(maxWidth: .infinity) } - .buttonStyle(.bordered) + .buttonStyle(AppActionButtonStyle()) .help("フォルダを選ぶと,そのフォルダ名でアルバムを作成し中身を一括インポートします") } .padding(24) diff --git a/ArkServer/Features/Playback/Views/PhotoViewerView.swift b/ArkServer/Features/Playback/Views/PhotoViewerView.swift index 6d5fddd..1ecccaf 100644 --- a/ArkServer/Features/Playback/Views/PhotoViewerView.swift +++ b/ArkServer/Features/Playback/Views/PhotoViewerView.swift @@ -130,7 +130,7 @@ struct PhotoViewerView: View { hideFilmstripTask?.cancel() } .onKeyPress(phases: .down, action: handleKeyPress) - .confirmationDialog( + .appConfirmationPanel( "削除方法を選んでください", isPresented: $showDeleteConfirmation, titleVisibility: .visible diff --git a/ArkServer/Features/Playback/Views/SlideshowPlayerView.swift b/ArkServer/Features/Playback/Views/SlideshowPlayerView.swift index 61f8761..aaa58f0 100644 --- a/ArkServer/Features/Playback/Views/SlideshowPlayerView.swift +++ b/ArkServer/Features/Playback/Views/SlideshowPlayerView.swift @@ -82,7 +82,7 @@ struct SlideshowPlayerView: View { .keyboardShortcut(.cancelAction) Button("開始") { startGeneration() } .keyboardShortcut(.defaultAction) - .buttonStyle(.borderedProminent) + .buttonStyle(AppActionButtonStyle(isPrimary: true)) } } .padding(40) diff --git a/ArkServer/Features/Playback/Views/VariantSwitchPlayerView.swift b/ArkServer/Features/Playback/Views/VariantSwitchPlayerView.swift index e4e9867..107cc98 100644 --- a/ArkServer/Features/Playback/Views/VariantSwitchPlayerView.swift +++ b/ArkServer/Features/Playback/Views/VariantSwitchPlayerView.swift @@ -201,7 +201,7 @@ struct VariantSwitchPlayerView: View { HStack { Button("閉じる") { close() } Button("再試行") { viewModel.retryContentAlignment() } - .buttonStyle(.borderedProminent) + .buttonStyle(AppActionButtonStyle(isPrimary: true)) } } .foregroundStyle(.white) @@ -378,7 +378,7 @@ struct VariantSwitchPlayerView: View { } label: { Label("削除", systemImage: "trash") } - .buttonStyle(.borderedProminent) + .buttonStyle(AppActionButtonStyle(isPrimary: true)) .controlSize(.small) .disabled(viewModel.markedForDeletionIDs.isEmpty) } @@ -468,7 +468,7 @@ struct VariantSwitchPlayerView: View { Toggle(isOn: $viewModel.isAutoSwitching) { Text("自動切り替え").font(.appCaption) } - .toggleStyle(.switch) + .toggleStyle(AppToggleStyle()) .controlSize(.mini) .help("一定間隔で差分を自動的に切り替える(\(keyLabel(.variantToggleAuto)))") @@ -498,7 +498,7 @@ struct VariantSwitchPlayerView: View { Toggle(isOn: $viewModel.avoidsImmediateRepeat) { Text("同じものを続けない").font(.appCaption) } - .toggleStyle(.checkbox) + .toggleStyle(AppToggleStyle(isCheckbox: true)) .controlSize(.mini) .help("切り替えたのに同じ差分が選ばれて「何も変わらない」のを防ぎます") } @@ -510,7 +510,7 @@ struct VariantSwitchPlayerView: View { Text("BGM音量を揃える") .font(.appCaption.weight(.semibold)) } - .toggleStyle(.switch) + .toggleStyle(AppToggleStyle()) .controlSize(.mini) .help("BGMだけを分離せず,動画内の音声全体をBGM音量の目安として比較します.大きい動画だけを減衰するため,音割れを防げます.") @@ -540,14 +540,14 @@ struct VariantSwitchPlayerView: View { Text("BGMの拍に合わせる") .font(.appCaption.weight(.semibold)) } - .toggleStyle(.switch) + .toggleStyle(AppToggleStyle()) .controlSize(.mini) .disabled(!viewModel.isAutoSwitching) .help("拍とは音楽の一定の脈,小節とは通常4拍をまとめた区切りです.BPMは1分間の拍数を表します.") if viewModel.synchronizesSwitchesToBeats { HStack(spacing: 4) { - Picker( + AppChoicePicker( "切り替え", selection: Binding( get: { viewModel.switchQuarterBeats }, @@ -567,7 +567,7 @@ struct VariantSwitchPlayerView: View { } } .labelsHidden() - .pickerStyle(.segmented) + .controlSize(.small) .fixedSize() @@ -605,7 +605,7 @@ struct VariantSwitchPlayerView: View { label: String, set: @escaping (Double) -> Void ) -> some View { - Stepper( + AppNumberStepper( onIncrement: { set( VariantSwitchSettings.adjustedInterval( diff --git a/ArkServer/Features/Playback/Views/VideoPlayerView.swift b/ArkServer/Features/Playback/Views/VideoPlayerView.swift index ccf0f92..6ed0f66 100644 --- a/ArkServer/Features/Playback/Views/VideoPlayerView.swift +++ b/ArkServer/Features/Playback/Views/VideoPlayerView.swift @@ -949,18 +949,18 @@ struct VideoPlayerView: View { /// 再生速度と自動再生。ボタンを並べるには数が多いのでメニューにまとめる。 private var playbackOptionsMenu: some View { - Menu { - Picker("再生速度", selection: rateBinding) { + AppChoiceMenu { + AppChoicePicker("再生速度", selection: rateBinding) { ForEach(PlaybackSettings.availableRates, id: \.self) { value in Text(PlaybackSettings.label(forRate: value)).tag(value) } } - .pickerStyle(.inline) + // トラックが1つしかない動画にまで選択 UI を出しても選ぶものがない。 if viewModel.audioTracks.count > 1 { Divider() - Picker("音声", selection: audioTrackBinding) { + AppChoicePicker("音声", selection: audioTrackBinding) { ForEach(viewModel.audioTracks) { track in Text(track.displayName).tag(track.index) } @@ -969,7 +969,7 @@ struct VideoPlayerView: View { if !viewModel.subtitleTracks.isEmpty { Divider() - Picker("字幕", selection: subtitleTrackBinding) { + AppChoicePicker("字幕", selection: subtitleTrackBinding) { ForEach(viewModel.subtitleTracks) { track in Text(track.displayName).tag(track.index) } @@ -992,7 +992,7 @@ struct VideoPlayerView: View { .padding(.horizontal, 6) .frame(height: 30) } - .menuStyle(.borderlessButton) + // メニューの文字がアクセントの青になるのを避け、他のボタンと同じ白にそろえる。 .tint(PlayerChrome.icon) .fixedSize() @@ -1250,58 +1250,352 @@ struct LibraryTourMenu: View { let videos: [VideoItem] let dataManager: LibraryViewModel let beforePlay: () -> Void + @State private var isPanelPresented = false + + var body: some View { + Button { isPanelPresented.toggle() } label: { + HStack(spacing: 8) { + Label("お楽しみ再生", systemImage: "play.rectangle.on.rectangle") + Image(systemName: "chevron.down") + .font(.system(size: 8, weight: .medium)) + } + } + .buttonStyle(.quiet) + .accessibilityIdentifier("library.tour.open") + .help("チャンネル・気分ミックス・時間指定・ストック・プレビュー巡回・シーン再生") + .disabled(videos.isEmpty) + .popover(isPresented: $isPanelPresented, arrowEdge: .bottom) { + LibraryTourSelectionPanel(videos: videos, dataManager: dataManager, beforePlay: beforePlay) { + isPanelPresented = false + } + } + } +} + +/// パネル内の移動は表示元のツールバーから独立させ,項目を開いてもパネルを保つ。 +private struct LibraryTourSelectionPanel: View { + let videos: [VideoItem] + let dataManager: LibraryViewModel + let beforePlay: () -> Void + let close: () -> Void @EnvironmentObject private var watchState: WatchStateStore @EnvironmentObject private var coordinator: PlaybackCoordinator @State private var errorMessage: String? + @State private var panelPage: PanelPage = .overview + @FocusState private var focusedOption: Int? + + private enum PanelPage { + case overview + case mood + case duration + } + + private static let durationChoices = [5, 10, 15, 30] + private static let secondsPerMinute = 60 + private static let panelWidth: CGFloat = 360 + + private var optionCount: Int { + switch panelPage { + case .overview: return 7 + case .mood: return PlaybackTourSession.Mood.allCases.count + case .duration: return Self.durationChoices.count + } + } + + private var panelTitle: String { + switch panelPage { + case .overview: return "お楽しみ再生" + case .mood: return "気分でミックス" + case .duration: return "時間ぴったり再生" + } + } + + private var panelSubtitle: String { + switch panelPage { + case .overview: return "いつもの動画を,違う楽しみ方で" + case .mood: return "表示中の動画から,気分に合うものを" + case .duration: return "動画の再生時間の合計を合わせます" + } + } + + private var panelHeight: CGFloat { + switch panelPage { + case .overview: return 548 + case .mood: return 316 + case .duration: return 328 + } + } var body: some View { - Menu { - Section("新しい楽しみ方") { - Button("マイチャンネル(全動画アルバム)") { - start { try PlaybackTourSession.channelSession(albums: dataManager.albums, videos: dataManager.videos) } - } - Menu("気分でミックス") { - ForEach(PlaybackTourSession.Mood.allCases, id: \.rawValue) { mood in - Button(mood.rawValue) { - start { - try PlaybackTourSession.mix(videos: videos, mood: mood, - seenIDs: Set(watchState.historyOrder).union(watchState.progress.keys)) - } - } - } - } - Menu("時間ぴったり再生") { - ForEach([5, 10, 15, 30], id: \.self) { minutes in - Button("\(minutes)分") { - start { try PlaybackTourSession.timed(videos: videos, seconds: Double(minutes * 60)) } - } + VStack(spacing: 0) { + panelHeader + Divider().overlay(NeomorphicTheme.separator) + ScrollView { + VStack(alignment: .leading, spacing: 16) { + switch panelPage { + case .overview: overviewOptions + case .mood: moodOptions + case .duration: durationOptions } } - Button("ストックした場面を再生") { - start { try PlaybackTourSession.highlights(videos: videos, urlForVideo: dataManager.fileURL) } - } + .padding(12) } - Section("プレビュー巡回") { - Button("15秒ずつ試聴") { startPreview(seconds: 15) } - Button("30秒ずつ試聴") { startPreview(seconds: 30) } + .scrollBounceBehavior(.basedOnSize) + Divider().overlay(NeomorphicTheme.separator) + HStack(spacing: 4) { + Text("↑↓ 選択") + Text("·") + Text("Enter 決定") + Text("·") + Text("Esc 閉じる") + Spacer(minLength: 0) } - Section("採用した区間を楽しむ") { - Button("シーンシャッフル") { - start { try PlaybackTourSession.scenes(videos: videos, urlForVideo: dataManager.fileURL) } - } - } - } label: { - Label("お楽しみ再生", systemImage: "play.rectangle.on.rectangle") + .font(.appMicro) + .foregroundStyle(NeomorphicTheme.muted) + .padding(.horizontal, 16) + .padding(.vertical, 8) } - .help("チャンネル・気分ミックス・時間指定・ストック・プレビュー巡回・シーン再生") - .disabled(videos.isEmpty) - .alert("再生を開始できません", isPresented: Binding( + .frame(width: Self.panelWidth, height: panelHeight) + .background(NeomorphicTheme.canvas) + .foregroundStyle(NeomorphicTheme.ink) + .tint(NeomorphicTheme.accent) + .environment(\.colorScheme, NeomorphicTheme.isDarkBase ? .dark : .light) + .background(LibraryTourPanelFocusBridge { focusedOption = 0 }) + .onKeyPress(.downArrow) { moveFocus(by: 1) } + .onKeyPress(.upArrow) { moveFocus(by: -1) } + .onKeyPress(.return) { + guard let focusedOption else { return .ignored } + activateOption(focusedOption) + return .handled + } + .onKeyPress(.leftArrow) { + guard panelPage != .overview else { return .ignored } + returnToOverview() + return .handled + } + .onKeyPress(.escape) { + close() + return .handled + } + .appAlert("再生を開始できません", isPresented: Binding( get: { errorMessage != nil }, set: { if !$0 { errorMessage = nil } } )) { Button("閉じる", role: .cancel) { errorMessage = nil } } message: { Text(errorMessage ?? "") } } + private var panelHeader: some View { + HStack(spacing: 12) { + if panelPage != .overview { + Button(action: returnToOverview) { + Image(systemName: "chevron.left") + .font(.system(size: 12, weight: .medium)) + .frame(width: 28, height: 28) + .background(NeomorphicTheme.control, in: RoundedRectangle(cornerRadius: 6)) + } + .buttonStyle(.plain) + .help("再生方法の一覧へ戻る") + .accessibilityLabel("再生方法の一覧へ戻る") + .accessibilityIdentifier("library.tour.back") + } + VStack(alignment: .leading, spacing: 4) { + Text(panelTitle) + .font(.appBodyStrong) + .accessibilityAddTraits(.isHeader) + Text(panelSubtitle) + .font(.appMicro) + .foregroundStyle(NeomorphicTheme.muted) + } + Spacer(minLength: 0) + Button(action: close) { + Image(systemName: "xmark") + .font(.system(size: 10, weight: .medium)) + .frame(width: 24, height: 24) + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + .foregroundStyle(NeomorphicTheme.muted) + .help("閉じる") + .accessibilityLabel("お楽しみ再生の選択を閉じる") + } + .padding(16) + } + + private var overviewOptions: some View { + Group { + optionGroup("新しい楽しみ方") { + optionRow(0, title: "マイチャンネル", detail: "全動画アルバムをチャンネルに", symbol: "tv") + optionRow(1, title: "気分でミックス", detail: "短く・未視聴・お気に入りから選ぶ", symbol: "shuffle", opensPage: true) + optionRow(2, title: "時間ぴったり再生", detail: "5・10・15・30分から選ぶ", symbol: "timer", opensPage: true) + optionRow(3, title: "ストックした場面を再生", detail: "保存しておいた場面を見返す", symbol: "bookmark") + } + optionGroup("プレビュー巡回") { + HStack(spacing: 8) { + durationTile(4, value: "15", unit: "秒", detail: "ずつ試聴") + durationTile(5, value: "30", unit: "秒", detail: "ずつ試聴") + } + } + optionGroup("採用した区間を楽しむ") { + optionRow(6, title: "シーンシャッフル", detail: "シーン抽出で採用した区間を再生", symbol: "film.stack") + } + } + } + + private var moodOptions: some View { + VStack(spacing: 4) { + ForEach(Array(PlaybackTourSession.Mood.allCases.enumerated()), id: \.offset) { index, mood in + optionRow(index, title: mood.rawValue, detail: moodDetail(mood), symbol: moodSymbol(mood)) + } + } + } + + private var durationOptions: some View { + VStack(alignment: .leading, spacing: 16) { + LazyVGrid(columns: [GridItem(.flexible()), GridItem(.flexible())], spacing: 8) { + ForEach(Array(Self.durationChoices.enumerated()), id: \.offset) { index, minutes in + durationTile(index, value: String(minutes), unit: "分", detail: "再生する") + } + } + Text("最後の区間の長さを調整して,選んだ時間に合わせます") + .font(.appCaption) + .foregroundStyle(NeomorphicTheme.muted) + } + } + + private func optionGroup(_ title: String, @ViewBuilder content: () -> Content) -> some View { + VStack(alignment: .leading, spacing: 8) { + Text(title) + .font(.appMicroStrong) + .foregroundStyle(NeomorphicTheme.muted) + .padding(.horizontal, 8) + .accessibilityAddTraits(.isHeader) + VStack(spacing: 4, content: content) + } + } + + private func optionRow(_ index: Int, title: String, detail: String, symbol: String, opensPage: Bool = false) -> some View { + Button { activateOption(index) } label: { + HStack(spacing: 12) { + Image(systemName: symbol) + .font(.system(size: 16, weight: .regular)) + .foregroundStyle(NeomorphicTheme.muted) + .frame(width: 24) + VStack(alignment: .leading, spacing: 4) { + Text(title) + .font(.appCaptionStrong) + .foregroundStyle(NeomorphicTheme.ink) + Text(detail) + .font(.appMicro) + .foregroundStyle(NeomorphicTheme.muted) + .lineLimit(1) + } + Spacer(minLength: 0) + Image(systemName: opensPage ? "chevron.right" : "play.fill") + .font(.system(size: opensPage ? 10 : 8, weight: .medium)) + .foregroundStyle(NeomorphicTheme.muted) + .frame(width: 12) + } + .frame(maxWidth: .infinity, alignment: .leading) + } + .buttonStyle(LibraryTourOptionStyle(isFocused: focusedOption == index)) + .focusable() + .focused($focusedOption, equals: index) + .onHover { inside in + if inside { focusedOption = index } + } + .accessibilityLabel(title) + .accessibilityHint(detail) + .accessibilityIdentifier("library.tour.\(panelPage).\(index)") + } + + private func durationTile(_ index: Int, value: String, unit: String, detail: String) -> some View { + Button { activateOption(index) } label: { + HStack(alignment: .firstTextBaseline, spacing: 4) { + Text(value) + .font(.system(size: 24, weight: .medium, design: .monospaced)) + Text(unit) + .font(.appCaption) + Spacer(minLength: 0) + Text(detail) + .font(.appMicro) + .foregroundStyle(NeomorphicTheme.muted) + } + .foregroundStyle(NeomorphicTheme.ink) + .frame(maxWidth: .infinity, minHeight: 40) + } + .buttonStyle(LibraryTourOptionStyle(isFocused: focusedOption == index, isTile: true)) + .focusable() + .focused($focusedOption, equals: index) + .onHover { inside in + if inside { focusedOption = index } + } + .accessibilityLabel("\(value)\(unit)\(detail)") + .accessibilityIdentifier("library.tour.\(panelPage).\(index)") + } + + private func moodDetail(_ mood: PlaybackTourSession.Mood) -> String { + switch mood { + case .short: return "3分以内の動画を30秒ずつ" + case .unseen: return "まだ見ていない動画を60秒ずつ" + case .favorites: return "お気に入りの動画を60秒ずつ" + } + } + + private func moodSymbol(_ mood: PlaybackTourSession.Mood) -> String { + switch mood { + case .short: return "bolt" + case .unseen: return "eye" + case .favorites: return "heart" + } + } + + private func moveFocus(by offset: Int) -> KeyPress.Result { + let current = focusedOption ?? (offset > 0 ? -1 : 0) + focusedOption = (current + offset + optionCount) % optionCount + return .handled + } + + private func returnToOverview() { + let previous = panelPage + panelPage = .overview + focusedOption = previous == .mood ? 1 : 2 + } + + /// 画面上の選択肢を,従来と同じ再生処理へ渡す。 + private func activateOption(_ index: Int) { + switch panelPage { + case .overview: + switch index { + case 0: + start { try PlaybackTourSession.channelSession(albums: dataManager.albums, videos: dataManager.videos) } + case 1: + panelPage = .mood + focusedOption = 0 + case 2: + panelPage = .duration + focusedOption = 0 + case 3: + start { try PlaybackTourSession.highlights(videos: videos, urlForVideo: dataManager.fileURL) } + case 4: startPreview(seconds: 15) + case 5: startPreview(seconds: 30) + case 6: + start { try PlaybackTourSession.scenes(videos: videos, urlForVideo: dataManager.fileURL) } + default: break + } + case .mood: + let moods = PlaybackTourSession.Mood.allCases + guard moods.indices.contains(index) else { return } + start { + try PlaybackTourSession.mix(videos: videos, mood: moods[index], + seenIDs: Set(watchState.historyOrder).union(watchState.progress.keys)) + } + case .duration: + guard Self.durationChoices.indices.contains(index) else { return } + let minutes = Self.durationChoices[index] + start { try PlaybackTourSession.timed(videos: videos, seconds: Double(minutes * Self.secondsPerMinute)) } + } + } + private func startPreview(seconds: Double) { start { try PlaybackTourSession.preview(videos: videos, seconds: seconds) } } @@ -1309,6 +1603,7 @@ struct LibraryTourMenu: View { private func start(_ makeSession: () throws -> PlaybackTourSession) { do { let session = try makeSession() + close() beforePlay() coordinator.startTour(session) } catch { @@ -1317,6 +1612,73 @@ struct LibraryTourMenu: View { } } +/// ツールバーのボタンではなく,表示したパネルへキー入力を渡す。 +private struct LibraryTourPanelFocusBridge: NSViewRepresentable { + let onReady: () -> Void + + func makeNSView(context: Context) -> FocusView { + FocusView(onReady: onReady) + } + + func updateNSView(_ view: FocusView, context: Context) { + view.onReady = onReady + } + + final class FocusView: NSView { + var onReady: () -> Void + + init(onReady: @escaping () -> Void) { + self.onReady = onReady + super.init(frame: .zero) + } + + required init?(coder: NSCoder) { return nil } + + override func viewDidMoveToWindow() { + super.viewDidMoveToWindow() + guard let window else { return } + // ホストのウィンドウが用意されてから,SwiftUIのフォーカスを設定する。 + DispatchQueue.main.async { [weak self, weak window] in + guard let self, let window else { return } + window.makeKey() + self.onReady() + } + } + } +} + +/// 選択行のホバーとキーボードのフォーカスを同じ面と青線で示す。 +private struct LibraryTourOptionStyle: ButtonStyle { + let isFocused: Bool + var isTile = false + @State private var isHovering = false + + func makeBody(configuration: Configuration) -> some View { + let isActive = isFocused || isHovering || configuration.isPressed + return configuration.label + .padding(.horizontal, 12) + .padding(.vertical, 8) + .background( + RoundedRectangle(cornerRadius: 8) + .fill(isActive ? NeomorphicTheme.controlSelected : (isTile ? NeomorphicTheme.control : .clear)) + ) + .overlay { + RoundedRectangle(cornerRadius: 8) + .strokeBorder(isActive || isTile ? NeomorphicTheme.cardBorder : .clear, lineWidth: 1) + } + .overlay(alignment: .leading) { + if isActive { + RoundedRectangle(cornerRadius: 1) + .fill(NeomorphicTheme.accent) + .frame(width: 2, height: 16) + .padding(.leading, 2) + } + } + .contentShape(RoundedRectangle(cornerRadius: 8)) + .onHover { isHovering = $0 } + } +} + // MARK: - 履歴を更新せずに区間を試す専用プレイヤー struct PlaybackTourView: View { @@ -1404,7 +1766,7 @@ struct PlaybackTourView: View { .frame(width: 90) .accessibilityLabel("音量") Button("このまま見る", systemImage: "play.rectangle") { continueWatching() } - .buttonStyle(.borderedProminent) + .buttonStyle(AppActionButtonStyle(isPrimary: true)) .keyboardShortcut(.return, modifiers: []) .disabled(model.isLoading || model.errorMessage != nil || model.isFinished) } @@ -1428,7 +1790,7 @@ struct PlaybackTourView: View { .foregroundStyle(.white) .background(Color.black) .tint(NeomorphicTheme.accent) - .buttonStyle(.bordered) + .buttonStyle(AppActionButtonStyle()) .preferredColorScheme(.dark) .onAppear { coordinator.setPlaybackActive(false) @@ -1482,7 +1844,7 @@ struct StockMomentButton: View { .popover(isPresented: Binding(get: { notice != nil }, set: { if !$0 { notice = nil } })) { Text(notice ?? "").font(.appBody).padding(16).frame(width: 300) } - .alert("保存できません", isPresented: Binding( + .appAlert("保存できません", isPresented: Binding( get: { errorMessage != nil }, set: { if !$0 { errorMessage = nil } } )) { Button("閉じる", role: .cancel) { errorMessage = nil } diff --git a/ArkServer/Features/SceneExtraction/Views/CandidateListView.swift b/ArkServer/Features/SceneExtraction/Views/CandidateListView.swift index 159b11d..fbf34e9 100644 --- a/ArkServer/Features/SceneExtraction/Views/CandidateListView.swift +++ b/ArkServer/Features/SceneExtraction/Views/CandidateListView.swift @@ -224,7 +224,7 @@ struct CandidateListView: View { .padding(.vertical, 5) } // 塗りつぶさず、色は文字と薄い面だけにする(3色の塗りが並ぶと、判定ボタンが画面で一番目立ってしまう)。 - .buttonStyle(.bordered) + .buttonStyle(AppActionButtonStyle()) .tint(labelColor(label)) } diff --git a/ArkServer/Features/SceneExtraction/Views/SceneExtractionTutorialView.swift b/ArkServer/Features/SceneExtraction/Views/SceneExtractionTutorialView.swift index 8ed2e82..5d3be30 100644 --- a/ArkServer/Features/SceneExtraction/Views/SceneExtractionTutorialView.swift +++ b/ArkServer/Features/SceneExtraction/Views/SceneExtractionTutorialView.swift @@ -368,7 +368,7 @@ struct SceneExtractionTutorialView: View { TextField("用語を検索", text: $searchText) .textFieldStyle(.roundedBorder) - Picker("カテゴリ", selection: $selectedCategory) { + AppChoicePicker("カテゴリ", selection: $selectedCategory) { ForEach(SceneExtractionGlossaryCategory.allCases) { category in Text(category.rawValue).tag(category) } diff --git a/ArkServer/Features/SceneExtraction/Views/SceneExtractionView.swift b/ArkServer/Features/SceneExtraction/Views/SceneExtractionView.swift index b2b0a8a..77fb6b1 100644 --- a/ArkServer/Features/SceneExtraction/Views/SceneExtractionView.swift +++ b/ArkServer/Features/SceneExtraction/Views/SceneExtractionView.swift @@ -70,7 +70,7 @@ struct SceneExtractionView: View { ) { SceneExtractionTutorialView() } - .alert( + .appAlert( "処理に失敗しました", isPresented: Binding( get: { viewModel.errorMessage != nil }, @@ -83,7 +83,7 @@ struct SceneExtractionView: View { } message: { Text(viewModel.errorMessage ?? "不明なエラーです.") } - .alert( + .appAlert( "処理が完了しました", isPresented: Binding( get: { viewModel.lastOperationMessage != nil }, @@ -166,13 +166,13 @@ struct SceneExtractionView: View { Label("候補を解析", systemImage: "waveform.path.ecg") } // この画面の主役の操作なので、ここだけ青の塗りにする。 - .buttonStyle(.borderedProminent) + .buttonStyle(AppActionButtonStyle(isPrimary: true)) .tint(NeomorphicTheme.accent) .disabled(viewModel.videoDocument == nil || viewModel.isLoadingVideo) } Toggle("GTラベル付与モード", isOn: $viewModel.isGroundTruthModeEnabled) - .toggleStyle(.switch) + .toggleStyle(AppToggleStyle()) Button { viewModel.addGroundTruthAtCurrentTime() diff --git a/ArkServer/Features/Settings/Views/SettingsPageView.swift b/ArkServer/Features/Settings/Views/SettingsPageView.swift index b889307..dfc5795 100644 --- a/ArkServer/Features/Settings/Views/SettingsPageView.swift +++ b/ArkServer/Features/Settings/Views/SettingsPageView.swift @@ -167,7 +167,7 @@ struct SettingsPageView: View { SettingsSwitch(title: "インポート時にファイルをアプリ内へコピー", isOn: $dataManager.importCopiesFiles) } SettingsRow(title: "ゴミ箱の自動削除", detail: "ゴミ箱に入れてから指定日数が経過した項目を,起動時に完全削除します.") { - Picker("ゴミ箱の自動削除", selection: $dataManager.trashAutoDeleteDays) { + AppChoicePicker("ゴミ箱の自動削除", selection: $dataManager.trashAutoDeleteDays) { Text("しない").tag(0) Text("30日後").tag(30) Text("90日後").tag(90) @@ -209,7 +209,7 @@ struct SettingsPageView: View { title: "アップロード上限", detail: "受信中のファイルは丸ごとメモリに読み込まれるため,搭載メモリ(\(Self.physicalMemoryGB) GB)の半分までしか選べません." ) { - Picker("アップロード上限", selection: $webServerManager.maxUploadGB) { + AppChoicePicker("アップロード上限", selection: $webServerManager.maxUploadGB) { ForEach(ServerViewModel.uploadLimitOptionsGB, id: \.self) { gb in Text("\(gb) GB").tag(gb) } @@ -227,7 +227,7 @@ struct SettingsPageView: View { SettingsSection(title: "処理の負荷") { SettingsGroup { SettingsRow(title: "自動重複チェックの間隔") { - Picker("自動重複チェックの間隔", selection: $dataManager.duplicateCheckIntervalSeconds) { + AppChoicePicker("自動重複チェックの間隔", selection: $dataManager.duplicateCheckIntervalSeconds) { Text("30秒").tag(30) Text("1分").tag(60) Text("5分").tag(300) @@ -237,7 +237,7 @@ struct SettingsPageView: View { .fixedSize() } SettingsRow(title: "インポートの並列数") { - Picker("インポートの並列数", selection: $dataManager.importConcurrency) { + AppChoicePicker("インポートの並列数", selection: $dataManager.importConcurrency) { Text("2(省電力)").tag(2) Text("4(標準)").tag(4) Text("8(高速)").tag(8) @@ -246,7 +246,7 @@ struct SettingsPageView: View { .fixedSize() } SettingsRow(title: "サムネイルのメモリキャッシュ上限") { - Picker("サムネイルのメモリキャッシュ上限", selection: $thumbnailMemoryCacheLimit) { + AppChoicePicker("サムネイルのメモリキャッシュ上限", selection: $thumbnailMemoryCacheLimit) { Text("200枚(省メモリ)").tag(200) Text("600枚(標準)").tag(600) Text("1200枚(大量表示向け)").tag(1200) diff --git a/ArkServer/Features/Storage/Views/StorageManagerView.swift b/ArkServer/Features/Storage/Views/StorageManagerView.swift index d142100..ba77242 100644 --- a/ArkServer/Features/Storage/Views/StorageManagerView.swift +++ b/ArkServer/Features/Storage/Views/StorageManagerView.swift @@ -101,7 +101,7 @@ struct StorageManagerView: View { .frame(width: 540, height: 660) .appSheet() .onAppear(perform: viewModel.refreshUsage) - .alert("クリーンアップ完了", isPresented: $viewModel.isShowingResultAlert) { + .appAlert("クリーンアップ完了", isPresented: $viewModel.isShowingResultAlert) { Button("OK", role: .cancel) { } } message: { Text(viewModel.resultMessage) From 1c67d6f9ce2962f37bf5a52a9d37f366f30c8ba4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8E=9F=E3=80=80=E9=A2=AF=E7=99=BB?= Date: Fri, 6 Nov 2026 01:54:03 +0900 Subject: [PATCH 2/7] =?UTF-8?q?feat(audio):=20=E9=9F=B3=E5=A3=B0=E3=81=AE?= =?UTF-8?q?=E5=80=8D=E9=9F=B3=E9=99=A4=E5=8E=BB=E3=83=BB=E6=88=90=E5=88=86?= =?UTF-8?q?=E5=88=86=E9=9B=A2=E3=81=A8=E5=8C=BA=E9=96=93=E6=A4=9C=E5=87=BA?= =?UTF-8?q?=E3=82=92=E8=A1=8C=E3=81=86VoiceSeparationKit=E3=83=91=E3=83=83?= =?UTF-8?q?=E3=82=B1=E3=83=BC=E3=82=B8=E3=82=92=E8=BF=BD=E5=8A=A0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Packages/VoiceSeparationKit/Package.swift | 24 +++ Packages/VoiceSeparationKit/README.md | 158 ++++++++++++++ .../Sources/VoiceSeparation/AudioSignal.swift | 57 +++++ .../Sources/VoiceSeparation/FFT.swift | 98 +++++++++ .../VoiceSeparation/HarmonicRemover.swift | 196 +++++++++++++++++ .../MusicEffectsSplitter.swift | 120 +++++++++++ .../VoiceSeparation/PitchTracker.swift | 184 ++++++++++++++++ .../Sources/VoiceSeparation/STFT.swift | 107 ++++++++++ .../VoiceSeparation/SoundComponents.swift | 52 +++++ .../VoiceSeparationConfiguration.swift | 47 ++++ .../VoiceSeparation/VoiceSeparator.swift | 121 +++++++++++ .../SpeechActivityDetector.swift | 201 ++++++++++++++++++ .../SoundComponentsTests.swift | 93 ++++++++ .../SpeechActivityDetectorTests.swift | 71 +++++++ .../VoiceSeparationTests/TestSignals.swift | 108 ++++++++++ .../VoiceSeparatorTests.swift | 170 +++++++++++++++ 16 files changed, 1807 insertions(+) create mode 100644 Packages/VoiceSeparationKit/Package.swift create mode 100644 Packages/VoiceSeparationKit/README.md create mode 100644 Packages/VoiceSeparationKit/Sources/VoiceSeparation/AudioSignal.swift create mode 100644 Packages/VoiceSeparationKit/Sources/VoiceSeparation/FFT.swift create mode 100644 Packages/VoiceSeparationKit/Sources/VoiceSeparation/HarmonicRemover.swift create mode 100644 Packages/VoiceSeparationKit/Sources/VoiceSeparation/MusicEffectsSplitter.swift create mode 100644 Packages/VoiceSeparationKit/Sources/VoiceSeparation/PitchTracker.swift create mode 100644 Packages/VoiceSeparationKit/Sources/VoiceSeparation/STFT.swift create mode 100644 Packages/VoiceSeparationKit/Sources/VoiceSeparation/SoundComponents.swift create mode 100644 Packages/VoiceSeparationKit/Sources/VoiceSeparation/VoiceSeparationConfiguration.swift create mode 100644 Packages/VoiceSeparationKit/Sources/VoiceSeparation/VoiceSeparator.swift create mode 100644 Packages/VoiceSeparationKit/Sources/VoiceSeparationSoundAnalysis/SpeechActivityDetector.swift create mode 100644 Packages/VoiceSeparationKit/Tests/VoiceSeparationTests/SoundComponentsTests.swift create mode 100644 Packages/VoiceSeparationKit/Tests/VoiceSeparationTests/SpeechActivityDetectorTests.swift create mode 100644 Packages/VoiceSeparationKit/Tests/VoiceSeparationTests/TestSignals.swift create mode 100644 Packages/VoiceSeparationKit/Tests/VoiceSeparationTests/VoiceSeparatorTests.swift diff --git a/Packages/VoiceSeparationKit/Package.swift b/Packages/VoiceSeparationKit/Package.swift new file mode 100644 index 0000000..8b5ffb0 --- /dev/null +++ b/Packages/VoiceSeparationKit/Package.swift @@ -0,0 +1,24 @@ +// swift-tools-version:5.9 +import PackageDescription + +let package = Package( + name: "VoiceSeparationKit", + platforms: [ + .iOS(.v16), + .macOS(.v13), + ], + products: [ + // 人の声と、それ以外の音(効果音・環境音)を分ける。信号処理だけで動き、外部依存はない。 + .library(name: "VoiceSeparation", targets: ["VoiceSeparation"]), + // 「いつ声があるか」を Apple 標準の音分類(SoundAnalysis)で調べ、分離の手がかりにする。 + .library(name: "VoiceSeparationSoundAnalysis", targets: ["VoiceSeparationSoundAnalysis"]), + ], + targets: [ + .target(name: "VoiceSeparation"), + .target(name: "VoiceSeparationSoundAnalysis", dependencies: ["VoiceSeparation"]), + .testTarget( + name: "VoiceSeparationTests", + dependencies: ["VoiceSeparation", "VoiceSeparationSoundAnalysis"] + ), + ] +) diff --git a/Packages/VoiceSeparationKit/README.md b/Packages/VoiceSeparationKit/README.md new file mode 100644 index 0000000..7e7e871 --- /dev/null +++ b/Packages/VoiceSeparationKit/README.md @@ -0,0 +1,158 @@ +# VoiceSeparationKit + +音声から**人の声**と**それ以外(効果音・環境音など)**を分ける Swift パッケージ。 +学習済みモデルを使わず、信号処理(STFT・声の高さの追跡・倍音の除去)だけで動く。外部依存はない。 + +> **English summary** — A dependency-free Swift package that splits audio into "human voice" and "everything else +> (sound effects, ambience)". It tracks the fundamental frequency of speech and removes its harmonics from the +> spectrogram; no machine-learning model is bundled. An optional companion target asks Apple's SoundAnalysis +> *when* speech is present so that sound effects outside speech are left untouched. It is **not** a +> neural-network separator: see "できないこと" for the honest limits. + +## 何ができて、何ができないか + +| できること | できないこと | +|---|---| +| 母音・有声子音(声帯が震える音)の除去。合成の話し声で 95〜99%(−13〜−19 dB)のエネルギーが消える | 息の音・「s」「f」のような無声子音の完全な除去(弱めるだけ) | +| 声が無い区間の効果音を壊さない(`VoiceActivity` を与えたとき、ほぼ無傷) | 声と**同じ周波数で同時に**鳴る音(笛・電子音・楽器)の保護。声の倍音と重なる所は一緒に削れる | +| 声と同時に鳴る雑音・衝撃音をなるべく残す(谷の高さまでしか削らない) | 複数人が同時に話す声の分離(いちばん目立つ 1 人の高さを追う) | +| ステレオの左右の違いを保つ | 歌声の分離・楽曲のステム分離(Demucs などの学習型の領域) | +| 声以外を「音楽」と「効果音」に分ける API(`separateComponents`)を持つ | **音楽と効果音を、実用になる精度で見分けること**(下の「音楽と効果音」参照) | + +**学習型の分離器(Demucs・Spleeter など)ほどは分けられない。** 声の除去量は声によって違う(下の測定を参照)。 +音楽用の分離器が欲しいなら、それらを使うこと。 + +## 使い方 + +```swift +import VoiceSeparation + +let signal = AudioSignal(sampleRate: 44_100, channels: [left, right]) // [Float] の配列 +let result = VoiceSeparator().separate(signal) + +result.background // 声を取り除いた音(効果音・環境音) +result.voice // 取り除いた声。voice + background は入力に一致する +result.pitch // 声の高さの流れ(診断用) +``` + +声がどこにあるかが分かっているなら、`VoiceActivity` で教えると、声が無い所を壊さない。 +Apple 標準の音分類(SoundAnalysis)で調べるのが `VoiceSeparationSoundAnalysis`: + +```swift +import VoiceSeparation +import VoiceSeparationSoundAnalysis + +let activity = try SpeechActivityDetector().detect(signal) // 端末の中だけで動く +let result = VoiceSeparator().separate(signal, voiceActivity: activity) +``` + +**声の度合い(`voiceActivity`)は、事実上必須。** 与えないと、和音・笛・楽器のように倍音が整数倍に並ぶ音が、声と誤られて取り除かれる。 + +声・音楽・効果音の3つに分けるとき(音楽と効果音の見分けは、おおまか。下の「音楽と効果音」を必ず読むこと): + +```swift +let activities = try SpeechActivityDetector().detectActivities(signal) // 声・音楽・効果音の度合い +let parts = VoiceSeparator().separateComponents( + signal, voiceActivity: activities.voice, musicActivity: activities.music, effectsActivity: activities.effects +) +let withoutVoice = parts.mixed(voice: false, music: true, effects: true) // 選んだ成分だけを足す +``` + +`SpeechActivityDetector` は、窓(既定 1 秒)より短い音では判断できず、値が空の `VoiceActivity` を返す。 +その場合 `separate` は声の度合いを使わずに分ける。**声の判定が安定するよう、使いたい範囲の前後に 1〜2 秒の音を足して渡すとよい。** + +Swift Package Manager: + +```swift +.package(path: "Packages/VoiceSeparationKit"), // 公開後は URL に差し替える +.product(name: "VoiceSeparation", package: "VoiceSeparationKit"), +.product(name: "VoiceSeparationSoundAnalysis", package: "VoiceSeparationKit"), // 任意 +``` + +対応: macOS 13+ / iOS 16+。`VoiceSeparation` は Foundation だけを使うので、SoundAnalysis が無い環境でもビルドできる。 + +## 仕組み + +1. **STFT**(ハン窓・4096 点・1024 サンプルずつずらす)でスペクトルにする。FFT は Swift で書いた基数 2 の実装。 +2. **声の高さの追跡**。基本周波数の候補(70〜450 Hz)ごとに、整数倍の位置の山と、その中間の谷の差(対数振幅)を、低い倍音から順に平均する。 + 途中までの平均の最大を採る(高い倍音が無い声でも薄まらない)。雑音や衝撃音は山と谷の差が出ないので、声と誤られにくい。 + 時間方向はビタビ法でつなぎ、声の有無も同時に決める。 +3. **倍音の除去**。低い倍音の実測位置から倍音の間隔を精密に求め直し、各倍音の山の位置と、両側の谷(隣の倍音との中間の最小値)を実測する。 + 谷から谷までを直線でつないだ高さを「声が無かったときの高さ」とみなし、山のまわりでそれを超える分だけを削る。 + 倍音を丸ごと 0 にしないので、声と同時に鳴っていた雑音や、倍音の間にある音は残る。 + 高域(1.5 kHz 以上)で周りの倍音より飛び抜けて強い山は、別の音が重なっているとみなし、声の分(周りの 2 倍まで)だけを削る。 +4. 位相は入力のまま使い、逆 STFT で波形に戻す。声は入力から背景を引いたもの。 + +## 測定 + +合成音声(macOS の `say`)に、macOS のシステム効果音を混ぜ、混ぜる前の声と効果音も別に持って測った。 +声だけ・効果音だけ・声と効果音が重なる区間がある 40 秒のステレオ音声。`SpeechActivityDetector` を併用。 + +| 声 | 声だけの区間で残る量 | 効果音だけの区間で残る量 | 重なり区間の効果音の SDR(入力 → 分離後、2 か所) | +|---|---|---|---| +| 日本語の女声(Kyoko) | −19.3 dB | −0.4 dB | −11.5 → **+0.4** / −11.4 → **+4.4** | +| 英語の女声(Samantha) | −16.9 dB | −0.4 dB | −19.6 → **−4.1** / −19.4 → **−3.3** | +| 英語の男声(Daniel) | −12.8 dB | −0.4 dB | −17.0 → **−5.0** / −16.8 → **−4.1** | +| 英語の男声(Fred、低くて機械的) | −16.2 dB | −0.4 dB | −15.5 → **−1.1** / −15.3 → **+0.2** | + +読み方: 「声だけの区間で残る量」は小さい(負で大きい)ほど声が消えている。−13 dB は声のエネルギーの約 5%、−19 dB は約 1%。 +SDR は大きいほど、効果音に近い。分離後も負の値が残るのは、声が効果音より十数 dB 大きい所で、取りきれなかった声がまだ効果音より大きいため(改善幅は 12〜16 dB)。 + +**この測定の限界**: 声は音声合成で、実際の録音ではない(実際の声は息の音・ゆらぎ・残響が多く、より難しい可能性が高い)。 +効果音も数種類のシステム音だけ。声の種類(5 種類)と効果音の組み合わせも少ない。 +**実際の動画でこの数値が出るとは限らない。** 残っている声の大半は、息の音・無声子音と、声の出始め・終わりの弱い枠。 + +速度(Apple M3、リリースビルド、ステレオ): 3 秒の音で声の検出 約 90 ms + 分離 約 30 ms、12 秒で 約 190 ms + 約 130 ms(実時間の 26〜37 倍速)。 +**デバッグビルドでは 10〜50 倍遅い**ので、実機の確認はリリースビルドで行うこと。 + +## 音楽と効果音(実用になる精度には届いていない) + +声以外を音楽と効果音に分ける処理(`MusicEffectsSplitter`)は、**スペクトルで見分けているのではない**。 +- 周波数の帯ごとに、前後 0.8 秒の強さの中央値を「鳴り続けている分」とみなし、その分を音楽、はみ出した分を効果音とする。 +- 音楽の度合い(SoundAnalysis)が低い区間は、すべて効果音にする。 +- 効果音の度合い(声でも音楽でもない分類の確からしさ)を与えると、「効果音が起きている区間の突発的な成分」だけを効果音とし、それ以外は音楽にする。 + +合成した背景音楽(撥弦楽器の和音・ドラム、120 BPM)・話し声・システム効果音を混ぜ、混ぜる前の3つと比べた(40 秒、SDR は大きいほど良い): + +| | 声 | 音楽 | 効果音 | +|---|---|---|---| +| 混ぜたまま | −0.2 | −0.3 | −14.9 | +| 鳴り続けるかだけで分ける | 6.1 | 1.4 | −9.3 | +| 効果音の度合いも使う(既定、しきい値 0.3/0.6) | 6.1 | 5.2 | **−0.8(効果音の出力がほぼ空)** | +| 同、しきい値 0.05/0.15 | 6.1 | 2.0 | −8.3 | + +読み方: 効果音は、どの設定でも **0 dB を超えなかった**。「効果音の出力が空」(0 dB 付近)か、「音楽のドラムなどの突発音が混ざる」(−8 dB)かのどちらかで、効果音だけを取り出せてはいない。 +音楽の SDR が高いのは、効果音が音楽より 12 dB 小さく、「ほぼ全部を音楽に入れた」だけで高く出るため。 +**声の分離だけが、実際に効いている。** 音楽と効果音を実用的に分けるには、学習型のモデルが要る。 + +この測定の限界: 効果音は macOS のシステム音(電子音)で、SoundAnalysis が効果音と認識しにくい(「音楽」と判定する)。 +衝撃・足音・ドアなどの実際の効果音では、効果音の度合いがもっと高く出て、結果が変わる可能性はあるが、確かめていない。 + +## 調整項目(`VoiceSeparationConfiguration`) + +| 項目 | 既定 | 説明 | +|---|---|---| +| `fftSize` / `hopSize` | 4096 / 1024 | 長いほど低い声の倍音を分けられるが、声の高さが動く所はにじむ | +| `minimumPitch` / `maximumPitch` | 70 / 450 Hz | 声の基本周波数を探す範囲 | +| `voicingThreshold` | 0.45 | 声とみなす「倍音の山と谷の差」。小さいほど声を拾うが、効果音を声と誤る | +| `lowPitchBias` | 0.1 | 本来の数倍の高さを選ぶ誤りを減らすための、低い周波数への偏り | +| `maximumRemovedFrequency` | 5000 Hz | これより上の倍音は残す | +| `breathReduction` | 0.7 | 声の区間で高さが見つからない枠(息の音・子音)の高域を弱める量。同じ周波数の効果音も弱まる | +| `activityInfluence` | 1.0 | `VoiceActivity` を重く見る度合い。0 なら無視 | +| `removalStrength` | 1.0 | 声を取り除く強さ | +| `musicGateLow` / `musicGateHigh` | 0.4 / 0.7 | 音楽の度合いが、この範囲で、音楽を認める度合いが 0→1 になる | +| `effectsGateLow` / `effectsGateHigh` | 0.3 / 0.6 | 効果音の度合いが、この範囲で、突発成分を効果音とみなす度合いが 0→1 になる | +| `musicStationarySeconds` | 0.8 | 「鳴り続けている音」を見分ける、前後の長さ(秒) | + +## テスト + +```bash +swift test +``` + +合成した声(高さが動く・ビブラート・音節の強弱)と効果音(雑音の衝撃・電子音)での検証と、 +macOS の `say` で作った本物の話し声を使う検出器のテストがある(`say` が無い環境では、そのテストは飛ばされる)。 + +## ライセンス + +未設定。公開する前に決める。 diff --git a/Packages/VoiceSeparationKit/Sources/VoiceSeparation/AudioSignal.swift b/Packages/VoiceSeparationKit/Sources/VoiceSeparation/AudioSignal.swift new file mode 100644 index 0000000..28c88ea --- /dev/null +++ b/Packages/VoiceSeparationKit/Sources/VoiceSeparation/AudioSignal.swift @@ -0,0 +1,57 @@ +import Foundation + +/// 複数チャンネルの音声。サンプルは 32bit 浮動小数点(ふつう -1...1)で、チャンネルごとに配列を持つ。 +public struct AudioSignal: Equatable, Sendable { + public var sampleRate: Double + public var channels: [[Float]] + + /// チャンネルの長さが違うときは、いちばん短いものに合わせて切り詰める。 + public init(sampleRate: Double, channels: [[Float]]) { + self.sampleRate = sampleRate + let length = channels.map(\.count).min() ?? 0 + self.channels = channels.map { $0.count == length ? $0 : Array($0.prefix(length)) } + } + + public var frameCount: Int { channels.first?.count ?? 0 } + public var duration: Double { sampleRate > 0 ? Double(frameCount) / sampleRate : 0 } + + /// 全チャンネルの平均。解析(ピッチ・分離の判断)はこの音で行う。 + public func monoMix() -> [Float] { + guard let first = channels.first else { return [] } + guard channels.count > 1 else { return first } + var mix = [Float](repeating: 0, count: first.count) + for channel in channels { + for index in 0.. Float? { + guard !values.isEmpty else { return nil } + let position = (time - startTime) / interval + if position <= 0 { return values[0] } + let last = values.count - 1 + if position >= Double(last) { return values[last] } + let lower = Int(position) + let fraction = Float(position - Double(lower)) + return values[lower] * (1 - fraction) + values[lower + 1] * fraction + } +} diff --git a/Packages/VoiceSeparationKit/Sources/VoiceSeparation/FFT.swift b/Packages/VoiceSeparationKit/Sources/VoiceSeparation/FFT.swift new file mode 100644 index 0000000..18ffe22 --- /dev/null +++ b/Packages/VoiceSeparationKit/Sources/VoiceSeparation/FFT.swift @@ -0,0 +1,98 @@ +import Foundation + +/// 2 のべき乗の長さの複素 FFT(基数 2、その場で計算)。 +/// Accelerate に頼らず Swift だけで書いてあるので、どの環境でも同じ結果になる。 +final class FFTPlan { + let size: Int + private let cosines: [Float] + private let sines: [Float] + private let reversed: [Int32] + + init(size: Int) { + precondition(size >= 2 && size & (size - 1) == 0, "FFT の長さは 2 のべき乗にする") + self.size = size + var cosines = [Float](repeating: 0, count: size / 2) + var sines = [Float](repeating: 0, count: size / 2) + for index in 0..>= 1 + } + reversed[index] = Int32(result) + } + self.reversed = reversed + } + + /// `real`/`imag` を FFT する。`inverse` なら逆変換で、結果を長さで割って元の大きさに戻す。 + func transform(real: inout [Float], imag: inout [Float], inverse: Bool) { + precondition(real.count == size && imag.count == size) + real.withUnsafeMutableBufferPointer { re in + imag.withUnsafeMutableBufferPointer { im in + cosines.withUnsafeBufferPointer { cosines in + sines.withUnsafeBufferPointer { sines in + reversed.withUnsafeBufferPointer { reversed in + Self.run(re: re, im: im, cosines: cosines, sines: sines, reversed: reversed, size: size, inverse: inverse) + } + } + } + } + } + } + + private static func run( + re: UnsafeMutableBufferPointer, + im: UnsafeMutableBufferPointer, + cosines: UnsafeBufferPointer, + sines: UnsafeBufferPointer, + reversed: UnsafeBufferPointer, + size: Int, + inverse: Bool + ) { + for index in 0.. index { + let r = re[index]; re[index] = re[other]; re[other] = r + let i = im[index]; im[index] = im[other]; im[other] = i + } + } + let direction: Float = inverse ? -1 : 1 + var length = 2 + while length <= size { + let half = length / 2 + let step = size / length + var start = 0 + while start < size { + for offset in 0.. [Float] { + var gains = [Float](repeating: 1, count: frames * bins) + let binHz = sampleRate / Double(fftSize) + let threshold = configuration.voicingThreshold + magnitude.withUnsafeBufferPointer { mag in + for frame in 0.. 0 else { continue } + // 山と谷が分けられるだけ、倍音の間隔が空いているときだけ処理する。 + let spacing = frequency / binHz + guard spacing >= 4 else { continue } + + // 声らしさが弱い枠は、削る量を減らす(閾値で 0、閾値の `fullRemovalRatio` 倍で全開)。 + let ramp = max(threshold * (configuration.fullRemovalRatio - 1), 1e-6) + let confidence = min(max((pitch.strengths[frame] - threshold) / ramp, 0), 1) + let strength = confidence * configuration.removalStrength + guard strength > 0 else { continue } + + removeHarmonics( + mag: mag, base: frame * bins, bins: bins, spacing: spacing, strength: Float(strength), + gains: &gains + ) + } + } + return gains + } + + /// 低い倍音(声の主なエネルギーがあり、山がはっきり分かれている)の実測位置から、倍音の間隔(ビン)を求め直す。 + /// 声の高さの推定は 0.7% 刻みなので、高い倍音(20 番目など)では位置が 1 ビン以上ずれる。 + /// 倍音は整数倍に並ぶので、低い倍音を使えば、高い倍音の位置もずっと正確に予測できる。 + private func refinedSpacing(mag: UnsafeBufferPointer, base: Int, bins: Int, spacing: Double) -> Double { + var weightedPositions = 0.0 + var weights = 0.0 + var harmonic = 1 + while harmonic <= 8, Double(harmonic) * spacing < Double(bins - 3) { + let nominal = Double(harmonic) * spacing + let tolerance = min(max(1.5, 0.012 * nominal), 0.3 * spacing) + let low = max(1, Int((nominal - tolerance).rounded(.up))) + let high = min(bins - 2, Int((nominal + tolerance).rounded(.down))) + defer { harmonic += 1 } + guard high >= low else { continue } + var peak = low + for bin in low...high where mag[base + bin] > mag[base + peak] { peak = bin } + // 範囲の端にある(その先も上がっていく)ものは、山ではないので使わない。 + guard peak > low, peak < high || mag[base + peak] >= mag[base + peak + 1] else { continue } + let before = log(max(mag[base + peak - 1], 1e-12)) + let center = log(max(mag[base + peak], 1e-12)) + let after = log(max(mag[base + peak + 1], 1e-12)) + let curvature = before - 2 * center + after + let offset = curvature < 0 ? Double(0.5 * (before - after) / curvature) : 0 + let position = Double(peak) + min(max(offset, -0.5), 0.5) + let weight = Double(mag[base + peak]) + weightedPositions += weight * Double(harmonic) * position + weights += weight * Double(harmonic) * Double(harmonic) + } + guard weights > 0 else { return spacing } + let refined = weightedPositions / weights + // 大きく外れたときは、誤った山を拾ったとみなして元の値を使う。 + return abs(refined - spacing) / spacing < 0.03 ? refined : spacing + } + + private func removeHarmonics( + mag: UnsafeBufferPointer, + base: Int, + bins: Int, + spacing initialSpacing: Double, + strength: Float, + gains: inout [Float] + ) { + let spacing = refinedSpacing(mag: mag, base: base, bins: bins, spacing: initialSpacing) + let binHz = sampleRate / Double(fftSize) + let limitBin = min(configuration.maximumRemovedFrequency / binHz, Double(bins - 3)) + let count = Int(limitBin / spacing) + guard count >= 1 else { return } + + // 3 ビンで均した振幅。谷の高さを、ビンごとのばらつきに左右されずに見るために使う。 + var smoothed = [Float](repeating: 0, count: bins) + for bin in 1..<(bins - 1) { + smoothed[bin] = 0.25 * mag[base + bin - 1] + 0.5 * mag[base + bin] + 0.25 * mag[base + bin + 1] + } + let reach = max(2, Int((0.5 * spacing).rounded(.down))) + let bias = configuration.valleyBias + + /// 倍音ひとつぶんの、山と谷の位置。 + struct Harmonic { + var peak: Int + var left: Int + var right: Int + var leftLevel: Float + var rightLevel: Float + /// 山の高さのうち、谷の線を超えている分(声の強さの目安)。 + var excess: Float + /// 削る割合(1 = 山ぜんぶ、小さいほど、周りの倍音より突出した分を残す)。 + var share: Float = 1 + + func floorLevel(at bin: Int, bias: Float) -> Float { + (leftLevel + (rightLevel - leftLevel) * Float(bin - left) / Float(right - left)) * bias + } + } + + var harmonics: [Harmonic] = [] + for harmonic in 1...count { + // 山: 倍音の目安の位置の近くで、実際にいちばん大きいビン(声の高さが動くとずれるので、実測で探す)。 + let nominal = Double(harmonic) * spacing + let tolerance = min(max(1.5, Self.relativeSmear * 0.5 * nominal), 0.3 * spacing) + let searchLow = max(1, Int((nominal - tolerance).rounded(.up))) + let searchHigh = min(bins - 2, Int((nominal + tolerance).rounded(.down))) + guard searchHigh >= searchLow else { continue } + var peak = searchLow + for bin in searchLow...searchHigh where mag[base + bin] > mag[base + peak] { peak = bin } + + // 谷: 山の両側で、隣の倍音との中間までのうち、いちばん低い所。 + var left = peak + var leftLevel = smoothed[peak] + var bin = peak - 1 + while bin >= max(1, peak - reach) { + if smoothed[bin] < leftLevel { leftLevel = smoothed[bin]; left = bin } + bin -= 1 + } + var right = peak + var rightLevel = smoothed[peak] + bin = peak + 1 + while bin <= min(bins - 2, peak + reach) { + if smoothed[bin] < rightLevel { rightLevel = smoothed[bin]; right = bin } + bin += 1 + } + guard right > left else { continue } + var entry = Harmonic(peak: peak, left: left, right: right, leftLevel: leftLevel, rightLevel: rightLevel, excess: 0) + entry.excess = max(0, mag[base + peak] - entry.floorLevel(at: peak, bias: bias)) + harmonics.append(entry) + } + + // 声の倍音の強さは、隣どうしでなめらかに変わる。周りの倍音より飛び抜けて強い山は、 + // 同じ位置で鳴っている別の音(電子音など)が足されているとみなし、声の分(周りの 2 倍まで)だけを削る。 + let firstOutlierBin = Self.outlierMinimumFrequency / binHz + for index in harmonics.indices where harmonics[index].excess > 0 && Double(harmonics[index].peak) >= firstOutlierBin { + let low = max(0, index - 2) + let high = min(harmonics.count - 1, index + 2) + guard high - low >= 3 else { continue } + let neighbors = (low...high).filter { $0 != index }.map { harmonics[$0].excess }.sorted() + let typical = neighbors[neighbors.count / 2] + let allowed = Self.outlierTolerance * typical + if harmonics[index].excess > allowed { + harmonics[index].share = max(0, allowed / harmonics[index].excess) + } + } + + for entry in harmonics { + // 谷から谷までを直線でつないだ高さを「声が無かったときの高さ」とみなし、山のまわりでそれを超える分だけを削る。 + // 山から外へ向かって、その高さを超えている間だけを削るので、倍音と倍音の間に独立してある音は残る。 + func attenuate(_ bin: Int) { + let original = mag[base + bin] + let level = entry.floorLevel(at: bin, bias: bias) + guard original > level, original > 0 else { return } + let kept = 1 - strength * entry.share * (1 - level / original) + if kept < gains[base + bin] { gains[base + bin] = kept } + } + attenuate(entry.peak) + var outward = entry.peak - 1 + while outward >= entry.left, smoothed[outward] > entry.floorLevel(at: outward, bias: bias) { + attenuate(outward) + outward -= 1 + } + outward = entry.peak + 1 + while outward <= entry.right, smoothed[outward] > entry.floorLevel(at: outward, bias: bias) { + attenuate(outward) + outward += 1 + } + } + } +} diff --git a/Packages/VoiceSeparationKit/Sources/VoiceSeparation/MusicEffectsSplitter.swift b/Packages/VoiceSeparationKit/Sources/VoiceSeparation/MusicEffectsSplitter.swift new file mode 100644 index 0000000..6f37490 --- /dev/null +++ b/Packages/VoiceSeparationKit/Sources/VoiceSeparation/MusicEffectsSplitter.swift @@ -0,0 +1,120 @@ +import Foundation + +/// 声を取り除いた残りを、音楽と効果音に分ける。 +/// +/// 音楽は、一定の時間のあいだ同じような強さで鳴り続ける(和音・伴奏・環境の連続音)。 +/// 効果音は、短く突発的に鳴る(衝撃・動作の音)。そこで、周波数の帯ごとに、前後 `musicStationarySeconds` 秒の +/// 強さの中央値を「鳴り続けている分」とみなし、全体のうちその分を音楽、はみ出した分を効果音とする。 +/// ただし、音楽が鳴っているとは限らないので、外から与える「音楽の度合い」が低い区間は、すべて効果音にする。 +/// +/// これは、音楽と効果音を**スペクトルで見分けている**のではなく、「鳴り続けるか、突発的か」で分けているだけ。 +/// 長く鳴り続ける効果音は音楽に、音楽のドラムのような短い音は効果音に入ることがある。 +struct MusicEffectsSplitter { + let configuration: VoiceSeparationConfiguration + + /// 帯に束ねるビンの数。ビンごとの細かいばらつきに、中央値が左右されないようにする。 + private static let bandWidth = 4 + + func split( + _ background: AudioSignal, musicActivity: VoiceActivity, effectsActivity: VoiceActivity? = nil + ) -> (music: AudioSignal, effects: AudioSignal) { + let frameCount = background.frameCount + let empty = AudioSignal(sampleRate: background.sampleRate, channels: background.channels.map { _ in [Float](repeating: 0, count: frameCount) }) + guard frameCount > 0, background.sampleRate > 0, !musicActivity.values.isEmpty else { return (empty, background) } + + let stft = STFT(fftSize: configuration.fftSize, hop: configuration.hopSize) + let frames = stft.frameCount(forLength: frameCount) + let bins = stft.bins + let decision = stft.analyze(background.monoMix()) + let magnitude = decision.magnitudes() + + // 1. 周波数の帯ごとの強さ。 + let width = Self.bandWidth + let bands = (bins + width - 1) / width + var level = [Float](repeating: 0, count: frames * bands) + for frame in 0.. 1e-9 ? min(1, stationary / current) : 0 + } + } + + // 3. 音楽の度合いで、区間ごとに音楽を認めるかを決める(低ければ、すべて効果音)。 + let low = configuration.musicGateLow + let high = max(configuration.musicGateHigh, low + 1e-3) + let gate: [Float] = (0.. 0 { + let time = stft.centerTime(ofFrame: frame, sampleRate: background.sampleRate) + let x = min(max(((effectsActivity.value(at: time) ?? 0) - effectsLow) / (effectsHigh - effectsLow), 0), 1) + let effectsGate = x * x * (3 - 2 * x) + for bin in 0.. 0 { + for bin in 0.. [Candidate] { + let binHz = sampleRate / Double(fftSize) + let octaves = log2(configuration.maximumPitch / configuration.minimumPitch) + let count = Int(octaves * Self.stepsPerOctave) + 1 + var candidates: [Candidate] = [] + candidates.reserveCapacity(count) + for index in 0.. limit { break } + let tolerance = min(max(1.0, 0.012 * peakCenter), 0.3 * spacing) + let weight = Float(1 / Double(harmonic).squareRoot()) + harmonics.append(( + Int((peakCenter - tolerance).rounded()), Int((peakCenter + tolerance).rounded()), + Int((valleyCenter - tolerance).rounded()), Int((valleyCenter + tolerance).rounded()), + weight + )) + weightSum += weight + harmonic += 1 + } + candidates.append(Candidate(frequency: frequency, harmonics: harmonics, totalWeight: weightSum)) + } + return candidates + } + + /// - Parameters: + /// - logMagnitude: 時間枠×ビンの対数振幅(`frames * bins`)。 + /// - activity: 時間枠ごとの声の度合い(0...1)。nil なら全部を 1 とみなす。 + func track(logMagnitude: [Float], frames: Int, bins: Int, activity: [Float]?) -> PitchTrack { + guard frames > 0 else { return PitchTrack(frequencies: [], strengths: []) } + let candidates = makeCandidates(bins: bins) + let count = candidates.count + guard count > 0 else { + return PitchTrack(frequencies: [Float](repeating: 0, count: frames), strengths: [Float](repeating: 0, count: frames)) + } + + // 低い周波数を選びやすくする偏り(最も低い候補を 0 として、オクターブごとに引く)。 + let tilt = candidates.map { configuration.lowPitchBias * Float(log2($0.frequency / configuration.minimumPitch)) } + + // 1. 枠ごと・候補ごとの、倍音の山と谷の差。 + var salience = [Float](repeating: 0, count: frames * count) + logMagnitude.withUnsafeBufferPointer { log in + for frame in 0.. 0 { + // 低い倍音から順に「山と谷の差」を足していき、途中までの平均のうち最大のものを採る。 + // 声によっては、高い倍音がほとんど無い(エネルギーが最初の数本に集中している)。 + // 全部の平均を取ると、そういう声は高域の「何も無い倍音」に薄められてしまい、 + // 倍音の数が少ない、本来の数倍の高さの候補に負ける。 + var cumulative: Float = 0 + var weightSum: Float = 0 + var best = -Float.infinity + let minimumCount = min(Self.minimumHarmonicCount, candidate.harmonics.count) + for (position, harmonic) in candidate.harmonics.enumerated() { + var peak = -Float.infinity + var bin = max(0, harmonic.peakLow) + let peakEnd = min(bins - 1, harmonic.peakHigh) + while bin <= peakEnd { peak = max(peak, log[base + bin]); bin += 1 } + var valley = -Float.infinity + bin = max(0, harmonic.valleyLow) + let valleyEnd = min(bins - 1, harmonic.valleyHigh) + while bin <= valleyEnd { valley = max(valley, log[base + bin]); bin += 1 } + if peak.isFinite && valley.isFinite { cumulative += harmonic.weight * (peak - valley) } + weightSum += harmonic.weight + if position + 1 >= minimumCount { best = max(best, cumulative / weightSum) } + } + salience[frame * count + index] = (best.isFinite ? best : 0) - tilt[index] + } + } + } + + // 2. ビタビ法。状態は「各候補の高さ」と「声なし」。 + let unvoiced = count + let states = count + 1 + let threshold = configuration.voicingThreshold + let switchCost = threshold * 0.5 + let stepCost = configuration.pitchChangePenalty * 0.05 + var previous = [Float](repeating: 0, count: states) + var current = [Float](repeating: 0, count: states) + var back = [Int16](repeating: 0, count: frames * states) + let negativeInfinity = -Float.greatestFiniteMagnitude + + for frame in 0.. bestVoiced { + bestVoiced = previous[index] + bestVoicedIndex = index + } + for index in 0.. best { best = score; from = other } + } + // 声なしから来る場合。 + let fromUnvoiced = previous[unvoiced] - switchCost + if fromUnvoiced > best { best = fromUnvoiced; from = unvoiced } + current[index] = best + salience[frame * count + index] + back[frame * states + index] = Int16(from) + } + // 声なしの状態へ。 + var best = previous[unvoiced] + var from = unvoiced + if bestVoiced - switchCost > best { best = bestVoiced - switchCost; from = bestVoicedIndex } + current[unvoiced] = best + unvoicedScore + back[frame * states + unvoiced] = Int16(from) + } + swap(&previous, ¤t) + } + + // 3. 最後から辿って、高さの流れを取り出す。 + var state = 0 + var bestScore = negativeInfinity + for index in 0.. bestScore { + bestScore = previous[index] + state = index + } + var frequencies = [Float](repeating: 0, count: frames) + var strengths = [Float](repeating: 0, count: frames) + for frame in stride(from: frames - 1, through: 0, by: -1) { + if state != unvoiced { + frequencies[frame] = Float(candidates[state].frequency) + strengths[frame] = salience[frame * count + state] + } + state = Int(back[frame * states + state]) + } + return PitchTrack(frequencies: frequencies, strengths: strengths) + } +} diff --git a/Packages/VoiceSeparationKit/Sources/VoiceSeparation/STFT.swift b/Packages/VoiceSeparationKit/Sources/VoiceSeparation/STFT.swift new file mode 100644 index 0000000..373b308 --- /dev/null +++ b/Packages/VoiceSeparationKit/Sources/VoiceSeparation/STFT.swift @@ -0,0 +1,107 @@ +import Foundation + +/// 短時間フーリエ変換の結果。`frames` 個の時間枠それぞれに、0 Hz からナイキスト周波数までの `bins` 個の複素数を持つ。 +struct Spectrogram { + let frames: Int + let bins: Int + var real: [Float] + var imag: [Float] + + init(frames: Int, bins: Int) { + self.frames = frames + self.bins = bins + real = [Float](repeating: 0, count: frames * bins) + imag = [Float](repeating: 0, count: frames * bins) + } + + /// 振幅(複素数の絶対値)。 + func magnitudes() -> [Float] { + var result = [Float](repeating: 0, count: real.count) + for index in 0.. 0 && hop <= fftSize / 2, "hop は窓の半分以下にする") + self.fftSize = fftSize + self.hop = hop + bins = fftSize / 2 + 1 + plan = FFTPlan(size: fftSize) + window = (0.. Int { + length <= 0 ? 0 : (length + hop - 1) / hop + 1 + } + + /// 時間枠 `frame` の中心の時刻(秒)。 + func centerTime(ofFrame frame: Int, sampleRate: Double) -> Double { + Double(frame * hop) / sampleRate + } + + func analyze(_ samples: [Float]) -> Spectrogram { + let frames = frameCount(forLength: samples.count) + var spectrogram = Spectrogram(frames: frames, bins: bins) + var real = [Float](repeating: 0, count: fftSize) + var imag = [Float](repeating: 0, count: fftSize) + for frame in 0..= 0 && source < samples.count) ? samples[source] * window[index] : 0 + imag[index] = 0 + } + plan.transform(real: &real, imag: &imag, inverse: false) + let base = frame * bins + for bin in 0.. [Float] { + var output = [Float](repeating: 0, count: length) + var weight = [Float](repeating: 0, count: length) + var real = [Float](repeating: 0, count: fftSize) + var imag = [Float](repeating: 0, count: fftSize) + for frame in 0..= 0 && target < length else { continue } + output[target] += real[index] * window[index] + weight[target] += window[index] * window[index] + } + } + for index in 0.. AudioSignal { + var selected: [AudioSignal] = [] + if includesVoice { selected.append(voice) } + if includesMusic { selected.append(music) } + if includesEffects { selected.append(effects) } + let frameCount = voice.frameCount + var channels = voice.channels.map { _ in [Float](repeating: 0, count: frameCount) } + for signal in selected { + for (index, samples) in signal.channels.enumerated() where index < channels.count { + for position in 0.. SoundComponents { + let result = separate(signal, voiceActivity: voiceActivity) + guard let musicActivity else { + let silent = AudioSignal(sampleRate: signal.sampleRate, channels: signal.channels.map { [Float](repeating: 0, count: $0.count) }) + return SoundComponents(voice: result.voice, music: silent, effects: result.background, pitch: result.pitch) + } + let split = MusicEffectsSplitter(configuration: configuration).split( + result.background, musicActivity: musicActivity, effectsActivity: effectsActivity + ) + return SoundComponents(voice: result.voice, music: split.music, effects: split.effects, pitch: result.pitch) + } +} diff --git a/Packages/VoiceSeparationKit/Sources/VoiceSeparation/VoiceSeparationConfiguration.swift b/Packages/VoiceSeparationKit/Sources/VoiceSeparation/VoiceSeparationConfiguration.swift new file mode 100644 index 0000000..3144661 --- /dev/null +++ b/Packages/VoiceSeparationKit/Sources/VoiceSeparation/VoiceSeparationConfiguration.swift @@ -0,0 +1,47 @@ +import Foundation + +/// 声の分離の調整項目。既定値は、話し声(男女・子どもを含む)を想定している。 +public struct VoiceSeparationConfiguration: Equatable, Sendable { + /// FFT の長さ(2 のべき乗)。長いほど、低い声の倍音を分けて見られるが、声の高さが動く所はにじむ。 + public var fftSize = 4096 + /// 時間枠の間隔(サンプル)。`fftSize` の半分以下にする。 + public var hopSize = 1024 + /// 声の基本周波数を探す範囲(Hz)。 + public var minimumPitch = 70.0 + public var maximumPitch = 450.0 + /// 声の高さを調べるときに見る周波数の上限(Hz)。 + public var pitchSearchLimit = 3500.0 + /// 声として取り除く周波数の上限(Hz)。これより上の倍音は残す。 + public var maximumRemovedFrequency = 5000.0 + /// 声とみなす「倍音の山と谷の差」の最小値(対数振幅、nat)。小さいほど声を拾いやすいが、効果音を声と誤る。 + public var voicingThreshold: Float = 0.45 + /// 低い周波数を選びやすくする偏り(1 オクターブ上がるごとに、声らしさから引く値、nat)。 + /// 基本周波数の整数倍の櫛も、同じくらい声らしく見えてしまう(本来の 3〜4 倍の高さを選ぶ誤り)ので、同点なら低いほうを採る。 + public var lowPitchBias: Float = 0.1 + /// 声の高さが急に変わることへの罰則の強さ。大きいほど高さの流れがなめらかになる。 + public var pitchChangePenalty: Float = 0.5 + /// 外から与えた「声の度合い」(`VoiceActivity`)を、どれだけ重く見るか。0 なら無視する。 + public var activityInfluence: Float = 1.0 + /// 声らしさが `voicingThreshold` の何倍以上なら、全力で削るか。閾値から、この倍率までの間は、声らしさに応じて削る量を増やす。 + public var fullRemovalRatio: Float = 2.0 + /// 倍音の谷の高さに掛ける倍率。1 より大きいと声が少し残るが、同時に鳴っている雑音を削りすぎない。 + public var valleyBias: Float = 1.0 + /// 声の区間(`VoiceActivity` が 0.5 以上)で、声の高さが見つからない枠(「s」「f」などの息の音・子音)の + /// 高い周波数をどれだけ弱めるか(0...1)。これらは倍音を持たないので、分けられずに残る。 + /// 弱めると息の音は減るが、同じ区間・同じ周波数の効果音も一緒に弱まる。`VoiceActivity` を与えたときだけ働く。 + public var breathReduction: Float = 0.7 + /// 音楽と効果音を分けるとき、「音楽の度合い」(`VoiceActivity`)がこの値以下なら、音楽は無いとみなす。 + public var musicGateLow: Float = 0.4 + /// 「音楽の度合い」がこの値以上なら、鳴り続けている成分を、すべて音楽とみなす。`musicGateLow` との間は、なだらかにつなぐ。 + public var musicGateHigh: Float = 0.7 + /// 「効果音の度合い」がこの値以下なら、効果音は起きていないとみなす。 + public var effectsGateLow: Float = 0.3 + /// 「効果音の度合い」がこの値以上なら、その区間の突発的な成分を、すべて効果音とみなす。 + public var effectsGateHigh: Float = 0.6 + /// 「鳴り続けている音」を見分ける時間の長さ(秒)。前後この長さのあいだ、ほぼ同じ強さで鳴っている成分を音楽とする。 + public var musicStationarySeconds = 0.8 + /// 声を取り除く強さ(0...1)。1 で、見つけた声をできるだけ取り除く。 + public var removalStrength: Float = 1.0 + + public init() {} +} diff --git a/Packages/VoiceSeparationKit/Sources/VoiceSeparation/VoiceSeparator.swift b/Packages/VoiceSeparationKit/Sources/VoiceSeparation/VoiceSeparator.swift new file mode 100644 index 0000000..043ed74 --- /dev/null +++ b/Packages/VoiceSeparationKit/Sources/VoiceSeparation/VoiceSeparator.swift @@ -0,0 +1,121 @@ +import Foundation + +/// 声の高さの流れ(診断や表示に使う)。 +public struct PitchContour: Equatable, Sendable { + /// 各時間枠の中心の時刻(秒)。 + public var times: [Double] + /// 基本周波数(Hz)。声が無い枠は 0。 + public var frequencies: [Float] + /// 声らしさ(倍音の山と谷の差、対数振幅 nat)。声が無い枠は 0。 + public var strengths: [Float] + + /// 声がある枠の割合(0...1)。 + public var voicedRatio: Double { + guard !frequencies.isEmpty else { return 0 } + return Double(frequencies.filter { $0 > 0 }.count) / Double(frequencies.count) + } +} + +/// 声の分離結果。`voice + background` は入力にほぼ一致する。 +public struct SeparationResult: Sendable { + /// 取り除いた声。 + public var voice: AudioSignal + /// 声を取り除いた残り(効果音・環境音・音楽など)。 + public var background: AudioSignal + public var pitch: PitchContour +} + +/// 人の声と、それ以外の音を分ける。 +/// +/// 学習済みのモデルは使わず、声の倍音(基本周波数の整数倍に並ぶ山)を信号処理で見つけて削る。 +/// 話し声のうち、声帯が震える母音や有声子音はよく分かれるが、息の音や「s」「f」のような無声子音は残りやすい。 +/// 声と同じ周波数で鳴る楽器や警告音は、声と見分けられず一緒に削れることがある。 +public struct VoiceSeparator: Sendable { + public var configuration: VoiceSeparationConfiguration + + /// 息の音を弱める周波数の下限(Hz)。これより下には声の本体があり、倍音として別に扱う。 + private static let breathLowestFrequency = 1_500.0 + + public init(configuration: VoiceSeparationConfiguration = VoiceSeparationConfiguration()) { + self.configuration = configuration + } + + /// - Parameters: + /// - signal: 分けたい音。ステレオなら、声の判断は左右の平均で行い、同じ削り方を左右に当てる。 + /// - voiceActivity: 時間ごとの声の度合い(`VoiceActivity`)。与えると、声が無いと分かっている区間を壊さない。 + public func separate(_ signal: AudioSignal, voiceActivity: VoiceActivity? = nil) -> SeparationResult { + let frameCount = signal.frameCount + guard frameCount > 0, signal.sampleRate > 0 else { + return SeparationResult( + voice: AudioSignal(sampleRate: signal.sampleRate, channels: signal.channels.map { _ in [] }), + background: signal, + pitch: PitchContour(times: [], frequencies: [], strengths: []) + ) + } + + let stft = STFT(fftSize: configuration.fftSize, hop: configuration.hopSize) + let frames = stft.frameCount(forLength: frameCount) + let bins = stft.bins + + // 声の判断は、全チャンネルの平均で行う(モノラルなら、その音そのもの)。 + let decisionSpectrogram = stft.analyze(signal.monoMix()) + let magnitude = decisionSpectrogram.magnitudes() + + let peak = magnitude.max() ?? 0 + let floorLevel = max(peak * 1e-4, 1e-9) + let logMagnitude = magnitude.map { log($0 + floorLevel) } + + let times = (0.. 0 { + for frame in 0.. 0 else { continue } + for bin in 0.. 0 { + let binHz = signal.sampleRate / Double(configuration.fftSize) + let firstBin = min(bins - 1, Int(Self.breathLowestFrequency / binHz)) + for frame in 0..= 0.5 { + let gain = 1 - configuration.breathReduction * activity[frame] + for bin in firstBin.. = [ + "speech", "babble", "chatter", "shout", "yell", "whispering", "screaming", "children_shouting", + "battle_cry", "laughter", "giggling", "chuckle_chortle", "snicker", "belly_laugh", "baby_laughter", + "crying_sobbing", "baby_crying", "singing", "choir_singing", "humming", "rapping", "yodeling", + ] + + /// 音楽とみなす分類名(楽曲そのものと、楽器・ドラム)。歌声(`singing`)は声のほうに入れる。 + public static let defaultMusicClasses: Set = [ + "music", "orchestra", "accordion", "acoustic_guitar", "banjo", "bass_drum", "bass_guitar", "bassoon", "bagpipes", + "bowed_string_instrument", "brass_instrument", "cello", "clarinet", "didgeridoo", "double_bass", "drum_kit", + "electric_guitar", "electric_piano", "electronic_organ", "flute", "french_horn", "glockenspiel", "guitar", + "guitar_strum", "guitar_tapping", "hammond_organ", "harmonica", "harp", "harpsichord", "hi_hat", "keyboard_musical", + "mallet_percussion", "mandolin", "marimba_xylophone", "oboe", "organ", "percussion", "piano", + "plucked_string_instrument", "saxophone", "sitar", "snare_drum", "steel_guitar_slide_guitar", "steelpan", + "synthesizer", "tabla", "theremin", "timpani", "trombone", "trumpet", "ukulele", "vibraphone", "violin_fiddle", + "wind_instrument", "zither", + ] + + /// 効果音の度合いから外す分類名。声・音楽のほかに、音が無いこと(`silence`)や、呼吸のような声に近い音を入れる。 + public static let defaultNonEffectClasses: Set = ["silence", "breathing", "sigh", "gasp", "hiccup"] + + public var voiceClasses: Set + public var musicClasses: Set + /// 分類の窓の長さ(秒)。短いほど時間の細かさが上がるが、判定は不安定になる(0.5〜15)。 + public var windowDuration: Double + /// 隣り合う窓の重なり(0...1 未満)。 + public var overlapFactor: Double + + public init( + voiceClasses: Set = SpeechActivityDetector.defaultVoiceClasses, + musicClasses: Set = SpeechActivityDetector.defaultMusicClasses, + windowDuration: Double = 1.0, + overlapFactor: Double = 0.75 + ) { + self.voiceClasses = voiceClasses + self.musicClasses = musicClasses + self.windowDuration = windowDuration + self.overlapFactor = overlapFactor + } + + /// 窓ひとつぶんの結果。 + private struct Window { + var start: Double + var duration: Double + var voice: Float + var music: Float + /// 声・音楽以外の分類のうち、最も確からしいもの(効果音・環境音の度合い)。 + var effects: Float + } + + /// 声の度合いと、音楽の度合い。 + public struct Activities: Sendable { + public var voice: VoiceActivity + public var music: VoiceActivity + /// 声でも音楽でもない音(衝撃・動作・環境の音)の度合い。 + public var effects: VoiceActivity + } + + private final class Collector: NSObject, SNResultsObserving { + let voiceClasses: Set + let musicClasses: Set + let excludedFromEffects: Set + private let lock = NSLock() + private var storedWindows: [Window] = [] + private var storedError: Error? + + init(voiceClasses: Set, musicClasses: Set, excludedFromEffects: Set) { + self.voiceClasses = voiceClasses + self.musicClasses = musicClasses + self.excludedFromEffects = excludedFromEffects + } + + var windows: [Window] { lock.lock(); defer { lock.unlock() }; return storedWindows } + var error: Error? { lock.lock(); defer { lock.unlock() }; return storedError } + + func request(_ request: SNRequest, didProduce result: SNResult) { + guard let result = result as? SNClassificationResult else { return } + var voice: Float = 0 + var music: Float = 0 + var effects: Float = 0 + for classification in result.classifications { + let confidence = Float(classification.confidence) + if voiceClasses.contains(classification.identifier) { + voice = max(voice, confidence) + } else if musicClasses.contains(classification.identifier) { + music = max(music, confidence) + } else if !excludedFromEffects.contains(classification.identifier) { + effects = max(effects, confidence) + } + } + lock.lock() + storedWindows.append(Window( + start: result.timeRange.start.seconds, duration: result.timeRange.duration.seconds, + voice: voice, music: music, effects: effects + )) + lock.unlock() + } + + func request(_ request: SNRequest, didFailWithError error: Error) { + lock.lock(); storedError = error; lock.unlock() + } + + func requestDidComplete(_ request: SNRequest) {} + } + + /// `signal` の声の度合いを調べる。短すぎて窓が一つも作れないときは、値が空の `VoiceActivity` を返す。 + public func detect(_ signal: AudioSignal) throws -> VoiceActivity { + try detectActivities(signal).voice + } + + /// `signal` の声の度合いと音楽の度合いを、一度の解析で調べる。 + public func detectActivities(_ signal: AudioSignal) throws -> Activities { + let interval = 0.05 + let none = VoiceActivity(interval: interval, values: []) + let empty = Activities(voice: none, music: none, effects: none) + let samples = signal.monoMix() + guard !samples.isEmpty, signal.sampleRate > 0, + let format = AVAudioFormat(commonFormat: .pcmFormatFloat32, sampleRate: signal.sampleRate, channels: 1, interleaved: false) + else { + return empty + } + + let request = try SNClassifySoundRequest(classifierIdentifier: .version1) + request.windowDuration = CMTime(seconds: windowDuration, preferredTimescale: 48_000) + request.overlapFactor = min(max(overlapFactor, 0), 0.95) + + let analyzer = SNAudioStreamAnalyzer(format: format) + let collector = Collector( + voiceClasses: voiceClasses, musicClasses: musicClasses, excludedFromEffects: Self.defaultNonEffectClasses + ) + try analyzer.add(request, withObserver: collector) + + let chunk = max(Int(signal.sampleRate), 1) + var position = 0 + while position < samples.count { + let count = min(chunk, samples.count - position) + guard let buffer = AVAudioPCMBuffer(pcmFormat: format, frameCapacity: AVAudioFrameCount(count)), + let destination = buffer.floatChannelData?[0] else { break } + buffer.frameLength = AVAudioFrameCount(count) + samples.withUnsafeBufferPointer { source in + destination.update(from: source.baseAddress! + position, count: count) + } + analyzer.analyze(buffer, atAudioFramePosition: AVAudioFramePosition(position)) + position += count + } + analyzer.completeAnalysis() + + if let error = collector.error { throw error } + let windows = collector.windows + guard !windows.isEmpty else { return empty } + return Activities( + voice: Self.activity(from: windows, score: \.voice, duration: signal.duration, interval: interval), + music: Self.activity(from: windows, score: \.music, duration: signal.duration, interval: interval), + effects: Self.activity(from: windows, score: \.effects, duration: signal.duration, interval: interval) + ) + } + + /// 窓ごとの得点を、一定間隔の時系列にする。各時刻は、それを覆う窓の最大値(中心から遠い窓ほど割り引く)。 + private static func activity( + from windows: [Window], score: KeyPath, duration: Double, interval: Double + ) -> VoiceActivity { + guard !windows.isEmpty else { return VoiceActivity(interval: interval, values: []) } + let count = Int((duration / interval).rounded(.up)) + 1 + var values = [Float](repeating: 0, count: count) + var covered = [Bool](repeating: false, count: count) + for window in windows where window.duration > 0 { + let half = window.duration / 2 + let center = window.start + half + let first = max(0, Int(((window.start) / interval).rounded(.up))) + let last = min(count - 1, Int(((window.start + window.duration) / interval).rounded(.down))) + guard last >= first else { continue } + for index in first...last { + let distance = abs(Double(index) * interval - center) / half + let weighted = window[keyPath: score] * Float(1 - 0.5 * min(distance, 1)) + values[index] = max(values[index], weighted) + covered[index] = true + } + } + // どの窓にも覆われない両端は、いちばん近い値で埋める。 + if let firstCovered = covered.firstIndex(of: true), let lastCovered = covered.lastIndex(of: true) { + for index in 0.. AudioSignal { AudioSignal(sampleRate: rate, channels: [samples]) } + private func constant(_ value: Float, seconds: Double = 10) -> VoiceActivity { + VoiceActivity(interval: 0.1, values: [Float](repeating: value, count: Int(seconds / 0.1) + 1)) + } + + /// 伴奏の和音 + 効果音(雑音の衝撃 2 回)。 + private func musicAndEffects(duration: Double) -> (music: [Float], effects: [Float]) { + let music = TestSignals.chord(duration: duration, frequencies: [262, 330, 392, 523], amplitude: 0.15) + let effects = TestSignals.add( + TestSignals.noiseBurst(total: duration, start: 1.0, length: 0.4, amplitude: 0.5, seed: 31), + TestSignals.noiseBurst(total: duration, start: 2.5, length: 0.3, amplitude: 0.5, seed: 32) + ) + return (music, effects) + } + + func testThreeComponentsAddUpToTheInput() { + let (music, effects) = musicAndEffects(duration: 4) + let input = TestSignals.add(TestSignals.voice(duration: 4), music, effects) + let result = VoiceSeparator().separateComponents(mono(input), voiceActivity: constant(0.9, seconds: 4), musicActivity: constant(0.9, seconds: 4)) + for index in stride(from: 0, to: input.count, by: 7) { + let total = result.voice.channels[0][index] + result.music.channels[0][index] + result.effects.channels[0][index] + XCTAssertEqual(total, input[index], accuracy: 1e-4) + } + } + + func testWithoutMusicActivityEverythingExceptTheVoiceIsEffects() { + let (music, effects) = musicAndEffects(duration: 3) + let input = TestSignals.add(music, effects) + // 和音は倍音が整数倍に並ぶので、声の度合いを与えないと声と誤られる。ここでは「声は無い」と教える。 + let result = VoiceSeparator().separateComponents(mono(input), voiceActivity: constant(0, seconds: 3)) + XCTAssertEqual(TestSignals.energy(result.music.channels[0]), 0, accuracy: 1e-9, "音楽の度合いが無ければ、音楽は無い") + XCTAssertEqual(result.music.channels.count, 1) + // 声が無い入力なので、効果音(声以外)は入力そのもの。 + XCTAssertGreaterThan(TestSignals.decibels(TestSignals.energy(result.effects.channels[0]) / TestSignals.energy(input)), -0.5) + } + + func testSteadyAccompanimentGoesToMusicAndSuddenSoundsToEffects() { + let duration = 4.0 + let (music, effects) = musicAndEffects(duration: duration) + let input = TestSignals.add(music, effects) + let result = VoiceSeparator().separateComponents( + mono(input), voiceActivity: constant(0, seconds: duration), musicActivity: constant(1, seconds: duration) + ) + + // 鳴り続ける和音のエネルギーの大半は音楽へ、衝撃の区間のエネルギーの大半は効果音へ入る。 + let steady = TestSignals.energy(music, from: 3.2, to: 3.9) + let steadyInMusic = TestSignals.energy(result.music.channels[0], from: 3.2, to: 3.9) + XCTAssertGreaterThan(steadyInMusic / steady, 0.7, "和音は音楽に残る(\(steadyInMusic / steady))") + let burst = TestSignals.energy(effects, from: 1.0, to: 1.4) + let burstInEffects = TestSignals.energy(result.effects.channels[0], from: 1.0, to: 1.4) + XCTAssertGreaterThan(burstInEffects / burst, 0.5, "衝撃は効果音に入る(\(burstInEffects / burst))") + XCTAssertLessThan(TestSignals.energy(result.effects.channels[0], from: 3.2, to: 3.9) / steady, 0.3, "和音は効果音にほとんど入らない") + } + + func testNoEffectEventMeansEverythingElseStaysInMusic() { + // 効果音が起きていないと分かっている(効果音の度合いが 0)なら、声以外はすべて音楽に残す。 + let duration = 3.0 + let (music, effects) = musicAndEffects(duration: duration) + let input = TestSignals.add(music, effects) + let result = VoiceSeparator().separateComponents( + mono(input), voiceActivity: constant(0, seconds: duration), + musicActivity: constant(1, seconds: duration), effectsActivity: constant(0, seconds: duration) + ) + XCTAssertLessThan(TestSignals.decibels(TestSignals.energy(result.effects.channels[0]) / TestSignals.energy(input)), -30) + } + + func testMixedKeepsOnlyTheChosenComponents() { + let (music, effects) = musicAndEffects(duration: 3) + let input = TestSignals.add(TestSignals.voice(duration: 3), music, effects) + let result = VoiceSeparator().separateComponents(mono(input), voiceActivity: constant(0.9, seconds: 3), musicActivity: constant(0.9, seconds: 3)) + + let none = result.mixed(voice: false, music: false, effects: false) + XCTAssertEqual(none.frameCount, input.count) + XCTAssertEqual(TestSignals.energy(none.channels[0]), 0, accuracy: 1e-12) + + let voiceOnly = result.mixed(voice: true, music: false, effects: false) + XCTAssertEqual(voiceOnly.channels[0], result.voice.channels[0]) + + let all = result.mixed(voice: true, music: true, effects: true) + for index in stride(from: 0, to: input.count, by: 11) { XCTAssertEqual(all.channels[0][index], input[index], accuracy: 1e-4) } + + // 声を除いた音 = 音楽 + 効果音。 + let withoutVoice = result.mixed(voice: false, music: true, effects: true) + for index in stride(from: 0, to: input.count, by: 11) { + XCTAssertEqual(withoutVoice.channels[0][index], result.music.channels[0][index] + result.effects.channels[0][index], accuracy: 1e-6) + } + } +} diff --git a/Packages/VoiceSeparationKit/Tests/VoiceSeparationTests/SpeechActivityDetectorTests.swift b/Packages/VoiceSeparationKit/Tests/VoiceSeparationTests/SpeechActivityDetectorTests.swift new file mode 100644 index 0000000..b69e66f --- /dev/null +++ b/Packages/VoiceSeparationKit/Tests/VoiceSeparationTests/SpeechActivityDetectorTests.swift @@ -0,0 +1,71 @@ +#if canImport(SoundAnalysis) +import AVFoundation +import XCTest +@testable import VoiceSeparation +import VoiceSeparationSoundAnalysis + +final class SpeechActivityDetectorTests: XCTestCase { + /// macOS 標準の `say` で話し声を作る(実際の音声合成なので、分類器が「話し声」と認める)。 + private func spokenSignal(_ text: String) throws -> AudioSignal { + let say = URL(fileURLWithPath: "/usr/bin/say") + try XCTSkipUnless(FileManager.default.isExecutableFile(atPath: say.path), "say が無い環境") + let url = FileManager.default.temporaryDirectory.appendingPathComponent("speech-\(UUID().uuidString).wav") + defer { try? FileManager.default.removeItem(at: url) } + let process = Process() + process.executableURL = say + process.arguments = ["-o", url.path, "--data-format=LEI16@44100", text] + try process.run() + process.waitUntilExit() + XCTAssertEqual(process.terminationStatus, 0) + + let file = try AVAudioFile(forReading: url) + let format = AVAudioFormat(commonFormat: .pcmFormatFloat32, sampleRate: file.fileFormat.sampleRate, channels: 1, interleaved: false)! + let buffer = AVAudioPCMBuffer(pcmFormat: format, frameCapacity: AVAudioFrameCount(file.length))! + try file.read(into: buffer) + return AudioSignal(sampleRate: format.sampleRate, channels: [Array(UnsafeBufferPointer(start: buffer.floatChannelData![0], count: Int(buffer.frameLength)))]) + } + + func testFindsSpeechAndIgnoresSoundEffects() throws { + let speech = try spokenSignal("Hello everyone. Welcome back to the channel. Today we are going to build something really cool together.") + let rate = speech.sampleRate + // 前の 4 秒は効果音(雑音の衝撃)だけ、そのあとが話し声、最後に再び効果音。 + let before = TestSignals.noiseBurst(total: 4, start: 0.5, length: 0.6, amplitude: 0.4, seed: 21) + let after = TestSignals.noiseBurst(total: 4, start: 1.0, length: 0.6, amplitude: 0.4, seed: 22) + let samples = before + speech.channels[0] + after + let signal = AudioSignal(sampleRate: rate, channels: [samples]) + let speechStart = 4.0 + let speechEnd = 4.0 + speech.duration + + let activity = try SpeechActivityDetector().detect(signal) + XCTAssertFalse(activity.values.isEmpty) + // 話し声の中ほどでは高く、効果音だけの所では低い。 + let inside = stride(from: speechStart + 1, to: speechEnd - 1, by: 0.5).compactMap { activity.value(at: $0) } + let outside = stride(from: 0.2, to: speechStart - 1, by: 0.5).compactMap { activity.value(at: $0) } + XCTAssertGreaterThan(inside.min() ?? 0, 0.5, "話し声の中は 0.5 より高い") + XCTAssertLessThan(outside.max() ?? 1, 0.3, "効果音だけの所は 0.3 より低い") + } + + func testVeryShortAudioReturnsNoInformationInsteadOfFailing() throws { + let signal = AudioSignal(sampleRate: 44_100, channels: [TestSignals.whiteNoise(duration: 0.2)]) + let activity = try SpeechActivityDetector().detect(signal) + XCTAssertNil(activity.value(at: 0.1), "窓より短い音では、判断できないので値を返さない") + } + + func testDetectorFeedsTheSeparatorToProtectEffectsBeforeTheVoice() throws { + let speech = try spokenSignal("The quick brown fox jumps over the lazy dog, and then it runs away through the forest.") + let rate = speech.sampleRate + let lead = 3.0 + // 先頭の効果音(声の前)が、声の除去で壊れないこと。 + let effect = TestSignals.noiseBurst(total: lead, start: 0.4, length: 0.8, amplitude: 0.4, seed: 5) + let samples = effect + speech.channels[0] + let signal = AudioSignal(sampleRate: rate, channels: [samples]) + let activity = try SpeechActivityDetector().detect(signal) + + let withActivity = VoiceSeparator().separate(signal, voiceActivity: activity) + let kept = TestSignals.decibels(TestSignals.energy(withActivity.background.channels[0], from: 0, to: lead) / TestSignals.energy(samples, from: 0, to: lead)) + XCTAssertGreaterThan(kept, -0.5, "声の前の効果音はそのまま残る(実測 \(kept) dB)") + let removed = TestSignals.decibels(TestSignals.energy(withActivity.background.channels[0], from: lead + 0.5, to: lead + speech.duration - 0.5) / TestSignals.energy(samples, from: lead + 0.5, to: lead + speech.duration - 0.5)) + XCTAssertLessThan(removed, -8, "声のある所では声が減る(実測 \(removed) dB)") + } +} +#endif diff --git a/Packages/VoiceSeparationKit/Tests/VoiceSeparationTests/TestSignals.swift b/Packages/VoiceSeparationKit/Tests/VoiceSeparationTests/TestSignals.swift new file mode 100644 index 0000000..57affba --- /dev/null +++ b/Packages/VoiceSeparationKit/Tests/VoiceSeparationTests/TestSignals.swift @@ -0,0 +1,108 @@ +import Foundation +@testable import VoiceSeparation + +/// テスト用の決まった乱数(再現できるように、種から同じ列を出す)。 +struct SeededNoise { + private var state: UInt64 + init(seed: UInt64) { state = seed } + /// -1...1 の一様乱数。 + mutating func next() -> Float { + state = state &* 6364136223846793005 &+ 1442695040888963407 + return Float(state >> 40) / Float(1 << 23) - 1 + } +} + +enum TestSignals { + static let sampleRate = 44_100.0 + + /// 母音のような声: 基本周波数が `startPitch` から `endPitch` へ動き、ビブラートが乗り、 + /// 音節ごとに強弱がつく。倍音の強さには、二つの山(フォルマント)を付けてある。 + static func voice( + duration: Double, startPitch: Double = 120, endPitch: Double = 180, amplitude: Float = 0.3, highestHarmonic: Double = 5_500 + ) -> [Float] { + let count = Int(duration * sampleRate) + var samples = [Float](repeating: 0, count: count) + var phase = 0.0 + for index in 0.. [Float] { + (0.. [Float] { + var noise = SeededNoise(seed: seed) + return (0.. [Float] { + var noise = SeededNoise(seed: seed) + var samples = [Float](repeating: 0, count: Int(total * sampleRate)) + let first = Int(start * sampleRate) + for offset in 0.. [Float] { + var samples = [Float](repeating: 0, count: Int(total * sampleRate)) + let first = Int(start * sampleRate) + for offset in 0.. [Float] { + let count = signals.map(\.count).max() ?? 0 + var result = [Float](repeating: 0, count: count) + for signal in signals { for index in 0.. Double { + let low = max(0, Int(start * sampleRate)) + let high = min(samples.count, end.isFinite ? Int(end * sampleRate) : samples.count) + guard high > low else { return 0 } + var sum = 0.0 + for index in low.. Double { 10 * log10(max(ratio, 1e-12)) } + + /// `signal` を `reference` に近づけたときの誤差(SDR、dB)。大きいほど `reference` に近い。 + static func sdr(_ signal: [Float], reference: [Float], from start: Double = 0, to end: Double = .infinity) -> Double { + let difference = zip(signal, reference).map { $0 - $1 } + return decibels(energy(reference, from: start, to: end) / energy(difference, from: start, to: end)) + } +} diff --git a/Packages/VoiceSeparationKit/Tests/VoiceSeparationTests/VoiceSeparatorTests.swift b/Packages/VoiceSeparationKit/Tests/VoiceSeparationTests/VoiceSeparatorTests.swift new file mode 100644 index 0000000..0d1ef83 --- /dev/null +++ b/Packages/VoiceSeparationKit/Tests/VoiceSeparationTests/VoiceSeparatorTests.swift @@ -0,0 +1,170 @@ +import XCTest +@testable import VoiceSeparation + +final class FFTTests: XCTestCase { + func testSinusoidAppearsInTheExpectedBin() { + let size = 1024 + let plan = FFTPlan(size: size) + var real = (0.. AudioSignal { AudioSignal(sampleRate: rate, channels: [samples]) } + + func testTracksTheMovingPitchOfASyntheticVoice() { + let voice = TestSignals.voice(duration: 3, startPitch: 120, endPitch: 180) + let result = VoiceSeparator().separate(mono(voice)) + // 声のある枠だけで、真の高さ(ビブラート込み)との差を見る。 + var errors: [Double] = [] + for (index, time) in result.pitch.times.enumerated() where result.pitch.frequencies[index] > 0 && time > 0.2 && time < 2.8 { + let base = 120 + 60 * (time / 3) + errors.append(abs(Double(result.pitch.frequencies[index]) - base) / base) + } + XCTAssertGreaterThan(errors.count, 40, "声のある枠が十分に見つかる") + errors.sort() + XCTAssertLessThan(errors[errors.count / 2], 0.03, "高さの中央値のずれは 3% 以内") + } + + func testTracksAVoiceWhoseEnergyIsOnlyInTheFirstFewHarmonics() { + // 高い倍音がほとんど無い声(低い男声など)。全部の倍音の平均で声らしさを測ると、薄まって、 + // 本来の 4 倍の高さ(倍音の数が少ない候補)に取り違える。 + let voice = TestSignals.voice(duration: 3, startPitch: 105, endPitch: 112, highestHarmonic: 650) + let result = VoiceSeparator().separate(mono(voice)) + var wrong = 0 + var voiced = 0 + for (index, time) in result.pitch.times.enumerated() where time > 0.2 && time < 2.8 && result.pitch.frequencies[index] > 0 { + voiced += 1 + if abs(Double(result.pitch.frequencies[index]) - 108) / 108 > 0.1 { wrong += 1 } + } + XCTAssertGreaterThan(voiced, 40) + XCTAssertLessThan(Double(wrong) / Double(max(voiced, 1)), 0.05, "高さの取り違えは 5% 未満(\(wrong)/\(voiced))") + let remaining = TestSignals.decibels(TestSignals.energy(result.background.channels[0], from: 0.3, to: 2.7) / TestSignals.energy(voice, from: 0.3, to: 2.7)) + XCTAssertLessThan(remaining, -12, "声が 12dB 以上減る(実測 \(remaining) dB)") + } + + func testRemovesASyntheticVoice() { + let voice = TestSignals.voice(duration: 3) + let result = VoiceSeparator().separate(mono(voice)) + let remaining = TestSignals.decibels(TestSignals.energy(result.background.channels[0], from: 0.3, to: 2.7) / TestSignals.energy(voice, from: 0.3, to: 2.7)) + XCTAssertLessThan(remaining, -15, "声のエネルギーが 15dB 以上減る(実測 \(remaining) dB)") + } + + func testVoiceAndBackgroundAddUpToTheInput() { + let input = TestSignals.add(TestSignals.voice(duration: 2), TestSignals.noiseBurst(total: 2, start: 0.8, length: 0.4)) + let result = VoiceSeparator().separate(mono(input)) + for index in 0.. Date: Fri, 6 Nov 2026 01:54:26 +0900 Subject: [PATCH 3/7] =?UTF-8?q?feat(musicvideo):=20=E7=B4=A0=E6=9D=90?= =?UTF-8?q?=E5=8B=95=E7=94=BB=E3=81=AE=E9=9F=B3=E5=A3=B0=E3=83=9F=E3=83=83?= =?UTF-8?q?=E3=82=AF=E3=82=B9=E3=83=BB=E3=81=A4=E3=81=AA=E3=81=8E=E7=9B=AE?= =?UTF-8?q?=E3=83=8E=E3=82=A4=E3=82=BA=E8=BB=BD=E6=B8=9B=E3=83=BB=E6=88=90?= =?UTF-8?q?=E5=88=86=E5=88=86=E9=9B=A2=E5=90=88=E6=88=90=E3=82=92=E8=BF=BD?= =?UTF-8?q?=E5=8A=A0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ArkServer.xcodeproj/project.pbxproj | 21 ++ .../MusicVideo/Models/MusicVideoTuning.swift | 122 ++++++++++ .../Services/MusicVideoComposer.swift | 221 ++++++++++++++++- .../Services/SourceAudioSeparator.swift | 227 ++++++++++++++++++ 4 files changed, 583 insertions(+), 8 deletions(-) create mode 100644 ArkServer/Features/MusicVideo/Services/SourceAudioSeparator.swift diff --git a/ArkServer.xcodeproj/project.pbxproj b/ArkServer.xcodeproj/project.pbxproj index 052b55b..da83817 100644 --- a/ArkServer.xcodeproj/project.pbxproj +++ b/ArkServer.xcodeproj/project.pbxproj @@ -9,6 +9,8 @@ /* Begin PBXBuildFile section */ 25959AC32E97F6E7003FA43E /* Swifter in Frameworks */ = {isa = PBXBuildFile; productRef = 25959AC22E97F6E7003FA43E /* Swifter */; }; 25959AD32E98000000000012 /* MediaServerKit in Frameworks */ = {isa = PBXBuildFile; productRef = 25959AD22E98000000000011 /* MediaServerKit */; }; + 25959AD72E98000000000023 /* VoiceSeparation in Frameworks */ = {isa = PBXBuildFile; productRef = 25959AD52E98000000000021 /* VoiceSeparation */; }; + 25959AD82E98000000000024 /* VoiceSeparationSoundAnalysis in Frameworks */ = {isa = PBXBuildFile; productRef = 25959AD62E98000000000022 /* VoiceSeparationSoundAnalysis */; }; /* End PBXBuildFile section */ /* Begin PBXContainerItemProxy section */ @@ -72,6 +74,8 @@ files = ( 25959AC32E97F6E7003FA43E /* Swifter in Frameworks */, 25959AD32E98000000000012 /* MediaServerKit in Frameworks */, + 25959AD72E98000000000023 /* VoiceSeparation in Frameworks */, + 25959AD82E98000000000024 /* VoiceSeparationSoundAnalysis in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -142,6 +146,8 @@ packageProductDependencies = ( 25959AC22E97F6E7003FA43E /* Swifter */, 25959AD22E98000000000011 /* MediaServerKit */, + 25959AD52E98000000000021 /* VoiceSeparation */, + 25959AD62E98000000000022 /* VoiceSeparationSoundAnalysis */, ); productName = ArkServer; productReference = 25959A8D2E97F5E5003FA43E /* ArkServer.app */; @@ -228,6 +234,7 @@ packageReferences = ( 25959AC02E97F6CD003FA43E /* XCRemoteSwiftPackageReference "swifter" */, 25959AD12E98000000000010 /* XCLocalSwiftPackageReference "Packages/MediaServerKit" */, + 25959AD42E98000000000020 /* XCLocalSwiftPackageReference "Packages/VoiceSeparationKit" */, ); preferredProjectObjectVersion = 77; productRefGroup = 25959A8E2E97F5E5003FA43E /* Products */; @@ -617,6 +624,10 @@ isa = XCLocalSwiftPackageReference; relativePath = Packages/MediaServerKit; }; + 25959AD42E98000000000020 /* XCLocalSwiftPackageReference "Packages/VoiceSeparationKit" */ = { + isa = XCLocalSwiftPackageReference; + relativePath = Packages/VoiceSeparationKit; + }; /* End XCLocalSwiftPackageReference section */ /* Begin XCRemoteSwiftPackageReference section */ @@ -641,6 +652,16 @@ package = 25959AD12E98000000000010 /* XCLocalSwiftPackageReference "Packages/MediaServerKit" */; productName = MediaServerKit; }; + 25959AD52E98000000000021 /* VoiceSeparation */ = { + isa = XCSwiftPackageProductDependency; + package = 25959AD42E98000000000020 /* XCLocalSwiftPackageReference "Packages/VoiceSeparationKit" */; + productName = VoiceSeparation; + }; + 25959AD62E98000000000022 /* VoiceSeparationSoundAnalysis */ = { + isa = XCSwiftPackageProductDependency; + package = 25959AD42E98000000000020 /* XCLocalSwiftPackageReference "Packages/VoiceSeparationKit" */; + productName = VoiceSeparationSoundAnalysis; + }; /* End XCSwiftPackageProductDependency section */ }; rootObject = 25959A852E97F5E5003FA43E /* Project object */; diff --git a/ArkServer/Features/MusicVideo/Models/MusicVideoTuning.swift b/ArkServer/Features/MusicVideo/Models/MusicVideoTuning.swift index 2fcf554..f8d8bd2 100644 --- a/ArkServer/Features/MusicVideo/Models/MusicVideoTuning.swift +++ b/ArkServer/Features/MusicVideo/Models/MusicVideoTuning.swift @@ -250,16 +250,138 @@ nonisolated enum MusicVideoTransition: String, Codable, CaseIterable, Hashable, } } +/// 素材動画の元の音を、音楽に重ねて入れるか。入れるときの大きさ。 +nonisolated enum SourceAudioLevel: String, Codable, CaseIterable, Hashable, Sendable { + case off + case low + case medium + case full + + var displayName: String { + switch self { + case .off: return "入れない" + case .low: return "小さめ" + case .medium: return "中くらい" + case .full: return "音楽と同じ" + } + } + + /// 素材の音に掛ける音量(音楽は 1)。0 なら素材の音を入れない。 + var volume: Float { + switch self { + case .off: return 0 + case .low: return 0.3 + case .medium: return 0.6 + case .full: return 1 + } + } + + var summary: String { + switch self { + case .off: return "音楽だけを流します.素材動画の音は入れません." + case .low: return "音楽に、素材動画の音を小さく重ねます." + case .medium: return "音楽に、素材動画の音を中くらいの大きさで重ねます." + case .full: return "音楽と同じ大きさで、素材動画の音を重ねます.音楽が聞き取りにくくなることがあります." + } + } +} + +/// 素材動画の音のうち、残す成分(音楽・声・効果音の組み合わせ)。「素材の音」を入れるときだけ効く。 +/// +/// 3つとも残すなら、素材の音をそのまま使う(分ける処理はしない)。声は倍音を見つけて取り除くので、比較的よく分かれる。 +/// 音楽と効果音の区別は、鳴り続けているか・効果音として認識された区間か、で見分けるだけなので、おおまか。 +nonisolated struct SourceAudioParts: OptionSet, Codable, Hashable, Sendable { + let rawValue: Int + + static let music = SourceAudioParts(rawValue: 1 << 0) + static let voice = SourceAudioParts(rawValue: 1 << 1) + static let effects = SourceAudioParts(rawValue: 1 << 2) + static let all: SourceAudioParts = [.music, .voice, .effects] + + /// 画面に並べる順番と名前。 + static let choices: [(part: SourceAudioParts, name: String)] = [ + (.music, "音楽"), (.voice, "声"), (.effects, "効果音"), + ] + + /// 分ける処理が要るか。全部残すなら、素材の音をそのまま使えるので不要。 + var needsSeparation: Bool { !isEmpty && self != .all } + + var summary: String { + if isEmpty { return "素材の音は入れません." } + if self == .all { return "素材動画の音を、そのまま入れます." } + var text = "選んだ成分だけを残します." + if !contains(.voice) { text += "声は、倍音を見つけて取り除きます." } + text += "音楽と効果音の見分けは、鳴り続けているか・効果音として認識された区間か、で判断するおおまかなものです." + text += "初めて使うカットは、音を調べるぶん少し時間がかかります." + return text + } + + // 保存は、名前の並びにする(ビットの意味が変わっても読めるように)。 + private static let names: [(part: SourceAudioParts, name: String)] = [(.music, "music"), (.voice, "voice"), (.effects, "effects")] + + init(rawValue: Int) { self.rawValue = rawValue } + + init(from decoder: Decoder) throws { + let stored = try decoder.singleValueContainer().decode([String].self) + self = Self.names.reduce(into: []) { result, entry in + if stored.contains(entry.name) { result.insert(entry.part) } + } + } + + func encode(to encoder: Encoder) throws { + var container = encoder.singleValueContainer() + try container.encode(Self.names.filter { contains($0.part) }.map(\.name)) + } +} + /// 見た目と音に効く調整項目。カット割りは変わらず、合成だけをやり直す。 nonisolated struct MusicVideoLookTuning: Codable, Equatable, Sendable { var fitMode: MusicVideoFitMode = .fill var transition: MusicVideoTransition = .cut /// 映像と音の、最初と最後のフェード(秒)。0 ならフェードしない。 var fadeSeconds: Double = 0 + /// 素材動画の元の音を入れるか。音楽の音量は変えず、その上に重ねる。 + var sourceAudio: SourceAudioLevel = .off + /// 素材の音のうち残す成分。`sourceAudio` が `.off` のときは使わない。 + var sourceParts: SourceAudioParts = .all static let fadeChoices: [Double] = [0, 0.5, 1, 2] } +nonisolated extension MusicVideoLookTuning { + private enum CodingKeys: String, CodingKey { + case fitMode, transition, fadeSeconds, sourceAudio, sourceParts + /// 以前の保存データにあった項目(読むだけ)。`remove` なら、声以外を残す。 + case sourceVoice + } + + /// 項目が足りない古い保存データでも、読めた分は使い、残りは既定値にする。 + init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + let defaults = MusicVideoLookTuning() + fitMode = try container.decodeIfPresent(MusicVideoFitMode.self, forKey: .fitMode) ?? defaults.fitMode + transition = try container.decodeIfPresent(MusicVideoTransition.self, forKey: .transition) ?? defaults.transition + fadeSeconds = try container.decodeIfPresent(Double.self, forKey: .fadeSeconds) ?? defaults.fadeSeconds + sourceAudio = try container.decodeIfPresent(SourceAudioLevel.self, forKey: .sourceAudio) ?? defaults.sourceAudio + if let parts = try container.decodeIfPresent(SourceAudioParts.self, forKey: .sourceParts) { + sourceParts = parts + } else if try container.decodeIfPresent(String.self, forKey: .sourceVoice) == "remove" { + sourceParts = SourceAudioParts.all.subtracting(.voice) + } else { + sourceParts = defaults.sourceParts + } + } + + func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(fitMode, forKey: .fitMode) + try container.encode(transition, forKey: .transition) + try container.encode(fadeSeconds, forKey: .fadeSeconds) + try container.encode(sourceAudio, forKey: .sourceAudio) + try container.encode(sourceParts, forKey: .sourceParts) + } +} + /// 曲のうち、映像にする範囲(秒)。 nonisolated struct MusicRange: Equatable, Sendable { var start: Double diff --git a/ArkServer/Features/MusicVideo/Services/MusicVideoComposer.swift b/ArkServer/Features/MusicVideo/Services/MusicVideoComposer.swift index 4198776..ce90825 100644 --- a/ArkServer/Features/MusicVideo/Services/MusicVideoComposer.swift +++ b/ArkServer/Features/MusicVideo/Services/MusicVideoComposer.swift @@ -84,13 +84,15 @@ nonisolated struct MusicVideoComposer: Sendable { /// - look: 画面の合わせ方・切り替え効果・フェード。既定(画面いっぱい・そのまま切り替え・フェードなし)では、 /// 映像トラックを1本だけ使う。 /// - audioStart: 音楽ファイルの何秒目を、映像の 0 秒に合わせるか(曲の一部だけを使うとき)。 + /// - audioSeparator: 素材の音から一部の成分だけを残すとき(`look.sourceParts` が全部ではない)に使う。分けた音の保存先を持つ。 func makeComposition( plan: CutPlan, sourceURLs: [UUID: URL], audioURL: URL, render: MusicVideoRenderSettings, look: MusicVideoLookTuning = MusicVideoLookTuning(), - audioStart: Double = 0 + audioStart: Double = 0, + audioSeparator: SourceAudioSeparator = .standard ) async throws -> MusicVideoComposition { guard !plan.cuts.isEmpty else { throw MusicVideoComposerError.emptyPlan } @@ -105,13 +107,34 @@ nonisolated struct MusicVideoComposer: Sendable { placement = try await placeSingleTrack(plan: plan, sourceURLs: sourceURLs, render: render, look: look, fade: fade, into: composition) } - let audioMix = try await addAudio( + // 音楽を先に入れる(音声トラックの先頭が音楽)。素材の音は、その上に重ねる。 + var audioParameters: [AVMutableAudioMixInputParameters] = [] + if let musicParameters = try await addAudio( from: audioURL, to: composition, duration: Self.time(plan.duration), startOffset: audioStart, fade: fade - ) + ) { + audioParameters.append(musicParameters) + } + if let sourceParameters = try await addSourceAudio( + plan: plan, + sourceURLs: sourceURLs, + volume: look.sourceAudio.volume, + fade: fade, + parts: look.sourceParts, + audioSeparator: audioSeparator, + into: composition + ) { + audioParameters.append(sourceParameters) + } + var audioMix: AVAudioMix? + if !audioParameters.isEmpty { + let mix = AVMutableAudioMix() + mix.inputParameters = audioParameters + audioMix = mix + } // 音声のほうが長いときも、映像の指示が全体を覆うように、最後の区間を合成の終わりまで延ばす。 var segments = placement.segments @@ -443,14 +466,14 @@ nonisolated struct MusicVideoComposer: Sendable { ) } - /// 音楽を映像の 0 秒に合わせて入れる。`fade` が 0 より大きければ、最初と最後で音量を 0↔1 に変える。 + /// 音楽を映像の 0 秒に合わせて入れる。`fade` が 0 より大きければ、最初と最後で音量を 0↔1 に変える指定を返す。 private func addAudio( from url: URL, to composition: AVMutableComposition, duration: CMTime, startOffset: Double, fade: Double - ) async throws -> AVAudioMix? { + ) async throws -> AVMutableAudioMixInputParameters? { let asset = AVURLAsset(url: url) guard let sourceTrack = try await asset.loadTracks(withMediaType: .audio).first else { throw MusicVideoComposerError.noAudioTrack @@ -481,9 +504,191 @@ nonisolated struct MusicVideoComposer: Sendable { toEndVolume: 0, timeRange: CMTimeRange(start: CMTimeSubtract(length, fadeTime), duration: fadeTime) ) - let mix = AVMutableAudioMix() - mix.inputParameters = [parameters] - return mix + return parameters + } + + /// カットのつなぎ目の前後で、素材の音を 0 まで絞る時間(秒)。音が飛ぶ所で出る「ぷつっ」という雑音を防ぐ。 + /// AVFoundation の音量は約 30ms より速く変えられない(これより短いと 0 まで下がりきらない)ので、その長さにする。 + private static let sourceAudioSeam = 0.03 + + /// 各カットの素材の音を、映像と同じ位置に入れる。`volume` が 0 なら何も入れない。 + /// + /// 映像と同じ素材の位置を使うので、クロスフェードでも映像と音は合ったまま。 + /// 音声トラックを持たない素材のカットは、無音になる。 + /// 最初と最後のフェード(`fade`)と、カットのつなぎ目の絞りが重ならないよう、フェードの間は絞りを入れない。 + private func addSourceAudio( + plan: CutPlan, + sourceURLs: [UUID: URL], + volume: Float, + fade: Double, + parts: SourceAudioParts, + audioSeparator: SourceAudioSeparator, + into composition: AVMutableComposition + ) async throws -> AVMutableAudioMixInputParameters? { + // 音量が 0 か、残す成分が無ければ、素材の音は入れない。 + guard volume > 0, !parts.isEmpty else { return nil } + guard let audioTrack = composition.addMutableTrack( + withMediaType: .audio, + preferredTrackID: kCMPersistentTrackID_Invalid + ) else { + throw MusicVideoComposerError.cannotCreateTrack + } + + // 素材の音声トラックは、元のアセットが解放されると使えなくなるので、アセットごと持ち続ける。 + struct SourceAudio { + let asset: AVURLAsset + let track: AVAssetTrack? + let audioRange: CMTimeRange + /// 映像側が素材の終わりに収めるときの基準。音も同じだけずらして、映像と音を合わせる。 + let videoRange: CMTimeRange + } + var sources: [UUID: SourceAudio] = [:] + + func loadedAudio(for videoID: UUID) async throws -> SourceAudio { + if let known = sources[videoID] { return known } + guard let url = sourceURLs[videoID] else { throw MusicVideoComposerError.missingSource(videoID) } + let asset = AVURLAsset(url: url) + let videoRange = try await asset.loadTracks(withMediaType: .video).first?.load(.timeRange) + ?? CMTimeRange(start: .zero, duration: .positiveInfinity) + let track = try await asset.loadTracks(withMediaType: .audio).first + let audioRange = try await track?.load(.timeRange) ?? .zero + let loaded = SourceAudio(asset: asset, track: track, audioRange: audioRange, videoRange: videoRange) + sources[videoID] = loaded + return loaded + } + + let seam = Self.time(Self.sourceAudioSeam) + let total = plan.duration + let fadeTime = Self.time(fade) + let parameters = AVMutableAudioMixInputParameters(track: audioTrack) + parameters.setVolume(volume, at: .zero) + + // 最初と最後のフェード。 + if fade > 0 { + parameters.setVolumeRamp(fromStartVolume: 0, toEndVolume: volume, timeRange: CMTimeRange(start: .zero, duration: fadeTime)) + parameters.setVolumeRamp( + fromStartVolume: volume, + toEndVolume: 0, + timeRange: CMTimeRange(start: CMTimeSubtract(Self.time(total), fadeTime), duration: fadeTime) + ) + } + + /// トラックに入れる音ひとつぶん。 + struct Piece { + let sourceURL: URL + let track: AVAssetTrack + let sourceRange: CMTimeRange + let timelineStart: CMTime + } + var pieces: [Piece] = [] + + for (index, cut) in plan.cuts.enumerated() { + try Task.checkCancellation() + let source = try await loadedAudio(for: cut.videoID) + + let start = Self.time(cut.timelineStart) + let end = Self.time(cut.timelineEnd) + let length = CMTimeSubtract(end, start) + guard length > .zero else { continue } + + // 映像と同じ素材の位置を使う(素材の終わりを越えるときは、映像と同じだけ手前へずらす)。 + var sourceStart = Self.time(cut.sourceStart) + if CMTimeAdd(sourceStart, length) > source.videoRange.end { + sourceStart = max(source.videoRange.start, CMTimeSubtract(source.videoRange.end, length)) + } + + if let track = source.track { + // 音声が映像より短い素材は、音のある範囲だけを入れる(残りは無音)。 + let audioStart = max(sourceStart, source.audioRange.start) + let skipped = CMTimeSubtract(audioStart, sourceStart) + let available = min(CMTimeSubtract(length, skipped), CMTimeSubtract(source.audioRange.end, audioStart)) + if available > .zero { + pieces.append(Piece( + sourceURL: source.asset.url, track: track, + sourceRange: CMTimeRange(start: audioStart, duration: available), + timelineStart: CMTimeAdd(start, skipped) + )) + } + } + + // つなぎ目(カットの頭)の前後を一瞬だけ絞る。前後のカットが短すぎるときと、フェードの間は入れない。 + guard index > 0 else { continue } + let previousLength = plan.cuts[index - 1].duration + let seamSeconds = Self.sourceAudioSeam + guard cut.duration > seamSeconds * 2, previousLength > seamSeconds * 2 else { continue } + let seamStart = cut.timelineStart - seamSeconds + let seamEnd = cut.timelineStart + seamSeconds + guard fade == 0 || (seamStart >= fade && seamEnd <= total - fade) else { continue } + parameters.setVolumeRamp( + fromStartVolume: volume, + toEndVolume: 0, + timeRange: CMTimeRange(start: CMTimeSubtract(start, seam), duration: seam) + ) + parameters.setVolumeRamp( + fromStartVolume: 0, + toEndVolume: volume, + timeRange: CMTimeRange(start: start, duration: seam) + ) + } + + // 一部の成分だけを残すときは、使う範囲ごとに、その成分だけの音を作り、それを入れる。 + guard parts.needsSeparation else { + for piece in pieces { + try audioTrack.insertTimeRange(piece.sourceRange, of: piece.track, at: piece.timelineStart) + } + return parameters + } + audioSeparator.trimCache() + let processed = try await separateAudio(from: pieces.map { ($0.sourceURL, $0.sourceRange) }, parts: parts, using: audioSeparator) + for (piece, url) in zip(pieces, processed) { + // 分けられなかった範囲は、選んでいない成分が混ざらないよう、無音にする。 + guard let url else { continue } + let asset = AVURLAsset(url: url) + guard let track = try await asset.loadTracks(withMediaType: .audio).first else { continue } + let available = min(piece.sourceRange.duration, try await asset.load(.duration)) + guard available > .zero else { continue } + try audioTrack.insertTimeRange(CMTimeRange(start: .zero, duration: available), of: track, at: piece.timelineStart) + } + return parameters + } + + /// 同時に分ける範囲の数。多すぎると、音の解析でメモリと CPU を使い切る。 + private static let separationConcurrency = 4 + + /// 各範囲から、選んだ成分だけを残したファイルを作る。失敗した範囲は nil(キャンセルのときは投げ直す)。順序は入力と同じ。 + private func separateAudio( + from ranges: [(url: URL, range: CMTimeRange)], + parts: SourceAudioParts, + using separator: SourceAudioSeparator + ) async throws -> [URL?] { + var results = [URL?](repeating: nil, count: ranges.count) + try await withThrowingTaskGroup(of: (Int, URL?).self) { group in + var next = 0 + func addNext() { + guard next < ranges.count else { return } + let index = next + next += 1 + let item = ranges[index] + group.addTask { + do { + let url = try await separator.audio( + source: item.url, start: item.range.start.seconds, duration: item.range.duration.seconds, parts: parts + ) + return (index, url) + } catch is CancellationError { + throw CancellationError() + } catch { + return (index, nil) + } + } + } + for _ in 0.. URL { + let output = cacheDirectory.appendingPathComponent( + "\(cacheKey(source: source, start: start, duration: duration, parts: parts)).caf" + ) + if FileManager.default.fileExists(atPath: output.path) { + // 使われたことが分かるよう、更新日時を新しくする(古いファイルの整理で消されないように)。 + try? FileManager.default.setAttributes([.modificationDate: Date()], ofItemAtPath: output.path) + return output + } + try Task.checkCancellation() + + let paddedStart = max(0, start - context) + let signal = try await readAudio(from: source, start: paddedStart, duration: (start - paddedStart) + duration + context) + try Task.checkCancellation() + + // 声・音楽・効果音の度合いが調べられなかったときは、その情報なしで分ける(声は取り除くほうを優先し、 + // 音楽の度合いが無ければ、声以外はすべて効果音として扱う)。 + let activities = try? SpeechActivityDetector().detectActivities(signal.audio) + let components = VoiceSeparator().separateComponents( + signal.audio, + voiceActivity: activities?.voice, + musicActivity: activities?.music, + effectsActivity: activities?.effects + ) + let selected = components.mixed( + voice: parts.contains(.voice), music: parts.contains(.music), effects: parts.contains(.effects) + ) + try Task.checkCancellation() + + // 読み出した範囲のうち、実際に使う部分だけを切り出す。 + let rate = signal.audio.sampleRate + let firstFrame = max(0, Int(((start - signal.startTime) * rate).rounded())) + let frameCount = max(0, min(Int((duration * rate).rounded()), selected.frameCount - firstFrame)) + guard frameCount > 0 else { throw SourceAudioSeparatorError.cannotRead("使う範囲に音がありません.") } + let channels = selected.channels.map { Array($0[firstFrame..<(firstFrame + frameCount)]) } + + try write(AudioSignal(sampleRate: rate, channels: channels), to: output) + return output + } + + // MARK: - 保存ファイルの整理 + + /// 保存ファイルの合計が `limitBytes` を超えていたら、古いものから消す。最近使ったもの(`keepRecent` 秒以内)は、 + /// いま再生中の映像が参照していることがあるので消さない。 + func trimCache(limitBytes: Int = 1_000_000_000, keepRecent: TimeInterval = 600) { + let keys: [URLResourceKey] = [.fileSizeKey, .contentModificationDateKey] + guard let urls = try? FileManager.default.contentsOfDirectory(at: cacheDirectory, includingPropertiesForKeys: keys) else { return } + var files: [(url: URL, size: Int, date: Date)] = urls.compactMap { url in + guard url.pathExtension == "caf", let values = try? url.resourceValues(forKeys: Set(keys)) else { return nil } + return (url, values.fileSize ?? 0, values.contentModificationDate ?? .distantPast) + } + var total = files.reduce(0) { $0 + $1.size } + guard total > limitBytes else { return } + files.sort { $0.date < $1.date } + let threshold = Date().addingTimeInterval(-keepRecent) + for file in files where total > limitBytes && file.date < threshold { + try? FileManager.default.removeItem(at: file.url) + total -= file.size + } + } + + // MARK: - 部品 + + private func cacheKey(source: URL, start: Double, duration: Double, parts: SourceAudioParts) -> String { + let values = try? source.resourceValues(forKeys: [.fileSizeKey, .contentModificationDateKey]) + let stamp = [ + source.path, + String(values?.fileSize ?? 0), + String(values?.contentModificationDate?.timeIntervalSince1970 ?? 0), + String(Int((start * 1000).rounded())), + String(Int((duration * 1000).rounded())), + String(parts.rawValue), + String(Self.algorithmVersion), + ].joined(separator: "|") + return SHA256.hash(data: Data(stamp.utf8)).map { String(format: "%02x", $0) }.joined() + } + + /// 読み出した音と、その先頭が素材の何秒目に当たるか。 + private struct ReadAudio { + var audio: AudioSignal + var startTime: Double + } + + /// 素材の音を、44.1kHz・ステレオ・浮動小数点で読み出す。 + private func readAudio(from url: URL, start: Double, duration: Double) async throws -> ReadAudio { + let asset = AVURLAsset(url: url) + guard let track = try await asset.loadTracks(withMediaType: .audio).first else { + throw SourceAudioSeparatorError.noAudioTrack + } + let reader: AVAssetReader + do { reader = try AVAssetReader(asset: asset) } catch { throw SourceAudioSeparatorError.cannotRead(error.localizedDescription) } + let output = AVAssetReaderTrackOutput( + track: track, + outputSettings: [ + AVFormatIDKey: kAudioFormatLinearPCM, + AVLinearPCMBitDepthKey: 32, + AVLinearPCMIsFloatKey: true, + AVLinearPCMIsBigEndianKey: false, + AVLinearPCMIsNonInterleaved: true, + AVSampleRateKey: Self.sampleRate, + AVNumberOfChannelsKey: 2, + ] + ) + output.alwaysCopiesSampleData = false + guard reader.canAdd(output) else { throw SourceAudioSeparatorError.cannotRead("読み出しを始められません.") } + reader.add(output) + reader.timeRange = CMTimeRange( + start: CMTime(seconds: start, preferredTimescale: 600), + duration: CMTime(seconds: duration, preferredTimescale: 600) + ) + guard reader.startReading() else { + throw SourceAudioSeparatorError.cannotRead(reader.error?.localizedDescription ?? "読み出しを始められません.") + } + + guard let format = AVAudioFormat(commonFormat: .pcmFormatFloat32, sampleRate: Self.sampleRate, channels: 2, interleaved: false) else { + throw SourceAudioSeparatorError.cannotRead("音声の形式を作れません.") + } + var left: [Float] = [] + var right: [Float] = [] + var firstTime: Double? + while let sampleBuffer = output.copyNextSampleBuffer() { + try Task.checkCancellation() + let frames = CMSampleBufferGetNumSamples(sampleBuffer) + guard frames > 0, let buffer = AVAudioPCMBuffer(pcmFormat: format, frameCapacity: AVAudioFrameCount(frames)) else { continue } + buffer.frameLength = AVAudioFrameCount(frames) + let status = CMSampleBufferCopyPCMDataIntoAudioBufferList( + sampleBuffer, at: 0, frameCount: Int32(frames), into: buffer.mutableAudioBufferList + ) + guard status == noErr, let channels = buffer.floatChannelData else { continue } + if firstTime == nil { firstTime = CMSampleBufferGetPresentationTimeStamp(sampleBuffer).seconds } + left.append(contentsOf: UnsafeBufferPointer(start: channels[0], count: frames)) + right.append(contentsOf: UnsafeBufferPointer(start: channels[1], count: frames)) + } + if reader.status == .failed { + throw SourceAudioSeparatorError.cannotRead(reader.error?.localizedDescription ?? "読み出しに失敗しました.") + } + guard !left.isEmpty else { throw SourceAudioSeparatorError.cannotRead("指定の範囲に音がありません.") } + return ReadAudio(audio: AudioSignal(sampleRate: Self.sampleRate, channels: [left, right]), startTime: firstTime ?? start) + } + + /// 16bit のステレオ PCM として保存する。書きかけのファイルが使われないよう、別名で書いてから名前を付ける。 + private func write(_ audio: AudioSignal, to url: URL) throws { + do { + try FileManager.default.createDirectory(at: cacheDirectory, withIntermediateDirectories: true) + let temporary = cacheDirectory.appendingPathComponent("tmp-\(UUID().uuidString).caf") + defer { try? FileManager.default.removeItem(at: temporary) } + guard let format = AVAudioFormat(commonFormat: .pcmFormatFloat32, sampleRate: audio.sampleRate, channels: 2, interleaved: false), + let buffer = AVAudioPCMBuffer(pcmFormat: format, frameCapacity: AVAudioFrameCount(audio.frameCount)), + let channels = buffer.floatChannelData else { + throw SourceAudioSeparatorError.cannotWrite("音声の形式を作れません.") + } + buffer.frameLength = AVAudioFrameCount(audio.frameCount) + for channel in 0..<2 { + let samples = audio.channels[min(channel, audio.channels.count - 1)] + samples.withUnsafeBufferPointer { channels[channel].update(from: $0.baseAddress!, count: samples.count) } + } + do { + let file = try AVAudioFile( + forWriting: temporary, + settings: [ + AVFormatIDKey: kAudioFormatLinearPCM, + AVSampleRateKey: audio.sampleRate, + AVNumberOfChannelsKey: 2, + AVLinearPCMBitDepthKey: 16, + AVLinearPCMIsFloatKey: false, + AVLinearPCMIsBigEndianKey: false, + ], + commonFormat: .pcmFormatFloat32, + interleaved: false + ) + try file.write(from: buffer) + } + // file の解放(書き込みの完了)後に名前を付ける。同時に同じ範囲を作った場合は、先にできたものを使う。 + if FileManager.default.fileExists(atPath: url.path) { return } + try FileManager.default.moveItem(at: temporary, to: url) + } catch let error as SourceAudioSeparatorError { + throw error + } catch { + throw SourceAudioSeparatorError.cannotWrite(error.localizedDescription) + } + } +} From 11c0a9347e690c22457ef2084c242be20b1cabc4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8E=9F=E3=80=80=E9=A2=AF=E7=99=BB?= Date: Fri, 6 Nov 2026 01:54:26 +0900 Subject: [PATCH 4/7] =?UTF-8?q?feat(musicvideo):=20=E7=B4=A0=E6=9D=90?= =?UTF-8?q?=E5=8B=95=E7=94=BB=E3=81=AE=E9=9F=B3=E9=87=8F=E3=81=A8=E6=AE=8B?= =?UTF-8?q?=E3=81=99=E9=9F=B3=E6=88=90=E5=88=86=E3=81=AE=E8=AA=BF=E6=95=B4?= =?UTF-8?q?UI=E3=82=92=E8=BF=BD=E5=8A=A0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../ViewModels/MusicVideoViewModel.swift | 2 ++ .../Views/MusicVideoTuningSections.swift | 26 +++++++++++++++++++ 2 files changed, 28 insertions(+) diff --git a/ArkServer/Features/MusicVideo/ViewModels/MusicVideoViewModel.swift b/ArkServer/Features/MusicVideo/ViewModels/MusicVideoViewModel.swift index 6ed8705..eb29bc1 100644 --- a/ArkServer/Features/MusicVideo/ViewModels/MusicVideoViewModel.swift +++ b/ArkServer/Features/MusicVideo/ViewModels/MusicVideoViewModel.swift @@ -668,6 +668,8 @@ final class MusicVideoViewModel: ObservableObject { private static func changedTitle(from old: MusicVideoLookTuning, to new: MusicVideoLookTuning) -> String { if old.fitMode != new.fitMode { return "画面の合わせ方" } if old.transition != new.transition { return "切り替え効果" } + if old.sourceAudio != new.sourceAudio { return "素材の音" } + if old.sourceParts != new.sourceParts { return "素材の音の成分" } return "フェード" } diff --git a/ArkServer/Features/MusicVideo/Views/MusicVideoTuningSections.swift b/ArkServer/Features/MusicVideo/Views/MusicVideoTuningSections.swift index 9a79d47..3474b1d 100644 --- a/ArkServer/Features/MusicVideo/Views/MusicVideoTuningSections.swift +++ b/ArkServer/Features/MusicVideo/Views/MusicVideoTuningSections.swift @@ -162,6 +162,27 @@ struct MusicVideoTuningSections: View { MusicVideoField(title: "切り替え効果", detail: viewModel.lookTuning.transition.summary) { MusicVideoChoices(options: MusicVideoTransition.allCases, title: \.displayName, selection: $viewModel.lookTuning.transition, minimumWidth: 100) } + MusicVideoField(title: "素材の音", detail: viewModel.lookTuning.sourceAudio.summary) { + MusicVideoChoices(options: SourceAudioLevel.allCases, title: \.displayName, selection: $viewModel.lookTuning.sourceAudio, minimumWidth: 100) + } + MusicVideoField(title: "残す音(素材)", detail: sourceAudioPartsDetail) { + HStack(spacing: 8) { + ForEach(SourceAudioParts.choices, id: \.name) { choice in + MusicVideoChoiceButton( + title: choice.name, + isSelected: viewModel.lookTuning.sourceParts.contains(choice.part) + ) { + // 組み合わせて選べる。押すたびに、入れる・外すを切り替える。 + if viewModel.lookTuning.sourceParts.contains(choice.part) { + viewModel.lookTuning.sourceParts.remove(choice.part) + } else { + viewModel.lookTuning.sourceParts.insert(choice.part) + } + } + } + } + } + .disabled(viewModel.lookTuning.sourceAudio == .off) MusicVideoFoldout(title: "映像と音のフェード", summary: viewModel.lookTuning.fadeSeconds == 0 ? "なし" : Self.seconds(viewModel.lookTuning.fadeSeconds)) { MusicVideoParameterBar( title: "最初と最後のフェード", options: MusicVideoLookTuning.fadeChoices, @@ -180,6 +201,11 @@ struct MusicVideoTuningSections: View { return text } + private var sourceAudioPartsDetail: String { + if viewModel.lookTuning.sourceAudio == .off { return "「素材の音」を入れると選べます." } + return viewModel.lookTuning.sourceParts.summary + } + private var fadeDetail: String { let seconds = viewModel.lookTuning.fadeSeconds if seconds == 0 { return "フェードしません.最初から最後まで、そのままの明るさと音量です." } From 3354f7a473c6b52e6ecee6a22ba1c93e9b7a9703 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8E=9F=E3=80=80=E9=A2=AF=E7=99=BB?= Date: Fri, 6 Nov 2026 01:54:26 +0900 Subject: [PATCH 5/7] =?UTF-8?q?test(musicvideo):=20=E7=B4=A0=E6=9D=90?= =?UTF-8?q?=E5=8B=95=E7=94=BB=E3=81=AE=E9=9F=B3=E5=A3=B0=E3=83=9F=E3=83=83?= =?UTF-8?q?=E3=82=AF=E3=82=B9=E3=83=BB=E6=88=90=E5=88=86=E5=88=86=E9=9B=A2?= =?UTF-8?q?=E3=83=BB=E8=A8=AD=E5=AE=9A=E4=BF=9D=E5=AD=98=E3=81=AE=E5=8D=98?= =?UTF-8?q?=E4=BD=93=E3=83=86=E3=82=B9=E3=83=88=E3=82=92=E8=BF=BD=E5=8A=A0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ArkServerTests/MusicVideoTuningTests.swift | 414 ++++++++++++++++++++- 1 file changed, 411 insertions(+), 3 deletions(-) diff --git a/ArkServerTests/MusicVideoTuningTests.swift b/ArkServerTests/MusicVideoTuningTests.swift index 64e6f65..d729b2a 100644 --- a/ArkServerTests/MusicVideoTuningTests.swift +++ b/ArkServerTests/MusicVideoTuningTests.swift @@ -382,6 +382,42 @@ struct MusicVideoTuningPreferencesTests { #expect(decoded.lookTuning == MusicVideoLookTuning()) } + @Test + func lookTuningSavedBeforeSourceAudioStillLoadsWithItOff() throws { + let legacy = #"{"cutStyle":"standard","lookTuning":{"fitMode":"fit","transition":"crossfade","fadeSeconds":1}}"# + let decoded = try JSONDecoder().decode(MusicVideoPreferences.self, from: Data(legacy.utf8)) + #expect(decoded.lookTuning.fitMode == .fit) + #expect(decoded.lookTuning.transition == .crossfade) + #expect(decoded.lookTuning.fadeSeconds == 1) + #expect(decoded.lookTuning.sourceAudio == .off) + #expect(decoded.lookTuning.sourceParts == .all) + } + + @Test + func theEarlierVoiceSettingIsReadAsTheMatchingParts() throws { + let removed = #"{"lookTuning":{"sourceAudio":"medium","sourceVoice":"remove"}}"# + let decoded = try JSONDecoder().decode(MusicVideoPreferences.self, from: Data(removed.utf8)) + #expect(decoded.lookTuning.sourceParts == [.music, .effects]) + let kept = #"{"lookTuning":{"sourceAudio":"medium","sourceVoice":"keep"}}"# + #expect(try JSONDecoder().decode(MusicVideoPreferences.self, from: Data(kept.utf8)).lookTuning.sourceParts == .all) + } + + @Test + func partsAreSavedAsNamesAndEmptyMeansNothing() throws { + var look = MusicVideoLookTuning() + look.sourceParts = [.voice, .effects] + let data = try JSONEncoder().encode(look) + let text = try #require(String(data: data, encoding: .utf8)) + #expect(text.contains(#""sourceParts":["voice","effects"]"#), "名前の並びで保存する(\(text))") + #expect(try JSONDecoder().decode(MusicVideoLookTuning.self, from: data).sourceParts == [.voice, .effects]) + + look.sourceParts = [] + #expect(try JSONDecoder().decode(MusicVideoLookTuning.self, from: JSONEncoder().encode(look)).sourceParts.isEmpty) + #expect(SourceAudioParts.all.needsSeparation == false, "全部残すなら、分けない") + #expect(SourceAudioParts([]).needsSeparation == false, "何も残さないなら、分ける必要もない") + #expect(SourceAudioParts([.voice]).needsSeparation) + } + @Test func tuningSurvivesASaveAndLoad() throws { var preferences = MusicVideoPreferences() @@ -392,6 +428,8 @@ struct MusicVideoTuningPreferencesTests { preferences.lookTuning.fitMode = .fit preferences.lookTuning.transition = .crossfade preferences.lookTuning.fadeSeconds = 1 + preferences.lookTuning.sourceAudio = .medium + preferences.lookTuning.sourceParts = [.voice, .effects] let data = try JSONEncoder().encode(preferences) let decoded = try JSONDecoder().decode(MusicVideoPreferences.self, from: data) @@ -456,6 +494,53 @@ private func audioRMS(of composed: MusicVideoComposition, from start: Double, le return count == 0 ? 0 : (sum / Double(count)).squareRoot() } +/// 合成した音の、`start` 秒から `length` 秒を `block` 秒ごとに区切ったピーク(絶対値の最大)。時刻は区切りの先頭。 +private func audioPeaks( + of composed: MusicVideoComposition, + from start: Double, + length: Double, + block: Double +) throws -> [(time: Double, peak: Float)] { + let sampleRate = 44_100.0 + let reader = try AVAssetReader(asset: composed.composition) + let output = AVAssetReaderAudioMixOutput( + audioTracks: composed.composition.tracks(withMediaType: .audio), + audioSettings: [ + AVFormatIDKey: kAudioFormatLinearPCM, + AVLinearPCMBitDepthKey: 32, + AVLinearPCMIsFloatKey: true, + AVLinearPCMIsBigEndianKey: false, + AVLinearPCMIsNonInterleaved: false, + AVSampleRateKey: sampleRate, + AVNumberOfChannelsKey: 1 + ] + ) + output.audioMix = composed.audioMix + reader.add(output) + reader.timeRange = CMTimeRange( + start: CMTime(seconds: start, preferredTimescale: 600), + duration: CMTime(seconds: length, preferredTimescale: 600) + ) + guard reader.startReading() else { throw reader.error ?? CocoaError(.fileReadUnknown) } + + var samples: [Float] = [] + var firstTime: Double? + while let buffer = output.copyNextSampleBuffer() { + if firstTime == nil { firstTime = CMSampleBufferGetPresentationTimeStamp(buffer).seconds } + guard let data = CMSampleBufferGetDataBuffer(buffer) else { continue } + let total = CMBlockBufferGetDataLength(data) + var bytes = [UInt8](repeating: 0, count: total) + CMBlockBufferCopyDataBytes(data, atOffset: 0, dataLength: total, destination: &bytes) + bytes.withUnsafeBytes { samples.append(contentsOf: $0.bindMemory(to: Float.self)) } + } + + let step = max(1, Int(block * sampleRate)) + let origin = firstTime ?? start + return stride(from: 0, to: samples.count - step, by: step).map { index in + (origin + Double(index) / sampleRate, samples[index.. MusicVideoComposition { try await step("compose") { - try await MusicVideoComposer().makeComposition( - plan: plan, sourceURLs: fixture.urls, audioURL: fixture.music, render: render, look: look, audioStart: audioStart + let separator = audioSeparator ?? SourceAudioSeparator(cacheDirectory: fixture.directory.appendingPathComponent("voice-cache")) + return try await MusicVideoComposer().makeComposition( + plan: plan, sourceURLs: fixture.urls, audioURL: fixture.music, render: render, look: look, + audioStart: audioStart, audioSeparator: separator ) } } @@ -753,6 +841,326 @@ struct MusicVideoLookCompositionTests { #expect(abs(fromThree.duration - 4) < 0.05) } + // MARK: 素材の元の音 + + /// 映像に、`samples`(モノラル 44.1kHz)の音を付けた動画を作る。素材の音が入ったかを調べるための素材。 + private func makeTestVideoWithAudio(at url: URL, duration: Double, samples: [Float]) async throws { + let directory = url.deletingLastPathComponent() + let videoURL = directory.appendingPathComponent("silent-\(UUID().uuidString).mp4") + let audioURL = directory.appendingPathComponent("tone-\(UUID().uuidString).wav") + defer { + try? FileManager.default.removeItem(at: videoURL) + try? FileManager.default.removeItem(at: audioURL) + } + try await makeTestVideo(at: videoURL, duration: duration) { _ in 120 } + try writeMonoWAV(samples: samples, sampleRate: 44_100, to: audioURL) + + let composition = AVMutableComposition() + for (sourceURL, mediaType) in [(videoURL, AVMediaType.video), (audioURL, .audio)] { + let asset = AVURLAsset(url: sourceURL) + let sourceTrack = try #require(try await asset.loadTracks(withMediaType: mediaType).first) + let track = try #require(composition.addMutableTrack(withMediaType: mediaType, preferredTrackID: kCMPersistentTrackID_Invalid)) + try track.insertTimeRange(CMTimeRange(start: .zero, duration: try await asset.load(.duration)), of: sourceTrack, at: .zero) + } + let session = try #require(AVAssetExportSession(asset: composition, presetName: AVAssetExportPresetPassthrough)) + try await session.export(to: url, as: .mov) + } + + private func tone(duration: Double, from toneStart: Double = 0, amplitude: Float = 0.4) -> [Float] { + let sampleRate = 44_100.0 + return (0.. SourceAudioFixture { + let base = try await makeFixture() + try writeMonoWAV(samples: [Float](repeating: 0, count: 8 * 44_100), sampleRate: 44_100, to: base.music) + let lateURL = base.directory.appendingPathComponent("late.mov") + let tonedURL = base.directory.appendingPathComponent("toned.mov") + try await step("late video") { try await makeTestVideoWithAudio(at: lateURL, duration: 8, samples: tone(duration: 8, from: 3)) } + try await step("toned video") { try await makeTestVideoWithAudio(at: tonedURL, duration: 8, samples: tone(duration: 8)) } + let late = UUID(), toned = UUID() + let urls = base.urls.merging([late: lateURL, toned: tonedURL]) { current, _ in current } + return SourceAudioFixture( + fixture: Fixture(directory: base.directory, dark: base.dark, bright: base.bright, portrait: base.portrait, urls: urls, music: base.music), + late: late, toned: toned, silent: base.dark + ) + } + + @Test + func sourceAudioIsLeftOutByDefault() async throws { + let sources = try await makeSourceAudioFixture() + defer { try? FileManager.default.removeItem(at: sources.fixture.directory) } + let plan = CutPlan(cuts: [plannedCut(sources.toned, from: 1, at: 0, length: 3)], duration: 3) + + let composed = try await compose(plan, fixture: sources.fixture, look: MusicVideoLookTuning()) + #expect(composed.audioMix == nil) + #expect(composed.composition.tracks(withMediaType: .audio).count == 1, "音楽の1本だけ") + #expect(try audioRMS(of: composed, from: 0.5, length: 1.5) < 0.01) + } + + @Test + func sourceAudioLevelsScaleTheOriginalSound() async throws { + let sources = try await makeSourceAudioFixture() + defer { try? FileManager.default.removeItem(at: sources.fixture.directory) } + let plan = CutPlan(cuts: [plannedCut(sources.toned, from: 1, at: 0, length: 3)], duration: 3) + + var levels: [SourceAudioLevel: Double] = [:] + for level in SourceAudioLevel.allCases { + var look = MusicVideoLookTuning() + look.sourceAudio = level + let composed = try await compose(plan, fixture: sources.fixture, look: look) + levels[level] = try audioRMS(of: composed, from: 0.5, length: 1.5) + } + // 振幅 0.4 の正弦波の RMS は約 0.28。「音楽と同じ」はその大きさがそのまま出る。 + let full = try #require(levels[.full]) + #expect(full > 0.24 && full < 0.32) + #expect(try #require(levels[.off]) < 0.01) + #expect(try #require(levels[.low]) > 0.06 && levels[.low]! < 0.11) + #expect(try #require(levels[.medium]) > 0.14 && levels[.medium]! < 0.2) + } + + @Test + func sourceAudioFollowsEachCutAndStaysInSyncWithTheVideo() async throws { + let sources = try await makeSourceAudioFixture() + defer { try? FileManager.default.removeItem(at: sources.fixture.directory) } + // 前半は素材の 0 秒から(無音の部分)、後半は 3.5 秒から(音のある部分)。 + let plan = CutPlan( + cuts: [ + plannedCut(sources.late, from: 0, at: 0, length: 1.5), + plannedCut(sources.late, from: 3.5, at: 1.5, length: 1.5) + ], + duration: 3 + ) + + for transition in MusicVideoTransition.allCases { + var look = MusicVideoLookTuning() + look.sourceAudio = .full + look.transition = transition + let composed = try await compose(plan, fixture: sources.fixture, look: look) + #expect(try audioRMS(of: composed, from: 0.2, length: 1.0) < 0.01, "\(transition) 前半は無音") + #expect(try audioRMS(of: composed, from: 1.8, length: 1.0) > 0.24, "\(transition) 後半は素材の音") + } + } + + @Test + func sourceAudioKeepsMusicAndSilentSourcesWorking() async throws { + let sources = try await makeSourceAudioFixture() + defer { try? FileManager.default.removeItem(at: sources.fixture.directory) } + // 音声トラックのない素材のカットは、素材の音がなく、音楽だけになる。 + let plan = CutPlan( + cuts: [ + plannedCut(sources.silent, from: 0, at: 0, length: 1.5), + plannedCut(sources.toned, from: 1, at: 1.5, length: 1.5) + ], + duration: 3 + ) + var look = MusicVideoLookTuning() + look.sourceAudio = .full + try writeSineWAV(to: sources.fixture.music, duration: 8) + let composed = try await compose(plan, fixture: sources.fixture, look: look) + + #expect(composed.composition.tracks(withMediaType: .audio).count == 2, "音楽と素材の音") + let silentPart = try audioRMS(of: composed, from: 0.2, length: 1.0) + let tonedPart = try audioRMS(of: composed, from: 1.8, length: 1.0) + // 音楽(0.3 の正弦波)だけの所は約 0.21。そこに素材の音(約 0.28)が重なると大きくなる。 + #expect(silentPart > 0.15 && silentPart < 0.27) + #expect(tonedPart > silentPart * 1.3) + } + + @Test + func sourceAudioFadesWithTheRestOfTheVideo() async throws { + let sources = try await makeSourceAudioFixture() + defer { try? FileManager.default.removeItem(at: sources.fixture.directory) } + let plan = CutPlan( + cuts: [ + plannedCut(sources.toned, from: 0, at: 0, length: 2.5), + plannedCut(sources.toned, from: 3, at: 2.5, length: 2.5) + ], + duration: 5 + ) + var look = MusicVideoLookTuning() + look.sourceAudio = .full + look.fadeSeconds = 1 + let composed = try await compose(plan, fixture: sources.fixture, look: look) + + let first = try audioRMS(of: composed, from: 0, length: 0.1) + let middle = try audioRMS(of: composed, from: 1.5, length: 0.5) + let last = try audioRMS(of: composed, from: 4.9, length: 0.1) + #expect(middle > 0.24) + #expect(first < middle * 0.25) + #expect(last < middle * 0.25) + } + + @Test + func sourceAudioDipsBrieflyAtCutSeamsToAvoidClicks() async throws { + let sources = try await makeSourceAudioFixture() + defer { try? FileManager.default.removeItem(at: sources.fixture.directory) } + let plan = CutPlan( + cuts: [ + plannedCut(sources.toned, from: 0, at: 0, length: 1.5), + plannedCut(sources.toned, from: 4, at: 1.5, length: 1.5) + ], + duration: 3 + ) + var look = MusicVideoLookTuning() + look.sourceAudio = .full + let composed = try await compose(plan, fixture: sources.fixture, look: look) + + // つなぎ目(1.5 秒)の前後 0.03 秒だけが絞られ、その外側は素材の音のまま。 + // 短い範囲ごとに読み直すと音声処理の単位に引きずられるので、一本の読み出しで波形を並べて調べる。 + let peaks = try audioPeaks(of: composed, from: 1.3, length: 0.4, block: 0.002) + func peak(in range: ClosedRange) -> Float { + peaks.filter { range.contains($0.time) }.map(\.peak).min() ?? .infinity + } + #expect(peak(in: 1.30...1.465) > 0.35, "つなぎ目の手前は素材の音のまま") + #expect(peak(in: 1.535...1.70) > 0.35, "つなぎ目の先も素材の音のまま") + #expect(peak(in: 1.49...1.51) < 0.1, "つなぎ目の真ん中は絞られる") + } + + /// macOS 標準の `say` で話し声を作り、44.1kHz モノラルのサンプルにして返す。作れない環境では nil。 + private func spokenSamples(_ text: String, in directory: URL) throws -> [Float]? { + let say = URL(fileURLWithPath: "/usr/bin/say") + guard FileManager.default.isExecutableFile(atPath: say.path) else { return nil } + let url = directory.appendingPathComponent("speech-\(UUID().uuidString).wav") + defer { try? FileManager.default.removeItem(at: url) } + let process = Process() + process.executableURL = say + process.arguments = ["-o", url.path, "--data-format=LEI16@44100", text] + try process.run() + process.waitUntilExit() + guard process.terminationStatus == 0 else { return nil } + let file = try AVAudioFile(forReading: url) + let format = try #require(AVAudioFormat(commonFormat: .pcmFormatFloat32, sampleRate: 44_100, channels: 1, interleaved: false)) + let buffer = try #require(AVAudioPCMBuffer(pcmFormat: format, frameCapacity: AVAudioFrameCount(file.length))) + try file.read(into: buffer) + return Array(UnsafeBufferPointer(start: try #require(buffer.floatChannelData)[0], count: Int(buffer.frameLength))) + } + + @Test(.enabled(if: FileManager.default.isExecutableFile(atPath: "/usr/bin/say"), "音声合成(say)が使える環境だけ")) + func choosingPartsKeepsOnlyTheSelectedSounds() async throws { + let base = try await makeFixture() + defer { try? FileManager.default.removeItem(at: base.directory) } + try writeMonoWAV(samples: [Float](repeating: 0, count: 8 * 44_100), sampleRate: 44_100, to: base.music) + + let speech = try #require(try spokenSamples( + "Hello everyone, welcome back to the channel. Today we are going to build something really cool together.", + in: base.directory + )) + // 素材の音: 0.4 秒から効果音(雑音の衝撃)、3 秒から話し声。 + var audio = [Float](repeating: 0, count: 14 * 44_100) + var seed: UInt64 = 99 + for offset in 0..> 40) / Float(1 << 23) - 1 + audio[Int(0.4 * 44_100) + offset] = 0.5 * noise * Float(exp(-Double(offset) / 44_100 / 0.2)) + } + for (offset, sample) in speech.enumerated() where 3 * 44_100 + offset < audio.count { audio[3 * 44_100 + offset] += sample } + let sourceURL = base.directory.appendingPathComponent("talking.mov") + try await step("talking video") { try await makeTestVideoWithAudio(at: sourceURL, duration: 14, samples: audio) } + let talking = UUID() + let fixture = Fixture( + directory: base.directory, dark: base.dark, bright: base.bright, portrait: base.portrait, + urls: base.urls.merging([talking: sourceURL]) { current, _ in current }, music: base.music + ) + // 前半は効果音だけの所、後半は話し声だけの所。 + let plan = CutPlan( + cuts: [ + plannedCut(talking, from: 0, at: 0, length: 2), + plannedCut(talking, from: 4, at: 2, length: 3) + ], + duration: 5 + ) + + var keep = MusicVideoLookTuning() + keep.sourceAudio = .full + var remove = keep + remove.sourceParts = [.music, .effects] // 声以外を残す + let kept = try await compose(plan, fixture: fixture, look: keep) + let removed = try await compose(plan, fixture: fixture, look: remove) + + let keptEffect = try audioRMS(of: kept, from: 0.45, length: 0.6) + let removedEffect = try audioRMS(of: removed, from: 0.45, length: 0.6) + let keptSpeech = try audioRMS(of: kept, from: 2.3, length: 2.4) + let removedSpeech = try audioRMS(of: removed, from: 2.3, length: 2.4) + #expect(keptEffect > 0.05) + #expect(keptSpeech > 0.02) + // 声を除く処理はモノラルの素材をステレオで読み出すので、音量の絶対値は測り方で変わる(テストの測り方では約 +3dB)。 + // そこで、声と効果音の比が、どれだけ変わったかで確かめる。 + #expect(removedEffect > keptEffect * 0.7, "効果音だけの所は、削られない(\(keptEffect) → \(removedEffect))") + let keptRatio = keptSpeech / keptEffect + let removedRatio = removedSpeech / removedEffect + #expect(removedRatio < keptRatio * 0.4, "効果音に対する話し声の大きさが 8dB 以上減る(\(keptRatio) → \(removedRatio))") + #expect(abs(removed.duration - 5) < 0.05) + + // 声だけ残す: 話し声の所は残り、効果音だけの所は、ほとんど消える。 + var voiceOnly = keep + voiceOnly.sourceParts = [.voice] + let voiced = try await compose(plan, fixture: fixture, look: voiceOnly) + let voicedEffect = try audioRMS(of: voiced, from: 0.45, length: 0.6) + let voicedSpeech = try audioRMS(of: voiced, from: 2.3, length: 2.4) + // 測り方でモノラルの素材が約 +3dB に出るので、比べるのは、声を残した音どうし・声以外を残した音どうし。 + #expect(voicedEffect < keptEffect * 0.2, "効果音だけの所は、ほとんど消える(\(keptEffect) → \(voicedEffect))") + #expect(voicedSpeech > keptSpeech * 0.6, "話し声の所は残る(\(keptSpeech) → \(voicedSpeech))") + + // 同じ範囲をもう一度作るときは、保存した音を使い回す(保存ファイルが増えない)。 + let cache = fixture.directory.appendingPathComponent("voice-cache") + let filesBefore = try FileManager.default.contentsOfDirectory(atPath: cache.path).count + _ = try await compose(plan, fixture: fixture, look: remove) + #expect(try FileManager.default.contentsOfDirectory(atPath: cache.path).count == filesBefore) + #expect(filesBefore == 4, "カットの数 × 残す成分の組み合わせ(2通り)だけ保存される") + } + + @Test + func partsSelectionDoesNothingWhileSourceAudioIsOff() async throws { + let sources = try await makeSourceAudioFixture() + defer { try? FileManager.default.removeItem(at: sources.fixture.directory) } + let plan = CutPlan(cuts: [plannedCut(sources.toned, from: 1, at: 0, length: 3)], duration: 3) + + var look = MusicVideoLookTuning() + look.sourceAudio = .off + look.sourceParts = [.effects] + let composed = try await compose(plan, fixture: sources.fixture, look: look) + #expect(composed.audioMix == nil) + #expect(composed.composition.tracks(withMediaType: .audio).count == 1, "音楽の1本だけ") + #expect(!FileManager.default.fileExists(atPath: sources.fixture.directory.appendingPathComponent("voice-cache").path)) + } + + @Test + func sourceAudioExportsIntoTheMP4() async throws { + let sources = try await makeSourceAudioFixture() + defer { try? FileManager.default.removeItem(at: sources.fixture.directory) } + let plan = CutPlan( + cuts: [ + plannedCut(sources.toned, from: 0, at: 0, length: 1.5), + plannedCut(sources.late, from: 3.5, at: 1.5, length: 1.5) + ], + duration: 3 + ) + var look = MusicVideoLookTuning() + look.sourceAudio = .medium + look.transition = .crossfade + look.fadeSeconds = 0.5 + let composed = try await compose(plan, fixture: sources.fixture, look: look) + + let output = sources.fixture.directory.appendingPathComponent("out/with-source-audio.mp4") + try await step("export") { try await MusicVideoComposer().export(composed, to: output) } + + let asset = AVURLAsset(url: output) + #expect(try await asset.loadTracks(withMediaType: .video).count == 1) + #expect(try await asset.loadTracks(withMediaType: .audio).count == 1, "音楽と素材の音は1本に混ざる") + #expect(abs(try await asset.load(.duration).seconds - 3) < 0.2) + } + @Test func crossfadeWithFadeExportsAPlayableMP4() async throws { let fixture = try await makeFixture() From 7845d0fa9cf2377efab7ac0c4d5dfb4bfc6e31af Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8E=9F=E3=80=80=E9=A2=AF=E7=99=BB?= Date: Fri, 6 Nov 2026 01:54:26 +0900 Subject: [PATCH 6/7] =?UTF-8?q?fix(musicvideo):=20=E6=9C=AC=E4=BD=93?= =?UTF-8?q?=E5=85=A8=E7=94=BB=E9=9D=A2=E6=99=82=E3=81=A7=E3=82=82=E3=83=97?= =?UTF-8?q?=E3=83=AC=E3=83=93=E3=83=A5=E3=83=BC=E3=82=92=E5=85=A8=E7=94=BB?= =?UTF-8?q?=E9=9D=A2=E8=A1=A8=E7=A4=BA=E3=81=A7=E3=81=8D=E3=82=8B=E3=82=88?= =?UTF-8?q?=E3=81=86=E6=9E=A0=E3=81=AA=E3=81=97=E3=82=A6=E3=82=A3=E3=83=B3?= =?UTF-8?q?=E3=83=89=E3=82=A6=E6=96=B9=E5=BC=8F=E3=81=AB=E5=A4=89=E6=9B=B4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Views/MusicVideoFullScreenPresenter.swift | 94 ++++++++++++++----- .../Views/MusicVideoPlayerViews.swift | 2 + 2 files changed, 70 insertions(+), 26 deletions(-) diff --git a/ArkServer/Features/MusicVideo/Views/MusicVideoFullScreenPresenter.swift b/ArkServer/Features/MusicVideo/Views/MusicVideoFullScreenPresenter.swift index 60e33c2..7cd839d 100644 --- a/ArkServer/Features/MusicVideo/Views/MusicVideoFullScreenPresenter.swift +++ b/ArkServer/Features/MusicVideo/Views/MusicVideoFullScreenPresenter.swift @@ -3,11 +3,31 @@ import AppKit import SwiftUI -/// プレビューを、macOS 標準の全画面ウィンドウで開く。 -/// 全画面をやめる(Esc・F・ダブルクリック・操作部のボタン)と、ウィンドウごと閉じて、元の画面へ戻る。 +/// 全画面のウィンドウ。枠の無い窓なので、そのままではキー入力を受けられない。受けられるようにして、Esc で閉じる。 +private final class FullScreenWindow: NSWindow { + var onCancel: (() -> Void)? + + override var canBecomeKey: Bool { true } + override var canBecomeMain: Bool { true } + + /// Esc。 + override func cancelOperation(_ sender: Any?) { + onCancel?() + } +} + +/// プレビューを、画面全体を覆うウィンドウで開く。 +/// +/// macOS 標準の全画面(`toggleFullScreen`)は使わない。アプリ本体の窓が全画面になっているとき、 +/// 2つ目の窓は全画面に入れず、小さな窓のまま残ってしまう(`windowDidFailToEnterFullScreen`)。 +/// 画面と同じ大きさの枠なしウィンドウをメニューバーとDockより上に出せば、本体が全画面でもそうでなくても、同じように全画面になる。 +/// 全画面をやめる(Esc・F・ダブルクリック・操作部のボタン)と、ウィンドウを閉じて、元の画面へ戻る。 @MainActor final class MusicVideoFullScreenPresenter: NSObject, NSWindowDelegate { - private var window: NSWindow? + private var window: FullScreenWindow? + /// 全画面を開く前に操作していた窓。閉じたあと、ここへ操作を戻す。 + private weak var previousKeyWindow: NSWindow? + private var screenObserver: NSObjectProtocol? var isPresented: Bool { window != nil } @@ -19,48 +39,70 @@ final class MusicVideoFullScreenPresenter: NSObject, NSWindowDelegate { return } + // 元の画面(いま操作しているウィンドウ)があるディスプレイを覆う。(置かないと、別のディスプレイに出ることがある) + previousKeyWindow = NSApp.keyWindow + guard let screen = NSApp.keyWindow?.screen ?? NSApp.mainWindow?.screen ?? NSScreen.main ?? NSScreen.screens.first else { return } + let content = MusicVideoFullScreenView(viewModel: viewModel) { [weak self] in self?.close() } - let window = NSWindow( - contentRect: CGRect(x: 0, y: 0, width: 1280, height: 720), - styleMask: [.titled, .closable, .miniaturizable, .resizable, .fullSizeContentView], + let window = FullScreenWindow( + contentRect: screen.frame, + styleMask: [.borderless], backing: .buffered, - defer: false + defer: false, + screen: screen ) window.title = "プレビュー" - window.titleVisibility = .hidden - window.titlebarAppearsTransparent = true window.isReleasedWhenClosed = false window.backgroundColor = .black - window.collectionBehavior = [.fullScreenPrimary] + window.isOpaque = true + window.hasShadow = false + window.animationBehavior = .none + // メニューバーとDockの上に出す。本体が全画面(別のSpace)のときも、そのSpaceの上に重ねる。 + window.level = .mainMenu + 1 + window.collectionBehavior = [.fullScreenAuxiliary, .moveToActiveSpace, .ignoresCycle] + // 別のアプリに切り替えたときは隠れて、戻ると出る(他のアプリの上に居座らない)。 + window.hidesOnDeactivate = true window.contentView = NSHostingView(rootView: content) window.delegate = self - // 元の画面(いま操作しているウィンドウ)があるディスプレイの中央に置いてから、全画面にする。 - // (置かないと、別のディスプレイで全画面になることがある) - let screen = NSApp.keyWindow?.screen ?? NSApp.mainWindow?.screen ?? NSScreen.main - if let frame = screen?.visibleFrame { - let size = window.frame.size - window.setFrameOrigin(NSPoint(x: frame.midX - size.width / 2, y: frame.midY - size.height / 2)) - } else { - window.center() - } + window.onCancel = { [weak self] in self?.close() } self.window = window - window.makeKeyAndOrderFront(nil) - window.toggleFullScreen(nil) + // ディスプレイの接続が変わったときは、覆う大きさを合わせ直す。 + screenObserver = NotificationCenter.default.addObserver( + forName: NSApplication.didChangeScreenParametersNotification, object: nil, queue: .main + ) { [weak self] _ in + MainActor.assumeIsolated { self?.fitToScreen() } + } + + window.setFrame(screen.frame, display: true) + NSApp.activate(ignoringOtherApps: true) + window.orderFrontRegardless() + window.makeKey() } func close() { window?.close() } + /// 覆うディスプレイの大きさに合わせる。ディスプレイが無くなっていたら、閉じる。 + private func fitToScreen() { + guard let window else { return } + guard let screen = window.screen ?? NSScreen.main else { + close() + return + } + window.setFrame(screen.frame, display: true) + } + // MARK: NSWindowDelegate func windowWillClose(_ notification: Notification) { + if let screenObserver { NotificationCenter.default.removeObserver(screenObserver) } + screenObserver = nil + // 閉じる前に押されたキーの入力が残らないよう、元の窓へ操作を戻す。 + let previous = previousKeyWindow window = nil - } - - /// 全画面をやめたら、通常サイズのウィンドウは残さず閉じる。 - func windowDidExitFullScreen(_ notification: Notification) { - close() + previousKeyWindow = nil + if let previous, previous.isVisible { previous.makeKeyAndOrderFront(nil) } } } diff --git a/ArkServer/Features/MusicVideo/Views/MusicVideoPlayerViews.swift b/ArkServer/Features/MusicVideo/Views/MusicVideoPlayerViews.swift index 645552a..2157fee 100644 --- a/ArkServer/Features/MusicVideo/Views/MusicVideoPlayerViews.swift +++ b/ArkServer/Features/MusicVideo/Views/MusicVideoPlayerViews.swift @@ -390,6 +390,8 @@ struct MusicVideoFullScreenView: View { if isGone { close() } } .background(shortcuts) + // Esc。ウィンドウ側(`cancelOperation`)でも受けているが、SwiftUI のビューが先に受けた場合に備える。 + .onExitCommand(perform: close) .accessibilityIdentifier("musicvideo.fullScreen") } From 8cc7056451653e41c8ee5c7576241c5b0a62792b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8E=9F=E3=80=80=E9=A2=AF=E7=99=BB?= Date: Fri, 6 Nov 2026 01:54:26 +0900 Subject: [PATCH 7/7] =?UTF-8?q?test(musicvideo):=20=E3=83=97=E3=83=AC?= =?UTF-8?q?=E3=83=93=E3=83=A5=E3=83=BC=E5=85=A8=E7=94=BB=E9=9D=A2=E8=A1=A8?= =?UTF-8?q?=E7=A4=BA=E3=81=AE=E3=82=A6=E3=82=A3=E3=83=B3=E3=83=89=E3=82=A6?= =?UTF-8?q?=E5=8B=95=E4=BD=9C=E3=83=86=E3=82=B9=E3=83=88=E3=82=92=E8=BF=BD?= =?UTF-8?q?=E5=8A=A0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../MusicVideoFullScreenPresenterTests.swift | 154 ++++++++++++++++++ 1 file changed, 154 insertions(+) create mode 100644 ArkServerTests/MusicVideoFullScreenPresenterTests.swift diff --git a/ArkServerTests/MusicVideoFullScreenPresenterTests.swift b/ArkServerTests/MusicVideoFullScreenPresenterTests.swift new file mode 100644 index 0000000..e3a4ae3 --- /dev/null +++ b/ArkServerTests/MusicVideoFullScreenPresenterTests.swift @@ -0,0 +1,154 @@ +// ArkServerTests/MusicVideoFullScreenPresenterTests.swift + +import AppKit +import AVFoundation +import SwiftUI +import Testing +@testable import ArkServer + +/// プレビューの全画面表示。アプリ本体の窓が macOS の全画面になっているときにも、画面いっぱいに出ることを確かめる。 +/// (以前は macOS 標準の全画面を使っていて、本体が全画面だと、2つ目の窓は全画面に入れず、小さな窓のまま残った) +@MainActor +@Suite(.serialized, .enabled(if: NSScreen.main != nil, "画面のある環境だけ")) +struct MusicVideoFullScreenPresenterTests { + /// 映像を作り終えた画面(曲の解析と、素材3本)。設定の保存先も置き場も、テスト専用にする。 + private func makeReadyViewModel(in directory: URL, suite: String) async throws -> (viewModel: MusicVideoViewModel, library: LibraryViewModel) { + let defaults = try #require(UserDefaults(suiteName: suite)) + let musicURL = directory.appendingPathComponent("music.wav") + try writeMonoWAV( + samples: clickTrack(duration: 16, clicks: evenClicks(from: 0.25, interval: 0.5, until: 16).map { ($0, 0.8) }), + sampleRate: testSampleRate, + to: musicURL + ) + var items: [VideoItem] = [] + for index in 0..<3 { + let url = directory.appendingPathComponent("source\(index).mp4") + try await makeTestVideo(at: url, duration: 6) { _ in UInt8(60 + index * 70) } + items.append(VideoItem( + id: UUID(), originalFilename: "source\(index).mp4", internalFilename: "", duration: 6, + importDate: Date(), creationDate: nil, fileHash: "", mediaType: .video, externalFilePath: url.path + )) + } + let library = LibraryViewModel(storageEnvironment: LibraryStorageEnvironment( + moviesDirectory: { directory }, + downloadsDirectory: { nil }, + createDirectory: { try FileManager.default.createDirectory(at: $0, withIntermediateDirectories: true) } + )) + library.videos = items + let viewModel = MusicVideoViewModel(preferencesStore: MusicVideoPreferencesStore(defaults: defaults)) + viewModel.attach(dataManager: library) + viewModel.selectedVideoIDs = Set(items.map(\.id)) + viewModel.chooseMusic(musicURL) + try await wait("曲の解析") { viewModel.fullAnalysis != nil && !viewModel.isWorking } + viewModel.generate(dataManager: library) + try await wait("映像の作成") { viewModel.phase == .ready && viewModel.plan != nil } + viewModel.isMuted = true + return (viewModel, library) + } + + private func wait(_ label: String, timeout: Double = 60, _ condition: () -> Bool) async throws { + let deadline = Date().addingTimeInterval(timeout) + while !condition() { + guard Date() < deadline else { throw WaitFailure(label: label) } + try await Task.sleep(for: .milliseconds(40)) + } + } + + private struct WaitFailure: Error, CustomStringConvertible { + let label: String + var description: String { "待っていた状態にならないまま時間切れ: \(label)" } + } + + private func previewWindows() -> [NSWindow] { + NSApp.windows.filter { $0.title == "プレビュー" && $0.isVisible } + } + + /// 本物のキーイベント(Esc)を、全画面の窓へ送る。 + private func pressEscape(in window: NSWindow) throws { + let event = try #require(NSEvent.keyEvent( + with: .keyDown, location: .zero, modifierFlags: [], timestamp: ProcessInfo.processInfo.systemUptime, + windowNumber: window.windowNumber, context: nil, characters: "\u{1B}", charactersIgnoringModifiers: "\u{1B}", + isARepeat: false, keyCode: 53 + )) + NSApp.sendEvent(event) + } + + @Test + func coversTheWholeScreenWhetherOrNotTheMainWindowIsFullScreen() async throws { + let directory = try temporaryDirectory("fullscreen-presenter") + let suite = "musicvideo-fullscreen-tests-\(UUID().uuidString)" + defer { + UserDefaults(suiteName: suite)?.removePersistentDomain(forName: suite) + try? FileManager.default.removeItem(at: directory) + } + let (viewModel, _) = try await makeReadyViewModel(in: directory, suite: suite) + defer { viewModel.stopAllPlayback() } + + for mainIsFullScreen in [false, true] { + let label = mainIsFullScreen ? "本体が全画面" : "本体が通常" + let presenter = MusicVideoFullScreenPresenter() + let main = NSWindow( + contentRect: CGRect(x: 100, y: 100, width: 800, height: 450), + styleMask: [.titled, .closable, .resizable], backing: .buffered, defer: false + ) + main.isReleasedWhenClosed = false + main.collectionBehavior = [.fullScreenPrimary] + main.contentView = NSHostingView(rootView: MusicVideoPlayerPane(viewModel: viewModel) { presenter.present(viewModel: viewModel) }) + main.makeKeyAndOrderFront(nil) + if mainIsFullScreen { + main.toggleFullScreen(nil) + try await wait("本体の全画面") { main.styleMask.contains(.fullScreen) } + try await Task.sleep(for: .seconds(1)) + } + + viewModel.seek(to: 0) + viewModel.togglePlayback() + try await Task.sleep(for: .milliseconds(500)) + #expect(viewModel.isPlaying, "\(label): 再生中") + + let before = Set(previewWindows().map(\.windowNumber)) + presenter.present(viewModel: viewModel) + try await Task.sleep(for: .seconds(1)) + let window = try #require(previewWindows().first { !before.contains($0.windowNumber) }, "\(label): 全画面の窓が出る") + let screenFrame = try #require((window.screen ?? NSScreen.main)?.frame) + #expect(presenter.isPresented, "\(label)") + #expect(window.frame == screenFrame, "\(label): 画面ぴったりを覆う(\(window.frame) / \(screenFrame))") + #expect(window.level.rawValue > NSWindow.Level.mainMenu.rawValue, "\(label): メニューバーより上") + // キーウィンドウ・実際に見えているか、は、アプリが前面にいて画面が点いているときだけ成り立つ(画面スリープ中などは判定できない)。 + let isForeground = NSApp.isActive && window.occlusionState.contains(.visible) + if isForeground { + #expect(window.isKeyWindow, "\(label): キー入力を受ける") + } + #expect(viewModel.isPlaying, "\(label): 全画面にしても再生が続く") + + try pressEscape(in: window) + try await Task.sleep(for: .seconds(1)) + #expect(!presenter.isPresented, "\(label): Esc で閉じる") + #expect(!window.isVisible, "\(label): 閉じた窓は見えない") + if isForeground { + #expect(main.isKeyWindow, "\(label): 元の窓へ操作が戻る") + } + #expect(viewModel.isPlaying, "\(label): 閉じても再生が続く") + + viewModel.pausePlayback() + if main.styleMask.contains(.fullScreen) { + main.toggleFullScreen(nil) + try await wait("本体の全画面を戻す") { !main.styleMask.contains(.fullScreen) } + try await Task.sleep(for: .seconds(1)) + } + main.close() + } + } + + @Test + func doesNothingUntilTheVideoIsReady() throws { + // 映像ができていないときは、全画面を開かない。 + let suite = "musicvideo-fullscreen-empty-\(UUID().uuidString)" + let defaults = try #require(UserDefaults(suiteName: suite)) + defer { defaults.removePersistentDomain(forName: suite) } + let viewModel = MusicVideoViewModel(preferencesStore: MusicVideoPreferencesStore(defaults: defaults)) + let presenter = MusicVideoFullScreenPresenter() + presenter.present(viewModel: viewModel) + #expect(!presenter.isPresented) + } +}