From 9d574093371eb7f09adc9d0a21b6cef2a8789230 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8E=9F=E3=80=80=E9=A2=AF=E7=99=BB?= Date: Wed, 4 Nov 2026 13:22:17 +0900 Subject: [PATCH 1/9] =?UTF-8?q?refactor(design):=20=E3=82=BF=E3=82=A4?= =?UTF-8?q?=E3=83=9D=E3=82=B0=E3=83=A9=E3=83=95=E3=82=A3=E9=9A=8E=E5=B1=A4?= =?UTF-8?q?=E3=81=A8=E9=85=8D=E8=89=B2=E3=83=88=E3=83=BC=E3=82=AF=E3=83=B3?= =?UTF-8?q?=E3=82=92=E6=95=B4=E7=90=86=E3=81=97=E8=A8=AD=E5=AE=9A=E8=A1=8C?= =?UTF-8?q?=E3=81=AE=E5=85=B1=E9=80=9AUI=E9=83=A8=E5=93=81=E3=82=92DesignS?= =?UTF-8?q?ystem=E3=81=B8=E7=A7=BB=E5=8B=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Common/DesignSystem/DesignSystem.swift | 85 ++++++++----------- .../DesignSystem/SettingsComponents.swift} | 31 +++---- 2 files changed, 53 insertions(+), 63 deletions(-) rename ArkServer/{Features/MusicVideo/Views/MusicVideoSettingsComponents.swift => Common/DesignSystem/SettingsComponents.swift} (82%) diff --git a/ArkServer/Common/DesignSystem/DesignSystem.swift b/ArkServer/Common/DesignSystem/DesignSystem.swift index 435cc7c..85b2ae6 100644 --- a/ArkServer/Common/DesignSystem/DesignSystem.swift +++ b/ArkServer/Common/DesignSystem/DesignSystem.swift @@ -14,19 +14,33 @@ import SwiftUI /// | appHeadline | 15 | カードの見出し | /// | appTitle | 17 | シート・パネルの見出し | /// | appLargeTitle | 26 | ページの見出し(LibraryPageHeader) | +/// +/// 見出しの太さは .medium までにする(太字にしない)。太字は、数値の強調や警告のように意味のある所だけで使う。 +/// 同じ大きさで少し強めたい文字(行の題名・件数・状態)は、`.weight` を足さず `…Strong` を使う。 +/// 時刻・IP・キー名のような等幅の文字は `appMono…`、画面の主役になる数値は `appMetric` を使う。 extension Font { static let appMicro = Font.system(size: 11) static let appCaption = Font.system(size: 12) static let appBody = Font.system(size: 13) - static let appHeadline = Font.system(size: 15, weight: .semibold) - static let appTitle = Font.system(size: 17, weight: .semibold) - static let appLargeTitle = Font.system(size: 26, weight: .bold) + static let appMicroStrong = Font.system(size: 11, weight: .medium) + static let appCaptionStrong = Font.system(size: 12, weight: .medium) + static let appBodyStrong = Font.system(size: 13, weight: .medium) + static let appMonoMicro = Font.system(size: 11, design: .monospaced) + static let appMonoCaption = Font.system(size: 12, design: .monospaced) + static let appMonoBody = Font.system(size: 13, design: .monospaced) + /// 件数のように、一目で読ませたい数値。数値だけは少し太くしてよい。 + static let appMetric = Font.system(size: 22, weight: .semibold) + static let appHeadline = Font.system(size: 15, weight: .medium) + static let appTitle = Font.system(size: 17, weight: .medium) + static let appLargeTitle = Font.system(size: 26, weight: .medium) + /// サーバーの「停止中/配信中」のような、画面の主役になる状態の文字。 + static let appStatus = Font.system(size: 28, weight: .medium) } // MARK: - デザイントークン enum DS { - static let cardCornerRadius: CGFloat = 16 + static let cardCornerRadius: CGFloat = 14 static let cardPadding: CGFloat = 20 static let cardSpacing: CGFloat = 20 } @@ -36,6 +50,10 @@ enum DS { enum NeomorphicTheme { static let darkBaseDefaultsKey = "appearance.neomorphicDarkBase" + // 黒基調の面の関係は、参考にした設定画面を、このアプリと同じ方法(スクリーンショットの画素値)で測って合わせた。 + // 窓の枠(タイトルバー・左のレール) > サイドバー > 内容の下地 の順に暗くなる。 + // 設定の行をまとめる面は、サイドバーとほぼ同じ明るさ。線と選択の面は、白の約8%。 + // つまり、内容は枠の内側にはめ込まれた一番暗いパネルに見える。 /// 未設定のときは黒基調。動画・画像が主役のアプリなので、作品の色が映える暗い下地を既定にする。 static var isDarkBase: Bool { UserDefaults.standard.object(forKey: darkBaseDefaultsKey) as? Bool ?? true @@ -46,18 +64,18 @@ enum NeomorphicTheme { /// 内容側の下地。 static var canvas: Color { - isDarkBase ? Color(white: 0.105) : Color(white: 0.965) + isDarkBase ? Color(white: 0.093) : Color(white: 0.965) } /// サイドバー・カードの面。下地よりわずかに明るい(黒基調)/白(明るい側)。 static var sidebar: Color { - isDarkBase ? Color(white: 0.150) : Color(white: 0.925) + isDarkBase ? Color(white: 0.133) : Color(white: 0.925) } - /// サイドバーの左に並ぶアイコンのレール。サイドバーより一段暗くして、2列を重ねて見せる。 + /// 窓の枠の色。左のレールとタイトルバーに使い、内側のサイドバーと内容を一段くぼませて見せる。 static var rail: Color { - isDarkBase ? Color(white: 0.125) : Color(white: 0.895) + isDarkBase ? Color(white: 0.204) : Color(white: 0.895) } static var card: Color { - isDarkBase ? Color(white: 0.150) : Color.white + isDarkBase ? Color(white: 0.139) : Color.white } /// 入力欄・検索欄・セグメントのような、面の上に置く操作部品の地。 static var control: Color { @@ -68,7 +86,7 @@ enum NeomorphicTheme { isDarkBase ? Color.white.opacity(0.17) : Color.white } static var cardBorder: Color { - isDarkBase ? Color.white.opacity(0.06) : Color.black.opacity(0.07) + isDarkBase ? Color.white.opacity(0.08) : Color.black.opacity(0.07) } static var background: Color { canvas } static var surface: Color { @@ -88,10 +106,10 @@ enum NeomorphicTheme { } /// 選択中の行・セグメント。色を付けず、面を一段明るく(暗く)するだけにする。 static var selection: Color { - isDarkBase ? Color.white.opacity(0.11) : Color.black.opacity(0.08) + isDarkBase ? Color.white.opacity(0.09) : Color.black.opacity(0.08) } static var hover: Color { - isDarkBase ? Color.white.opacity(0.06) : Color.black.opacity(0.045) + isDarkBase ? Color.white.opacity(0.05) : Color.black.opacity(0.045) } static var shadow: Color { Color.black.opacity(isDarkBase ? 0.5 : 0.12) @@ -114,7 +132,7 @@ struct SectionCard: View { var body: some View { VStack(alignment: .leading, spacing: 10) { Text(title) - .font(.system(size: 13, weight: .semibold)) + .font(.appBody.weight(.medium)) .foregroundStyle(NeomorphicTheme.muted) content } @@ -151,10 +169,10 @@ struct SheetHeader: View { .frame(width: 28) VStack(alignment: .leading, spacing: 2) { Text(title) - .font(.system(size: 17, weight: .semibold)) + .font(.appTitle) if let subtitle { Text(subtitle) - .font(.system(size: 12)) + .font(.appCaption) .foregroundStyle(NeomorphicTheme.muted) } } @@ -186,7 +204,7 @@ struct GlassCardSurface: View { .fill(NeomorphicTheme.card) .overlay { RoundedRectangle(cornerRadius: DS.cardCornerRadius, style: .continuous) - .strokeBorder(NeomorphicTheme.cardBorder, lineWidth: 0.5) + .strokeBorder(NeomorphicTheme.cardBorder, lineWidth: 1) } } } @@ -201,7 +219,7 @@ struct LibraryPageHeader: View { HStack(alignment: .center, spacing: 16) { VStack(alignment: .leading, spacing: 5) { Text(title) - .font(.system(size: 26, weight: .bold)) + .font(.appLargeTitle) .foregroundStyle(NeomorphicTheme.ink) .lineLimit(1) .truncationMode(.middle) @@ -299,11 +317,11 @@ struct CardHeader: View { .frame(width: 24, height: 24) VStack(alignment: .leading, spacing: 1) { Text(title) - .font(.system(size: 15, weight: .semibold)) + .font(.appHeadline) .foregroundStyle(NeomorphicTheme.ink) if let subtitle { Text(subtitle) - .font(.system(size: 12)) + .font(.appCaption) .foregroundStyle(NeomorphicTheme.muted) } } @@ -440,35 +458,6 @@ struct CopyableText: View { } } -// MARK: - 大きな主要アクションボタン(開始/停止用) - -struct ProminentActionButtonStyle: ButtonStyle { - let tint: Color - @Environment(\.isEnabled) private var isEnabled - - func makeBody(configuration: Configuration) -> some View { - configuration.label - .font(.system(size: 15, weight: .semibold)) - .foregroundStyle(.white) - .padding(.horizontal, 22) - .padding(.vertical, 9) - .background( - Capsule() - .fill( - LinearGradient( - colors: isEnabled - ? [tint, tint.opacity(0.75)] - : [Color.gray.opacity(0.45), Color.gray.opacity(0.35)], - startPoint: .top, endPoint: .bottom - ) - ) - .shadow(color: isEnabled ? tint.opacity(0.55) : .clear, radius: 10, x: 0, y: 3) - ) - .scaleEffect(configuration.isPressed ? 0.96 : 1.0) - .animation(.spring(response: 0.25, dampingFraction: 0.7), value: configuration.isPressed) - } -} - // MARK: - 統計表示(アイコン + 値 + ラベル) struct StatPill: View { diff --git a/ArkServer/Features/MusicVideo/Views/MusicVideoSettingsComponents.swift b/ArkServer/Common/DesignSystem/SettingsComponents.swift similarity index 82% rename from ArkServer/Features/MusicVideo/Views/MusicVideoSettingsComponents.swift rename to ArkServer/Common/DesignSystem/SettingsComponents.swift index d866e42..b31450f 100644 --- a/ArkServer/Features/MusicVideo/Views/MusicVideoSettingsComponents.swift +++ b/ArkServer/Common/DesignSystem/SettingsComponents.swift @@ -1,8 +1,9 @@ -// ArkServer/Features/MusicVideo/Views/MusicVideoSettingsComponents.swift +// ArkServer/Common/DesignSystem/SettingsComponents.swift import SwiftUI -// 設定画面のような「見出し + 行をまとめた面」で画面を組むための部品。 +// 設定画面のような「見出し + 行をまとめた面」で画面を組むための共通部品(一般的な設定画面の見た目に倣う)。 +// 詳細設定ページとミュージックビデオ画面が使う。 // // セクション名(控えめな小さい文字) // ┌──────────────────────────────────────────┐ @@ -14,11 +15,11 @@ import SwiftUI // // アイコン付きの見出しや色付きの面は使わない。色は、スイッチ・決定ボタン・選択中の印だけにする。 -/// 画面を中央の1列に収める幅。 -let musicVideoColumnWidth: CGFloat = 760 +/// 画面を中央の1列に収める幅(参考にした設定画面は約730pt)。 +let settingsColumnWidth: CGFloat = 760 /// セクション名と、その下の内容。 -struct MVSection: View { +struct SettingsSection: View { let title: String var footer: String? = nil @ViewBuilder var content: Content @@ -26,7 +27,7 @@ struct MVSection: View { var body: some View { VStack(alignment: .leading, spacing: 10) { Text(title) - .font(.appBody.weight(.medium)) + .font(.appBodyStrong) .foregroundStyle(NeomorphicTheme.muted) .padding(.horizontal, 2) .accessibilityAddTraits(.isHeader) @@ -43,7 +44,7 @@ struct MVSection: View { } /// 行をまとめる角丸の面。行の間に細い区切り線を入れる。 -struct MVRowGroup: View { +struct SettingsGroup: View { @ViewBuilder var content: Content var body: some View { @@ -64,7 +65,7 @@ struct MVRowGroup: View { } /// 1行。左に項目名と薄い説明、右に操作。 -struct MVRow: View { +struct SettingsRow: View { let title: String var detail: String? = nil @ViewBuilder var leading: Leading @@ -75,7 +76,7 @@ struct MVRow: View { leading VStack(alignment: .leading, spacing: 3) { Text(title) - .font(.appBody.weight(.medium)) + .font(.appBodyStrong) .foregroundStyle(NeomorphicTheme.ink) .lineLimit(2) if let detail { @@ -94,7 +95,7 @@ struct MVRow: View { } } -extension MVRow where Leading == EmptyView { +extension SettingsRow where Leading == EmptyView { init(title: String, detail: String? = nil, @ViewBuilder control: () -> Control) { self.title = title self.detail = detail @@ -104,12 +105,12 @@ extension MVRow where Leading == EmptyView { } /// 行の右に置く、小さな操作ボタン(「変更」のような見た目)。 -struct MVSmallButtonStyle: ButtonStyle { +struct QuietButtonStyle: ButtonStyle { @Environment(\.isEnabled) private var isEnabled func makeBody(configuration: Configuration) -> some View { configuration.label - .font(.appCaption.weight(.medium)) + .font(.appCaptionStrong) .foregroundStyle(NeomorphicTheme.ink.opacity(isEnabled ? 1 : 0.4)) .padding(.horizontal, 11) .padding(.vertical, 5) @@ -121,12 +122,12 @@ struct MVSmallButtonStyle: ButtonStyle { } } -extension ButtonStyle where Self == MVSmallButtonStyle { - static var mvSmall: MVSmallButtonStyle { MVSmallButtonStyle() } +extension ButtonStyle where Self == QuietButtonStyle { + static var quiet: QuietButtonStyle { QuietButtonStyle() } } /// 行の右に置く、スイッチ。 -struct MVSwitch: View { +struct SettingsSwitch: View { let title: String @Binding var isOn: Bool From 5802956c70df61da1d342b09afd0577b8ae04858 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8E=9F=E3=80=80=E9=A2=AF=E7=99=BB?= Date: Wed, 4 Nov 2026 13:22:28 +0900 Subject: [PATCH 2/9] =?UTF-8?q?feat(settings):=20=E8=A9=B3=E7=B4=B0?= =?UTF-8?q?=E8=A8=AD=E5=AE=9A=E3=82=92=E3=82=B7=E3=83=BC=E3=83=88=E3=81=8B?= =?UTF-8?q?=E3=82=89=E3=82=B5=E3=82=A4=E3=83=89=E3=83=90=E3=83=BC=E5=88=87?= =?UTF-8?q?=E3=82=8A=E6=9B=BF=E3=81=88=E5=BC=8F=E3=81=AE=E3=83=9A=E3=83=BC?= =?UTF-8?q?=E3=82=B8=E7=94=BB=E9=9D=A2=E3=81=B8=E5=88=B7=E6=96=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../App/Models/NavigationSelection.swift | 2 + ArkServer/App/ViewModels/AppViewModel.swift | 19 +- ArkServer/App/Views/ContentView.swift | 87 +++--- .../App/Views/WindowChromeConfigurator.swift | 2 +- .../Navigation/Views/MainSidebarView.swift | 27 +- .../Navigation/Views/SidebarRailView.swift | 4 +- .../Settings/Models/SettingsPane.swift | 89 ++++++ .../Views/MediaShortcutSettingsSection.swift | 79 +++-- .../Settings/Views/PreferencesView.swift | 257 ---------------- .../Settings/Views/SettingsPageView.swift | 278 ++++++++++++++++++ .../Settings/Views/SettingsSidebarView.swift | 86 ++++++ .../Features/Updates/AppUpdateView.swift | 43 ++- 12 files changed, 603 insertions(+), 370 deletions(-) create mode 100644 ArkServer/Features/Settings/Models/SettingsPane.swift delete mode 100644 ArkServer/Features/Settings/Views/PreferencesView.swift create mode 100644 ArkServer/Features/Settings/Views/SettingsPageView.swift create mode 100644 ArkServer/Features/Settings/Views/SettingsSidebarView.swift diff --git a/ArkServer/App/Models/NavigationSelection.swift b/ArkServer/App/Models/NavigationSelection.swift index a198cf5..2a07a5d 100644 --- a/ArkServer/App/Models/NavigationSelection.swift +++ b/ArkServer/App/Models/NavigationSelection.swift @@ -12,6 +12,8 @@ enum NavigationSelection: Hashable { case sceneExtraction /// 曲に合わせてライブラリの動画を自動で編集する画面。 case musicVideo + /// 詳細設定のページ。設定中は左のサイドバーが項目の一覧に切り替わる。 + case settings(SettingsPane) /// 動画・画像のアルバムを表紙つきで一覧するページ。 case albums case album(UUID) diff --git a/ArkServer/App/ViewModels/AppViewModel.swift b/ArkServer/App/ViewModels/AppViewModel.swift index eb8ecca..6487fa7 100644 --- a/ArkServer/App/ViewModels/AppViewModel.swift +++ b/ArkServer/App/ViewModels/AppViewModel.swift @@ -8,7 +8,6 @@ import Foundation @MainActor final class AppViewModel: ObservableObject { @Published var selection: NavigationSelection? = .home - @Published var isShowingPreferences = false @Published var isShowingStorageManager = false @Published var isShowingAccessLog = false @Published var sceneExtractionNavigationError: String? @@ -35,6 +34,7 @@ final class AppViewModel: ObservableObject { private var cancellables = Set() private var sceneExtractionReturnSelection: NavigationSelection = .home + private var settingsRouting = SettingsRouting() convenience init() { self.init( @@ -76,6 +76,23 @@ final class AppViewModel: ObservableObject { bridgeFavorites() } + // MARK: - 詳細設定ページ + + /// 詳細設定のページを開きます.元の画面は覚えておき,`closeSettings()` で戻します. + func openSettings(_ pane: SettingsPane = .connection) { + selection = settingsRouting.opening(from: selection, pane: pane) + } + + /// 詳細設定を閉じて,開く前の画面へ戻します. + func closeSettings() { + selection = settingsRouting.closing() + } + + /// レールの歯車用.設定中なら戻り,そうでなければ開きます. + func toggleSettings() { + if SettingsRouting.isSettings(selection) { closeSettings() } else { openSettings() } + } + /// ライブラリ内の動画を解析画面へ渡します. func openSceneExtraction(for item: VideoItem) { guard item.mediaType == .video else { diff --git a/ArkServer/App/Views/ContentView.swift b/ArkServer/App/Views/ContentView.swift index 6891aae..7aa0a1e 100644 --- a/ArkServer/App/Views/ContentView.swift +++ b/ArkServer/App/Views/ContentView.swift @@ -40,7 +40,7 @@ struct ContentView: View { // ライブラリ画面を出しっぱなしにすることではない。 if shouldShowLibraryView { // デスクトップが透けるガラス地はやめ、単色の下地にする(色の濁りと環境による見た目の差をなくす)。 - NeomorphicTheme.canvas + NeomorphicTheme.rail .id(appSettings.neomorphicDarkBase) .ignoresSafeArea() } else { @@ -72,12 +72,10 @@ struct ContentView: View { // ウィンドウのクロム設定はライブラリ画面の有無に関わらず効かせる必要があるため、 // ライブラリ画面ではなくこの常駐の階層に付ける。 .toolbar(isToolbarHidden ? .hidden : .automatic, for: .windowToolbar) - // タイトルバーの帯はサイドバーと同じ色にし、窓の上端でサイドバーと一続きに見せる。 - .toolbarBackground(NeomorphicTheme.sidebar, for: .windowToolbar) - .toolbarBackground( - isToolbarHidden ? .hidden : .visible, - for: .windowToolbar - ) + // タイトルバーの帯は、左のレールと同じ「窓の枠」の色にして内側のパネルをくぼませて見せる。 + // 帯の色は、ツールバーの背景として描かず、窓の背景色(WindowChromeConfigurator で枠の色にしてある)に任せる。 + // ツールバーの背景を出すと、検索欄などのあるライブラリ画面で、帯がパネルの中(見出しの背後)まで広がってしまう。 + .toolbarBackground(.hidden, for: .windowToolbar) .background( WindowChromeConfigurator(isToolbarHidden: isToolbarHidden) ) @@ -92,13 +90,6 @@ struct ContentView: View { \.appMenuContext, dataManager.isStorageReady ? appMenuContext : nil ) - .sheet(isPresented: $viewModel.isShowingPreferences) { - PreferencesView( - dataManager: dataManager, - webServerManager: viewModel.webServerManager, - appSettings: appSettings - ) - } .sheet(isPresented: $viewModel.isShowingStorageManager) { StorageManagerView(dataManager: dataManager) } @@ -133,6 +124,24 @@ struct ContentView: View { } } + /// 左のサイドバー。設定のページでは、アルバムの一覧の代わりに設定の項目の一覧を出す。 + @ViewBuilder + private var sidebarColumn: some View { + if case .settings(let pane) = viewModel.selection { + SettingsSidebarView( + selected: pane, + onSelect: { viewModel.openSettings($0) }, + onBack: { viewModel.closeSettings() } + ) + } else { + MainSidebarView( + dataManager: dataManager, + webServerManager: viewModel.webServerManager, + selection: $viewModel.selection + ) + } + } + /// ミニプレイヤー表示中は通常再生の裏でライブラリも操作できるようにする。 private var shouldShowLibraryView: Bool { guard let mode = playbackCoordinator.mode else { return true } @@ -234,8 +243,8 @@ struct ContentView: View { private var libraryView: some View { ZStack { - // ツールバーの背後まで同じ背景を広げ,フルスクリーン時の色の段差をなくす。 - CommandDeckBackground() + // ツールバーの背後まで同じ背景(窓の枠の色)を広げ,フルスクリーン時の色の段差をなくす。 + NeomorphicTheme.rail.ignoresSafeArea() // 標準の NavigationSplitView は macOS 26 でサイドバーが「浮いた角丸のガラス」になり、 // 窓の端や上下に余白ができて平らにできない。そこで左カラムを自前で組み、窓の端から端まで @@ -249,29 +258,21 @@ struct ContentView: View { allVideosAlbumID: dataManager.albums.first { $0.name == LibraryViewModel.allVideosAlbumName }?.id, allPhotosAlbumID: dataManager.albums.first { $0.name == LibraryViewModel.allPhotosAlbumName }?.id, onShowStorage: { viewModel.isShowingStorageManager = true }, - onShowPreferences: { viewModel.isShowingPreferences = true } + onShowPreferences: { viewModel.toggleSettings() } ) .background(NeomorphicTheme.rail.ignoresSafeArea()) - .overlay(alignment: .trailing) { - Rectangle() - .fill(NeomorphicTheme.separator) - .frame(width: 0.5) - .ignoresSafeArea() - } + // サイドバーと内容は、窓の枠の内側にはめ込んだ1枚の角丸パネルにする。 + HStack(spacing: 0) { if isSidebarVisible { - MainSidebarView( - dataManager: dataManager, - webServerManager: viewModel.webServerManager, - selection: $viewModel.selection - ) + sidebarColumn .frame(width: sidebarWidth) .frame(maxHeight: .infinity) .background(NeomorphicTheme.sidebar.ignoresSafeArea()) .overlay(alignment: .trailing) { Rectangle() .fill(NeomorphicTheme.separator) - .frame(width: 0.5) + .frame(width: 1) .ignoresSafeArea() } .transition(.move(edge: .leading)) @@ -351,6 +352,14 @@ struct ContentView: View { onAnalyzeScenes: viewModel.openSceneExtraction ) .navigationTitle(path.components(separatedBy: "/").last ?? path) + case .settings(let pane): + SettingsPageView( + pane: pane, + dataManager: dataManager, + webServerManager: viewModel.webServerManager, + appSettings: appSettings + ) + .navigationTitle("設定") case .none: ContentUnavailableView("サイドバーから項目を選択してください", systemImage: "sidebar.left") } @@ -363,10 +372,18 @@ struct ContentView: View { .toolbar(removing: .title) // タイトルを外すと、右寄せだった各画面のボタンが左へ詰まるので、中央に伸びる空きを置いて右側に戻す。 .toolbar { principalSpacer } - // 標準の分割表示が確保していたツールバーの下の余白を、自前の構成でも同じだけ空ける。 - .safeAreaInset(edge: .top, spacing: 0) { - Color.clear.frame(height: 44) } + // パネルの上端は、ツールバー(タイトルバーの帯)の下から始める。右と下には枠の色を少し残す。 + // 下地を持たない画面(ライブラリの一覧など)でも、窓の枠の色が透けないよう、内容の下地はパネルが持つ。 + .background(NeomorphicTheme.canvas) + .clipShape(RoundedRectangle(cornerRadius: DS.cardCornerRadius, style: .continuous)) + .overlay( + RoundedRectangle(cornerRadius: DS.cardCornerRadius, style: .continuous) + .strokeBorder(NeomorphicTheme.cardBorder, lineWidth: 1) + ) + .padding(.top, 44) + .padding(.trailing, 8) + .padding(.bottom, 8) } .toolbar { ToolbarItem(placement: .primaryAction) { @@ -417,7 +434,7 @@ struct ContentView: View { isPresentingPlayer: playbackCoordinator.isPresenting, canToggleMiniPlayer: isSingleVideoPlayback, isMiniPlayerActive: playbackCoordinator.isMiniPlayerActive, - showPreferences: { viewModel.isShowingPreferences = true }, + showPreferences: { viewModel.openSettings() }, showStorageManager: { viewModel.isShowingStorageManager = true }, showAccessLog: { viewModel.isShowingAccessLog = true }, showHome: { viewModel.selection = .home }, @@ -490,7 +507,7 @@ private struct LibraryStorageInitializationErrorView: View { VStack(spacing: 8) { Text("ライブラリ保存先を準備できませんでした") - .font(.appTitle.bold()) + .font(.appTitle) Text("データを保護するため,ライブラリの読み込みとサーバー起動を停止しています.") .foregroundStyle(.secondary) .multilineTextAlignment(.center) @@ -530,7 +547,7 @@ private struct LibraryStorageInitializationErrorView: View { private func errorRow(title: String, value: String) -> some View { VStack(alignment: .leading, spacing: 4) { Text(title) - .font(.appCaption.weight(.semibold)) + .font(.appCaptionStrong) .foregroundStyle(.secondary) Text(value) .textSelection(.enabled) diff --git a/ArkServer/App/Views/WindowChromeConfigurator.swift b/ArkServer/App/Views/WindowChromeConfigurator.swift index 4a35bd9..551aac1 100644 --- a/ArkServer/App/Views/WindowChromeConfigurator.swift +++ b/ArkServer/App/Views/WindowChromeConfigurator.swift @@ -36,7 +36,7 @@ final class WindowChromeView: NSView { ) // 下地は単色なので、透過ウィンドウにはしない(角の表示も安定する)。 window.isOpaque = true - window.backgroundColor = NSColor(NeomorphicTheme.canvas) + window.backgroundColor = NSColor(NeomorphicTheme.rail) window.toolbarStyle = .unifiedCompact window.toolbar?.isVisible = !isToolbarHidden } diff --git a/ArkServer/Features/Navigation/Views/MainSidebarView.swift b/ArkServer/Features/Navigation/Views/MainSidebarView.swift index 9b9abed..24735a9 100644 --- a/ArkServer/Features/Navigation/Views/MainSidebarView.swift +++ b/ArkServer/Features/Navigation/Views/MainSidebarView.swift @@ -48,7 +48,7 @@ struct MainSidebarView: View { // dataManager.videos / .albums が実際に変化したときだけ refreshSidebarCaches() で更新する。 private let sidebarContentPadding: CGFloat = 10 private let sidebarTopPadding: CGFloat = 12 - private let sidebarToolbarInset: CGFloat = 54 + private let sidebarToolbarInset: CGFloat = 14 private let sidebarRowHeight: CGFloat = 32 /// 表紙と2行目(要約)つきの行の高さ。 private let sidebarDetailRowHeight: CGFloat = 46 @@ -103,12 +103,7 @@ struct MainSidebarView: View { .font(.appCaption) } .padding() - .background( - RoundedRectangle(cornerRadius: 8, style: .continuous) - .fill(NeomorphicTheme.surface) - .shadow(color: .white.opacity(0.9), radius: 7, x: -5, y: -5) - .shadow(color: NeomorphicTheme.shadow.opacity(0.3), radius: 12, x: 7, y: 7) - ) + .background(GlassCardSurface()) } } .alert("エクスポート完了", isPresented: $showSidebarExportResultAlert) { @@ -142,7 +137,7 @@ struct MainSidebarView: View { let buttonsWidth: CGFloat = isAlbumSelectionMode ? 116 : 60 return HStack(spacing: 0) { Text("アルバム") - .font(.system(size: 11, weight: .bold, design: .default)) + .font(.appCaptionStrong) .foregroundStyle(NeomorphicTheme.muted) .padding(.leading, 10) .frame(width: sidebarRowWidth - buttonsWidth, alignment: .leading) @@ -289,7 +284,7 @@ struct MainSidebarView: View { if matchingAlbums.isEmpty { VStack(alignment: .leading, spacing: 8) { Text("一致するアルバムはありません") - .font(.appBody.weight(.semibold)) + .font(.appBodyStrong) Text("名前やフォルダ名を変えて検索してください.") .font(.appCaption) .foregroundStyle(NeomorphicTheme.muted) @@ -414,7 +409,7 @@ struct MainSidebarView: View { .foregroundStyle(isActive ? NeomorphicTheme.ink : NeomorphicTheme.muted) .frame(width: sidebarIconWidth) Text(title) - .font(.system(size: 13, weight: .regular, design: .default)) + .font(.appBody) .foregroundStyle(NeomorphicTheme.ink) .lineLimit(1) .truncationMode(.tail) @@ -457,7 +452,7 @@ struct MainSidebarView: View { sidebarCover(summary, isFolder: isFolder) VStack(alignment: .leading, spacing: 2) { Text(title) - .font(.system(size: 13, weight: .regular, design: .default)) + .font(.appBody) .foregroundStyle(NeomorphicTheme.ink) .lineLimit(1) .truncationMode(.tail) @@ -514,13 +509,13 @@ struct MainSidebarView: View { private func sidebarPlainLabel(_ title: String, systemImage: String) -> some View { Label(title, systemImage: systemImage) - .font(.system(size: 12, weight: .semibold, design: .default)) + .font(.appCaptionStrong) .foregroundStyle(NeomorphicTheme.ink) } private func sidebarSectionTitle(_ title: String) -> some View { Text(title) - .font(.system(size: 12, weight: .medium, design: .default)) + .font(.appCaptionStrong) .foregroundStyle(NeomorphicTheme.muted) .padding(.leading, sidebarRowLeadingPadding) .padding(.trailing, sidebarRowTrailingPadding) @@ -536,7 +531,7 @@ struct MainSidebarView: View { .foregroundStyle(NeomorphicTheme.muted) .frame(width: sidebarIconWidth) Text(title) - .font(.system(size: 13, weight: .regular, design: .default)) + .font(.appBody) .foregroundStyle(NeomorphicTheme.ink) .lineLimit(1) .truncationMode(.tail) @@ -552,7 +547,7 @@ struct MainSidebarView: View { // 件数は補足情報なので、色付きのカプセルにせず、控えめな数字だけにする // (全行に青い太字のバッジが並ぶと、行の名前より数字が目立ってしまう)。 Text("\(count.formatted())") - .font(.system(size: 11, weight: .regular)) + .font(.appMicro) .monospacedDigit() .foregroundStyle(NeomorphicTheme.muted) } @@ -992,7 +987,7 @@ struct MainSidebarView: View { VStack(spacing: 4) { Text("新規アルバム") - .font(.system(size: 17, weight: .semibold)) + .font(.appTitle) Text("名前とタイプを選んで作成します") .font(.appCaption) .foregroundStyle(NeomorphicTheme.muted) diff --git a/ArkServer/Features/Navigation/Views/SidebarRailView.swift b/ArkServer/Features/Navigation/Views/SidebarRailView.swift index f135953..73662ba 100644 --- a/ArkServer/Features/Navigation/Views/SidebarRailView.swift +++ b/ArkServer/Features/Navigation/Views/SidebarRailView.swift @@ -177,7 +177,7 @@ struct SidebarRailView: View { VStack(spacing: 6) { RailButton(title: "ストレージ管理", symbol: "internaldrive", count: nil, isActive: false, action: onShowStorage) - RailButton(title: "詳細設定", symbol: "gearshape", count: nil, isActive: false, action: onShowPreferences) + RailButton(title: "詳細設定", symbol: "gearshape", count: nil, isActive: SettingsRouting.isSettings(selection), action: onShowPreferences) } .padding(.bottom, 14) } @@ -215,7 +215,7 @@ private struct RailButton: View { .overlay(alignment: .topTrailing) { if let count, count > 0 { Text(Self.compact(count)) - .font(.appMicro.weight(.semibold).monospacedDigit()) + .font(.appMicroStrong.monospacedDigit()) .foregroundStyle(isActive ? NeomorphicTheme.ink : NeomorphicTheme.muted) .padding(.horizontal, 4.5) .frame(minWidth: 16, minHeight: 15) diff --git a/ArkServer/Features/Settings/Models/SettingsPane.swift b/ArkServer/Features/Settings/Models/SettingsPane.swift new file mode 100644 index 0000000..6fb90f3 --- /dev/null +++ b/ArkServer/Features/Settings/Models/SettingsPane.swift @@ -0,0 +1,89 @@ +// ArkServer/Features/Settings/Models/SettingsPane.swift + +import Foundation + +/// 設定ページの項目(左のサイドバーに並ぶ1つ1つ)。 +enum SettingsPane: String, CaseIterable, Identifiable, Hashable, Sendable { + case connection + case appearance + case data + case protection + case performance + case export + case updates + case shortcuts + + var id: String { rawValue } + + var title: String { + switch self { + case .connection: return "接続・認証" + case .appearance: return "外観" + case .data: return "データの安全" + case .protection: return "サーバー保護" + case .performance: return "パフォーマンス" + case .export: return "エクスポート" + case .updates: return "アップデート" + case .shortcuts: return "ショートカットキー" + } + } + + var symbol: String { + switch self { + case .connection: return "wifi" + case .appearance: return "circle.lefthalf.filled" + case .data: return "externaldrive" + case .protection: return "lock.shield" + case .performance: return "speedometer" + case .export: return "square.and.arrow.up" + case .updates: return "arrow.triangle.2.circlepath" + case .shortcuts: return "keyboard" + } + } + + /// サイドバーでの見出しのまとまり。 + enum Group: String, CaseIterable, Identifiable { + case general = "基本" + case library = "ライブラリとサーバー" + case app = "アプリ" + var id: String { rawValue } + } + + var group: Group { + switch self { + case .connection, .appearance: return .general + case .data, .protection, .performance, .export: return .library + case .updates, .shortcuts: return .app + } + } + + /// サイドバーに出す順の、(見出し, 項目) の一覧。 + static var grouped: [(group: Group, panes: [SettingsPane])] { + Group.allCases.map { group in (group, allCases.filter { $0.group == group }) } + } +} + +/// 設定ページを開いたときに「元いた画面」を覚え、閉じるときに戻す。 +/// +/// 設定の中で項目を切り替えても、戻り先は最初に開いたときの画面のまま。 +struct SettingsRouting: Equatable { + private(set) var returnSelection: NavigationSelection = .home + + /// `current` から設定を開くときの、新しい選択を返す。すでに設定の中なら、戻り先は変えない。 + mutating func opening(from current: NavigationSelection?, pane: SettingsPane) -> NavigationSelection { + if !Self.isSettings(current) { + returnSelection = current ?? .home + } + return .settings(pane) + } + + /// 設定を閉じたあとに出す選択。 + func closing() -> NavigationSelection { + returnSelection + } + + static func isSettings(_ selection: NavigationSelection?) -> Bool { + if case .settings = selection { return true } + return false + } +} diff --git a/ArkServer/Features/Settings/Views/MediaShortcutSettingsSection.swift b/ArkServer/Features/Settings/Views/MediaShortcutSettingsSection.swift index 915987f..0faeb38 100644 --- a/ArkServer/Features/Settings/Views/MediaShortcutSettingsSection.swift +++ b/ArkServer/Features/Settings/Views/MediaShortcutSettingsSection.swift @@ -4,52 +4,36 @@ struct MediaShortcutSettingsSection: View { @AppStorage(MediaShortcutSettings.versionKey) private var settingsVersion = 0 var body: some View { - Section("ショートカットキー") { - VStack(alignment: .leading, spacing: 8) { - Text("一覧") - .font(.appCaption.bold()) - .foregroundStyle(.secondary) - ForEach(MediaShortcutAction.libraryActions) { action in - MediaShortcutAssignmentRow(action: action) - } - } + VStack(alignment: .leading, spacing: 28) { + category("一覧", actions: MediaShortcutAction.libraryActions) + category("動画", actions: MediaShortcutAction.videoActions) + category("差分切り替え再生", actions: MediaShortcutAction.variantActions) + category("画像", actions: MediaShortcutAction.photoActions) - VStack(alignment: .leading, spacing: 8) { - Text("動画") - .font(.appCaption.bold()) - .foregroundStyle(.secondary) - ForEach(MediaShortcutAction.videoActions) { action in - MediaShortcutAssignmentRow(action: action) - } + if hasDuplicateAssignments { + Label("同じキーが複数の操作に割り当てられています.画面ごとの先に判定された操作が優先されます.", systemImage: "exclamationmark.triangle") + .font(.appCaption) + .foregroundStyle(NeomorphicTheme.caution) } - VStack(alignment: .leading, spacing: 8) { - Text("差分切り替え再生") - .font(.appCaption.bold()) - .foregroundStyle(.secondary) - ForEach(MediaShortcutAction.variantActions) { action in - MediaShortcutAssignmentRow(action: action) + SettingsGroup { + SettingsRow(title: "既定値に戻す", detail: "すべてのショートカットキーを初期の割り当てに戻します.") { + Button("戻す") { + MediaShortcutSettings.resetDefaults() + } + .buttonStyle(.quiet) } } + } + } - VStack(alignment: .leading, spacing: 8) { - Text("画像") - .font(.appCaption.bold()) - .foregroundStyle(.secondary) - ForEach(MediaShortcutAction.photoActions) { action in + private func category(_ title: String, actions: [MediaShortcutAction]) -> some View { + SettingsSection(title: title) { + SettingsGroup { + ForEach(actions) { action in MediaShortcutAssignmentRow(action: action) } } - - if hasDuplicateAssignments { - Label("同じキーが複数の操作に割り当てられています.画面ごとの先に判定された操作が優先されます.", systemImage: "exclamationmark.triangle") - .font(.appCaption) - .foregroundStyle(.orange) - } - - Button("既定値に戻す") { - MediaShortcutSettings.resetDefaults() - } } } @@ -75,14 +59,17 @@ private struct MediaShortcutAssignmentRow: View { @State private var isCapturing = false var body: some View { - HStack(alignment: .firstTextBaseline, spacing: 10) { - Text(action.settingsTitle) + HStack(alignment: .center, spacing: 10) { + // セクション名(一覧・動画・画像…)と重なる「一覧: 」のような接頭辞は省く。 + Text(action.settingsTitle.components(separatedBy: ": ").last ?? action.settingsTitle) + .font(.appBody.weight(.medium)) + .foregroundStyle(NeomorphicTheme.ink) Spacer(minLength: 12) FlowLayout(spacing: 6) { ForEach(keys) { key in HStack(spacing: 4) { Text(key.displayName) - .font(.system(size: 12, design: .monospaced).weight(.semibold)) + .font(.appMonoCaption.weight(.medium)) Button { MediaShortcutSettings.removeKey(key, for: action) } label: { @@ -95,7 +82,7 @@ private struct MediaShortcutAssignmentRow: View { } .padding(.horizontal, 7) .padding(.vertical, 3) - .background(Color.primary.opacity(0.08), in: Capsule()) + .background(NeomorphicTheme.control, in: Capsule()) } } Button { @@ -107,15 +94,17 @@ private struct MediaShortcutAssignmentRow: View { Label(isCapturing ? "キーを押してください" : "キーを追加", systemImage: isCapturing ? "keyboard" : "plus.circle") .font(.appCaption) } - .buttonStyle(.borderless) + .buttonStyle(.quiet) .help(isCapturing ? "登録したいキーを押してください.Escでキャンセルします." : "キーを押して追加") } - .padding(.vertical, 2) + .padding(.horizontal, 16) + .padding(.vertical, 10) + .frame(minHeight: 48) .focusable() .focused($isCaptureFocused) .background( - RoundedRectangle(cornerRadius: 6, style: .continuous) - .fill(isCapturing ? Color.accentColor.opacity(0.12) : Color.clear) + Rectangle() + .fill(isCapturing ? NeomorphicTheme.accent.opacity(0.12) : Color.clear) ) .onKeyPress(phases: .down, action: captureKeyPress) .onChange(of: settingsVersion) { _, _ in diff --git a/ArkServer/Features/Settings/Views/PreferencesView.swift b/ArkServer/Features/Settings/Views/PreferencesView.swift deleted file mode 100644 index 2ab325d..0000000 --- a/ArkServer/Features/Settings/Views/PreferencesView.swift +++ /dev/null @@ -1,257 +0,0 @@ -import AppKit -import SwiftUI - -/// 詳細設定シート。データ安全・サーバー保護・パフォーマンス・エクスポートの -/// 各設定をまとめる(値の実体は LibraryViewModel / ServerViewModel / UserDefaults)。 -struct PreferencesView: View { - @ObservedObject var dataManager: LibraryViewModel - @ObservedObject var webServerManager: ServerViewModel - @ObservedObject var appSettings: AppSettings - @Environment(\.dismiss) private var dismiss - - @AppStorage("thumbnailMemoryCacheLimit") private var thumbnailMemoryCacheLimit = 600 - - /// 上部の見出しボタンから飛べる区分。設定が縦に長いので,目的の場所へすぐ移れるようにする。 - private enum SettingsSection: String, CaseIterable, Identifiable { - // シートの最小幅(560)に1行で収まるよう,見出しより短い名前にしている。 - case connection = "接続" - case appearance = "外観" - case data = "データ" - case server = "保護" - case performance = "性能" - case export = "書き出し" - case updates = "更新" - case shortcuts = "ショートカット" - var id: String { rawValue } - } - - var body: some View { - VStack(spacing: 0) { - HStack(spacing: 12) { - IconTile(icon: "gearshape", tint: NeomorphicTheme.muted, size: 38) - VStack(alignment: .leading, spacing: 2) { - Text("Ark Serverの設定") - .font(.appTitle.bold()) - Text("接続・データの安全性・サーバー保護・パフォーマンスの設定") - .font(.appCaption) - .foregroundStyle(.secondary) - } - Spacer() - } - .padding(.horizontal, 20) - .padding(.top, 20) - .padding(.bottom, 10) - - ScrollViewReader { proxy in - VStack(spacing: 0) { - sectionJumpBar(proxy: proxy) - - Form { - // ポート・PIN・自動停止はホームのカードでも変えられるが,設定を探すときに - // ここだけ見れば全部そろっているようにする(値の実体は同じ ServerViewModel)。 - Section("接続・認証") { - LabeledContent("ポート番号") { - HStack(spacing: 6) { - TextField("ポート番号", value: $webServerManager.targetPort, format: .number.grouping(.never)) - .labelsHidden() - .frame(width: 70) - .multilineTextAlignment(.center) - Button { - webServerManager.targetPort = 8080 - } label: { - Image(systemName: "arrow.counterclockwise") - } - .buttonStyle(.borderless) - .help("デフォルト(8080)に戻す") - } - } - .disabled(webServerManager.isRunning) - - Toggle("自動停止タイマー", isOn: $webServerManager.autoStopEnabled) - .disabled(webServerManager.isRunning) - if webServerManager.autoStopEnabled { - LabeledContent("サーバー開始から終了まで") { - HStack(spacing: 5) { - TextField("分", value: $webServerManager.autoStopIntervalMinutes, format: .number) - .labelsHidden() - .frame(width: 54) - .multilineTextAlignment(.trailing) - Text("分").foregroundStyle(.secondary) - } - } - .disabled(webServerManager.isRunning) - } - if webServerManager.isRunning { - Text("ポート番号と自動停止は,サーバーを停止すると変更できます.") - .font(.appCaption) - .foregroundStyle(.secondary) - } - - Toggle("PIN認証を必須にする", isOn: $webServerManager.authEnabled) - if webServerManager.authEnabled { - LabeledContent("接続PIN") { - HStack(spacing: 8) { - Text(webServerManager.authPIN) - .font(.system(.body, design: .monospaced).weight(.bold)) - .textSelection(.enabled) - Button { - webServerManager.regeneratePIN() - } label: { - Image(systemName: "arrow.triangle.2.circlepath") - } - .buttonStyle(.borderless) - .help("PINを再生成する") - } - } - } else { - Text("認証が無効です.同じWi-Fi内の誰でもアクセスできます.") - .font(.appCaption) - .foregroundStyle(.orange) - } - } - .id(SettingsSection.connection) - - Section("外観") { - Toggle("ダークな外観にする", isOn: $appSettings.neomorphicDarkBase) - Text("ブルーを基調に,控えめなガラスと読みやすい文字で統一しています.明るい外観と暗い外観を切り替えられます.") - .font(.appCaption) - .foregroundStyle(.secondary) - - Toggle("サイドバーのアルバムに表紙と詳細を表示", isOn: $appSettings.sidebarShowsAlbumDetails) - Text("オフにすると,従来の名前と件数だけの行に戻ります.アルバムが非常に多いときに行を詰めたい場合に使います.") - .font(.appCaption) - .foregroundStyle(.secondary) - } - .id(SettingsSection.appearance) - - Section("データの安全") { - Toggle("インポート時にファイルをアプリ内へコピー", isOn: $dataManager.importCopiesFiles) - Text("オンにすると,元のフォルダを消してもサーバー内に実体が残ります(ディスク容量を消費).オフ(既定)は元の場所を参照するだけで,元ファイルを消すと再生できなくなります.") - .font(.appCaption) - .foregroundStyle(.secondary) - - Picker("ゴミ箱の自動削除", selection: $dataManager.trashAutoDeleteDays) { - Text("しない").tag(0) - Text("30日後").tag(30) - Text("90日後").tag(90) - } - Text("ゴミ箱に入れてから指定日数が経過した項目を,起動時に完全削除します.") - .font(.appCaption) - .foregroundStyle(.secondary) - - Toggle("起動時にリンク切れメディアを自動整理", isOn: $dataManager.autoCleanupMissingFilesEnabled) - Text("元ファイルが見つからない項目を起動時に自動削除します.外付けドライブのメディアを参照している場合はオフのままにしてください(未接続時に誤って消えます).") - .font(.appCaption) - .foregroundStyle(.secondary) - } - .id(SettingsSection.data) - - Section("サーバー保護") { - Toggle("認証オフでも削除操作にはPINを要求", isOn: $webServerManager.requirePINForDeletion) - Text("PIN認証をオフにしていても,完全削除・アルバム削除・サーバー停止のAPIにはPINを要求します.") - .font(.appCaption) - .foregroundStyle(.secondary) - - TextField("サーバー表示名(空欄でコンピュータ名)", text: $webServerManager.serverDisplayName) - Text("iOSアプリやブラウザに表示される名前です.変更はサーバーの再起動後に反映されます.") - .font(.appCaption) - .foregroundStyle(.secondary) - - Picker("アップロード上限", selection: $webServerManager.maxUploadGB) { - ForEach(ServerViewModel.uploadLimitOptionsGB, id: \.self) { gb in - Text("\(gb) GB").tag(gb) - } - } - Text("受信中のファイルは丸ごとメモリに読み込まれるため,搭載メモリ(\(Self.physicalMemoryGB) GB)の半分までしか選べません.") - .font(.appCaption) - .foregroundStyle(.secondary) - } - .id(SettingsSection.server) - - Section("パフォーマンス") { - Picker("自動重複チェックの間隔", selection: $dataManager.duplicateCheckIntervalSeconds) { - Text("30秒").tag(30) - Text("1分").tag(60) - Text("5分").tag(300) - Text("15分").tag(900) - } - - Picker("インポートの並列数", selection: $dataManager.importConcurrency) { - Text("2(省電力)").tag(2) - Text("4(標準)").tag(4) - Text("8(高速)").tag(8) - } - - Picker("サムネイルのメモリキャッシュ上限", selection: $thumbnailMemoryCacheLimit) { - Text("200枚(省メモリ)").tag(200) - Text("600枚(標準)").tag(600) - Text("1200枚(大量表示向け)").tag(1200) - } - .onChange(of: thumbnailMemoryCacheLimit) { _, newValue in - MacVideoThumbnailView.updateMemoryCacheLimit(newValue) - } - } - .id(SettingsSection.performance) - - Section("エクスポート") { - Toggle("アルバムの階層構造を再現して書き出す", isOn: $dataManager.exportPreservesAlbumStructure) - Text("オフにすると,すべてのファイルを選んだフォルダ直下にフラットに書き出します.") - .font(.appCaption) - .foregroundStyle(.secondary) - } - .id(SettingsSection.export) - - UpdateSettingsSection() - .id(SettingsSection.updates) - - MediaShortcutSettingsSection() - .id(SettingsSection.shortcuts) - } - .formStyle(.grouped) - } - } - - HStack { - Spacer() - Button("閉じる") { dismiss() } - .keyboardShortcut(.defaultAction) - } - .padding(16) - } - // 項目が多いので固定サイズにせず,ウィンドウの端をドラッグして広げられるようにする。 - .frame(minWidth: 560, idealWidth: 640, maxWidth: 900, minHeight: 520, idealHeight: 760, maxHeight: .infinity) - // シートを開くと AppKit が先頭の入力欄(ポート番号)を自動で選択し,うっかり打鍵しただけで - // 値が書き換わる。SwiftUI の FocusState では止められないので,開いた直後に選択を外す。 - .background(InitialFirstResponderClearer()) - // 半透明にするとデスクトップの色が透けて緑や青に濁るので、アプリ本体と同じ単色の下地にする。 - .background(NeomorphicTheme.canvas) - .tint(NeomorphicTheme.accent) - .foregroundStyle(NeomorphicTheme.ink) - } - - private static let physicalMemoryGB = Int(ProcessInfo.processInfo.physicalMemory / 1_073_741_824) - - private func sectionJumpBar(proxy: ScrollViewProxy) -> some View { - ScrollView(.horizontal, showsIndicators: false) { - HStack(spacing: 6) { - ForEach(SettingsSection.allCases) { section in - Button { - withAnimation(.easeOut(duration: 0.2)) { - proxy.scrollTo(section, anchor: .top) - } - } label: { - Text(section.rawValue) - .font(.appCaption) - .foregroundStyle(NeomorphicTheme.ink) - .padding(.horizontal, 10) - .padding(.vertical, 4) - .background(Capsule().fill(NeomorphicTheme.control)) - } - .buttonStyle(.plain) - } - } - .padding(.horizontal, 20) - } - .padding(.bottom, 8) - } -} diff --git a/ArkServer/Features/Settings/Views/SettingsPageView.swift b/ArkServer/Features/Settings/Views/SettingsPageView.swift new file mode 100644 index 0000000..b889307 --- /dev/null +++ b/ArkServer/Features/Settings/Views/SettingsPageView.swift @@ -0,0 +1,278 @@ +// ArkServer/Features/Settings/Views/SettingsPageView.swift + +import AppKit +import SwiftUI + +/// 詳細設定のページ。中央の1列に、項目ごとの「セクション名 + 行をまとめた面」を並べる。 +/// 値の実体は LibraryViewModel / ServerViewModel / AppSettings / UserDefaults(シートだった頃と同じ)。 +struct SettingsPageView: View { + let pane: SettingsPane + @ObservedObject var dataManager: LibraryViewModel + @ObservedObject var webServerManager: ServerViewModel + @ObservedObject var appSettings: AppSettings + + @AppStorage("thumbnailMemoryCacheLimit") private var thumbnailMemoryCacheLimit = 600 + + private static let physicalMemoryGB = Int(ProcessInfo.processInfo.physicalMemory / 1_073_741_824) + + var body: some View { + ScrollView { + VStack(alignment: .leading, spacing: 28) { + Text(pane.title) + .font(.appLargeTitle) + .foregroundStyle(NeomorphicTheme.ink) + .padding(.top, 8) + .accessibilityAddTraits(.isHeader) + + content + } + .frame(maxWidth: settingsColumnWidth, alignment: .leading) + .frame(maxWidth: .infinity) + .padding(.horizontal, 24) + .padding(.top, 28) + .padding(.bottom, 40) + } + .background(CommandDeckBackground()) + // 設定のスイッチなど「入」の色は青にする(内容側の既定は文字色の中立色)。 + .tint(NeomorphicTheme.accent) + .foregroundStyle(NeomorphicTheme.ink) + // ページを開くと AppKit が先頭の入力欄(ポート番号)を自動で選択し,うっかり打鍵しただけで + // 値が書き換わる。SwiftUI の FocusState では止められないので,開いた直後に選択を外す。 + .background(InitialFirstResponderClearer()) + .id(pane) + } + + @ViewBuilder + private var content: some View { + switch pane { + case .connection: connection + case .appearance: appearance + case .data: dataSafety + case .protection: protection + case .performance: performance + case .export: export + case .updates: UpdateSettingsSection() + case .shortcuts: MediaShortcutSettingsSection() + } + } + + // MARK: - 接続・認証 + + private var connection: some View { + // ポート・PIN・自動停止はホームのカードでも変えられるが,設定を探すときにここだけ見れば全部そろっているようにする + // (値の実体は同じ ServerViewModel)。 + VStack(alignment: .leading, spacing: 28) { + SettingsSection( + title: "サーバー", + footer: webServerManager.isRunning ? "ポート番号と自動停止は,サーバーを停止すると変更できます." : nil + ) { + SettingsGroup { + SettingsRow(title: "ポート番号", detail: "iPhoneやブラウザから接続するときのポートです.既定は8080です.") { + HStack(spacing: 6) { + TextField("ポート番号", value: $webServerManager.targetPort, format: .number.grouping(.never)) + .labelsHidden() + .textFieldStyle(.roundedBorder) + .frame(width: 76) + .multilineTextAlignment(.center) + Button { + webServerManager.targetPort = 8080 + } label: { + Image(systemName: "arrow.counterclockwise") + } + .buttonStyle(.quiet) + .help("既定(8080)に戻す") + .accessibilityLabel("ポート番号を既定に戻す") + } + .disabled(webServerManager.isRunning) + } + SettingsRow(title: "自動停止タイマー", detail: "サーバーを開始してから決めた時間がたつと,自動で停止します.") { + SettingsSwitch(title: "自動停止タイマー", isOn: $webServerManager.autoStopEnabled) + .disabled(webServerManager.isRunning) + } + if webServerManager.autoStopEnabled { + SettingsRow(title: "サーバー開始から終了まで") { + HStack(spacing: 6) { + TextField("分", value: $webServerManager.autoStopIntervalMinutes, format: .number) + .labelsHidden() + .textFieldStyle(.roundedBorder) + .frame(width: 60) + .multilineTextAlignment(.trailing) + Text("分").foregroundStyle(NeomorphicTheme.muted) + } + .disabled(webServerManager.isRunning) + } + } + } + } + + SettingsSection(title: "認証") { + SettingsGroup { + SettingsRow( + title: "PIN認証を必須にする", + detail: webServerManager.authEnabled + ? "接続する端末で6桁のPINの入力が必要になります." + : "認証が無効です.同じWi-Fi内の誰でもアクセスできます." + ) { + SettingsSwitch(title: "PIN認証を必須にする", isOn: $webServerManager.authEnabled) + } + if webServerManager.authEnabled { + SettingsRow(title: "接続PIN") { + HStack(spacing: 8) { + Text(webServerManager.authPIN) + .font(.system(.body, design: .monospaced).weight(.semibold)) + .textSelection(.enabled) + Button { + webServerManager.regeneratePIN() + } label: { + Image(systemName: "arrow.triangle.2.circlepath") + } + .buttonStyle(.quiet) + .help("PINを再生成する") + .accessibilityLabel("PINを再生成する") + } + } + } + } + } + } + } + + // MARK: - 外観 + + private var appearance: some View { + SettingsSection(title: "表示") { + SettingsGroup { + SettingsRow(title: "ダークな外観にする", detail: "暗い外観と明るい外観を切り替えます.") { + SettingsSwitch(title: "ダークな外観にする", isOn: $appSettings.neomorphicDarkBase) + } + SettingsRow( + title: "サイドバーのアルバムに表紙と詳細を表示", + detail: "オフにすると,名前と件数だけの行に戻ります.アルバムが非常に多いときに行を詰めたい場合に使います." + ) { + SettingsSwitch(title: "サイドバーのアルバムに表紙と詳細を表示", isOn: $appSettings.sidebarShowsAlbumDetails) + } + } + } + } + + // MARK: - データの安全 + + private var dataSafety: some View { + SettingsSection(title: "メディアの扱い") { + SettingsGroup { + SettingsRow( + title: "インポート時にファイルをアプリ内へコピー", + detail: "オンにすると,元のフォルダを消してもサーバー内に実体が残ります(ディスク容量を消費).オフ(既定)は元の場所を参照するだけで,元ファイルを消すと再生できなくなります." + ) { + SettingsSwitch(title: "インポート時にファイルをアプリ内へコピー", isOn: $dataManager.importCopiesFiles) + } + SettingsRow(title: "ゴミ箱の自動削除", detail: "ゴミ箱に入れてから指定日数が経過した項目を,起動時に完全削除します.") { + Picker("ゴミ箱の自動削除", selection: $dataManager.trashAutoDeleteDays) { + Text("しない").tag(0) + Text("30日後").tag(30) + Text("90日後").tag(90) + } + .labelsHidden() + .fixedSize() + } + SettingsRow( + title: "起動時にリンク切れメディアを自動整理", + detail: "元ファイルが見つからない項目を起動時に自動削除します.外付けドライブのメディアを参照している場合はオフのままにしてください(未接続時に誤って消えます)." + ) { + SettingsSwitch(title: "起動時にリンク切れメディアを自動整理", isOn: $dataManager.autoCleanupMissingFilesEnabled) + } + } + } + } + + // MARK: - サーバー保護 + + private var protection: some View { + SettingsSection(title: "サーバーの保護") { + SettingsGroup { + SettingsRow( + title: "認証オフでも削除操作にはPINを要求", + detail: "PIN認証をオフにしていても,完全削除・アルバム削除・サーバー停止のAPIにはPINを要求します." + ) { + SettingsSwitch(title: "認証オフでも削除操作にはPINを要求", isOn: $webServerManager.requirePINForDeletion) + } + SettingsRow( + title: "サーバー表示名", + detail: "iOSアプリやブラウザに表示される名前です.空欄ならコンピュータ名を使います.変更はサーバーの再起動後に反映されます." + ) { + TextField("コンピュータ名", text: $webServerManager.serverDisplayName) + .labelsHidden() + .textFieldStyle(.roundedBorder) + .frame(width: 200) + } + SettingsRow( + title: "アップロード上限", + detail: "受信中のファイルは丸ごとメモリに読み込まれるため,搭載メモリ(\(Self.physicalMemoryGB) GB)の半分までしか選べません." + ) { + Picker("アップロード上限", selection: $webServerManager.maxUploadGB) { + ForEach(ServerViewModel.uploadLimitOptionsGB, id: \.self) { gb in + Text("\(gb) GB").tag(gb) + } + } + .labelsHidden() + .fixedSize() + } + } + } + } + + // MARK: - パフォーマンス + + private var performance: some View { + SettingsSection(title: "処理の負荷") { + SettingsGroup { + SettingsRow(title: "自動重複チェックの間隔") { + Picker("自動重複チェックの間隔", selection: $dataManager.duplicateCheckIntervalSeconds) { + Text("30秒").tag(30) + Text("1分").tag(60) + Text("5分").tag(300) + Text("15分").tag(900) + } + .labelsHidden() + .fixedSize() + } + SettingsRow(title: "インポートの並列数") { + Picker("インポートの並列数", selection: $dataManager.importConcurrency) { + Text("2(省電力)").tag(2) + Text("4(標準)").tag(4) + Text("8(高速)").tag(8) + } + .labelsHidden() + .fixedSize() + } + SettingsRow(title: "サムネイルのメモリキャッシュ上限") { + Picker("サムネイルのメモリキャッシュ上限", selection: $thumbnailMemoryCacheLimit) { + Text("200枚(省メモリ)").tag(200) + Text("600枚(標準)").tag(600) + Text("1200枚(大量表示向け)").tag(1200) + } + .labelsHidden() + .fixedSize() + .onChange(of: thumbnailMemoryCacheLimit) { _, newValue in + MacVideoThumbnailView.updateMemoryCacheLimit(newValue) + } + } + } + } + } + + // MARK: - エクスポート + + private var export: some View { + SettingsSection(title: "書き出し") { + SettingsGroup { + SettingsRow( + title: "アルバムの階層構造を再現して書き出す", + detail: "オフにすると,すべてのファイルを選んだフォルダ直下にフラットに書き出します." + ) { + SettingsSwitch(title: "アルバムの階層構造を再現して書き出す", isOn: $dataManager.exportPreservesAlbumStructure) + } + } + } + } +} diff --git a/ArkServer/Features/Settings/Views/SettingsSidebarView.swift b/ArkServer/Features/Settings/Views/SettingsSidebarView.swift new file mode 100644 index 0000000..d3902f8 --- /dev/null +++ b/ArkServer/Features/Settings/Views/SettingsSidebarView.swift @@ -0,0 +1,86 @@ +// ArkServer/Features/Settings/Views/SettingsSidebarView.swift + +import SwiftUI + +/// 設定ページの左側。アルバムのサイドバーの代わりに出る、項目の一覧。 +/// 選ばれている行は、色を付けず、少し明るい角丸の面にする(一般的な設定画面の選択表示と同じ)。 +struct SettingsSidebarView: View { + let selected: SettingsPane + let onSelect: (SettingsPane) -> Void + let onBack: () -> Void + + var body: some View { + VStack(alignment: .leading, spacing: 0) { + HStack(spacing: 8) { + Button(action: onBack) { + Image(systemName: "chevron.left") + .font(.system(size: 13, weight: .medium)) + .frame(width: 26, height: 26) + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + .foregroundStyle(NeomorphicTheme.muted) + .help("元の画面へ戻る") + .accessibilityLabel("設定を閉じて戻る") + .accessibilityIdentifier("settings.back") + + Text("設定") + .font(.appTitle) + .foregroundStyle(NeomorphicTheme.ink) + Spacer(minLength: 0) + } + .padding(.horizontal, 12) + .padding(.top, 14) + .padding(.bottom, 10) + + ScrollView { + VStack(alignment: .leading, spacing: 20) { + ForEach(SettingsPane.grouped, id: \.group) { entry in + VStack(alignment: .leading, spacing: 2) { + Text(entry.group.rawValue) + .font(.appCaption) + .foregroundStyle(NeomorphicTheme.muted) + .padding(.horizontal, 10) + .padding(.bottom, 4) + ForEach(entry.panes) { pane in + row(pane) + } + } + } + } + .padding(.horizontal, 10) + .padding(.vertical, 8) + } + } + .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading) + } + + private func row(_ pane: SettingsPane) -> some View { + let isSelected = pane == selected + return Button { + onSelect(pane) + } label: { + HStack(spacing: 10) { + Image(systemName: pane.symbol) + .font(.system(size: 13)) + .foregroundStyle(isSelected ? NeomorphicTheme.ink : NeomorphicTheme.muted) + .frame(width: 18) + Text(pane.title) + .font(.appBody) + .foregroundStyle(NeomorphicTheme.ink) + .lineLimit(1) + Spacer(minLength: 0) + } + .padding(.horizontal, 10) + .frame(height: 32) + .background( + RoundedRectangle(cornerRadius: 8, style: .continuous) + .fill(isSelected ? NeomorphicTheme.selection : Color.clear) + ) + .contentShape(RoundedRectangle(cornerRadius: 8, style: .continuous)) + } + .buttonStyle(.plain) + .accessibilityAddTraits(isSelected ? .isSelected : []) + .accessibilityIdentifier("settings.pane.\(pane.rawValue)") + } +} diff --git a/ArkServer/Features/Updates/AppUpdateView.swift b/ArkServer/Features/Updates/AppUpdateView.swift index 96d6e11..a031ec7 100644 --- a/ArkServer/Features/Updates/AppUpdateView.swift +++ b/ArkServer/Features/Updates/AppUpdateView.swift @@ -5,7 +5,7 @@ struct AppUpdateView: View { var body: some View { VStack(alignment: .leading, spacing: 16) { - Text("ソフトウェアアップデート").font(.title2.bold()) + Text("ソフトウェアアップデート").font(.appTitle) Text("現在のバージョン: \(updater.currentVersion)(ビルド \(updater.currentBuild))") .foregroundStyle(.secondary) switch updater.state { @@ -65,19 +65,36 @@ struct AppUpdateView: View { struct UpdateSettingsSection: View { @ObservedObject private var updater = AppUpdater.shared var body: some View { - Section("アップデート") { - LabeledContent("現在のバージョン", value: "\(updater.currentVersion)(ビルド \(updater.currentBuild))") - Toggle("起動時に自動でアップデートを確認", isOn: $updater.automaticallyChecks) - LabeledContent("最終確認") { - if let date = updater.lastCheck { - Text(date, format: .dateTime.year().month().day().hour().minute()) - } else { - Text("未確認") + SettingsSection(title: "バージョン") { + SettingsGroup { + SettingsRow(title: "現在のバージョン") { + Text("\(updater.currentVersion)(ビルド \(updater.currentBuild))") + .font(.appBody.monospacedDigit()) + .foregroundStyle(NeomorphicTheme.muted) + } + SettingsRow(title: "起動時に自動でアップデートを確認") { + SettingsSwitch(title: "起動時に自動でアップデートを確認", isOn: $updater.automaticallyChecks) + } + SettingsRow(title: "最終確認") { + Group { + if let date = updater.lastCheck { + Text(date, format: .dateTime.year().month().day().hour().minute()) + } else { + Text("未確認") + } + } + .font(.appBody.monospacedDigit()) + .foregroundStyle(NeomorphicTheme.muted) + } + SettingsRow(title: updater.isBusy ? "アップデートの状況" : "アップデートを確認") { + HStack(spacing: 8) { + AppUpdateAvailabilityButton() + Button(updater.isBusy ? "状況を表示" : "今すぐ確認") { + updater.check(manual: true) + } + .buttonStyle(.quiet) + } } - } - AppUpdateAvailabilityButton() - Button(updater.isBusy ? "アップデートの状況を表示" : "今すぐアップデートを確認") { - updater.check(manual: true) } } } From 553a13e03bc3ce5d710899624f3e4f27ba3f5a75 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8E=9F=E3=80=80=E9=A2=AF=E7=99=BB?= Date: Wed, 4 Nov 2026 13:22:36 +0900 Subject: [PATCH 3/9] =?UTF-8?q?test(settings):=20=E8=A8=AD=E5=AE=9A?= =?UTF-8?q?=E3=83=9A=E3=82=A4=E3=83=B3=E6=A7=8B=E6=88=90=E3=81=A8=E7=94=BB?= =?UTF-8?q?=E9=9D=A2=E9=81=B7=E7=A7=BB=E3=83=AB=E3=83=BC=E3=83=86=E3=82=A3?= =?UTF-8?q?=E3=83=B3=E3=82=B0=E3=81=AE=E5=8D=98=E4=BD=93=E3=83=86=E3=82=B9?= =?UTF-8?q?=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/SettingsNavigationTests.swift | 69 ++++++++++++++++++++ 1 file changed, 69 insertions(+) create mode 100644 ArkServerTests/SettingsNavigationTests.swift diff --git a/ArkServerTests/SettingsNavigationTests.swift b/ArkServerTests/SettingsNavigationTests.swift new file mode 100644 index 0000000..6f9c916 --- /dev/null +++ b/ArkServerTests/SettingsNavigationTests.swift @@ -0,0 +1,69 @@ +// ArkServerTests/SettingsNavigationTests.swift + +import Foundation +import Testing +@testable import ArkServer + +@Suite(.serialized) +struct SettingsNavigationTests { + @Test + func everyPaneIsListedExactlyOnceUnderOneGroup() { + let grouped = SettingsPane.grouped + let listed = grouped.flatMap(\.panes) + + #expect(listed.count == SettingsPane.allCases.count) + #expect(Set(listed) == Set(SettingsPane.allCases)) + // どの項目も、自分が属する見出しの下に並ぶ。 + for entry in grouped { + #expect(entry.panes.allSatisfy { $0.group == entry.group }) + #expect(!entry.panes.isEmpty) + } + // 項目名とアイコンは空でなく、重複もしない。 + #expect(SettingsPane.allCases.allSatisfy { !$0.title.isEmpty && !$0.symbol.isEmpty }) + #expect(Set(SettingsPane.allCases.map(\.title)).count == SettingsPane.allCases.count) + } + + @Test @MainActor + func openingSettingsRemembersWhereYouWereAndClosingGoesBack() { + var routing = SettingsRouting() + let albumID = UUID() + + let opened = routing.opening(from: .album(albumID), pane: .appearance) + + #expect(opened == .settings(.appearance)) + #expect(routing.closing() == .album(albumID)) + } + + @Test @MainActor + func switchingPanesInsideSettingsKeepsTheOriginalReturnPoint() { + var routing = SettingsRouting() + + _ = routing.opening(from: .favorites, pane: .connection) + let second = routing.opening(from: .settings(.connection), pane: .shortcuts) + let third = routing.opening(from: second, pane: .data) + + #expect(third == .settings(.data)) + // 設定の中で何度項目を切り替えても、戻り先は最初の「お気に入り」のまま。 + #expect(routing.closing() == .favorites) + } + + @Test @MainActor + func returnsHomeWhenNothingWasSelectedAndRemembersANewPlaceNextTime() { + var routing = SettingsRouting() + + _ = routing.opening(from: nil, pane: .connection) + #expect(routing.closing() == .home) + + // 一度閉じたあと、別の画面から開き直したら、その画面へ戻る。 + _ = routing.opening(from: .trash, pane: .export) + #expect(routing.closing() == .trash) + } + + @Test @MainActor + func recognisesWhetherASelectionIsInsideSettings() { + #expect(SettingsRouting.isSettings(.settings(.updates))) + #expect(!SettingsRouting.isSettings(.home)) + #expect(!SettingsRouting.isSettings(.musicVideo)) + #expect(!SettingsRouting.isSettings(nil)) + } +} From d11173a1fc94b232375f648808b460a86e7386ed Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8E=9F=E3=80=80=E9=A2=AF=E7=99=BB?= Date: Wed, 4 Nov 2026 13:22:46 +0900 Subject: [PATCH 4/9] =?UTF-8?q?refactor(ui):=20=E3=83=9B=E3=83=BC=E3=83=A0?= =?UTF-8?q?=E3=83=BB=E3=83=A9=E3=82=A4=E3=83=96=E3=83=A9=E3=83=AA=E3=83=BB?= =?UTF-8?q?=E3=82=B9=E3=83=88=E3=83=AC=E3=83=BC=E3=82=B8=E7=AE=A1=E7=90=86?= =?UTF-8?q?=E3=81=AA=E3=81=A9=E5=90=84=E7=94=BB=E9=9D=A2=E3=81=AE=E3=82=BF?= =?UTF-8?q?=E3=82=A4=E3=83=9D=E3=82=B0=E3=83=A9=E3=83=95=E3=82=A3=E3=81=A8?= =?UTF-8?q?=E8=A8=AD=E5=AE=9A=E8=A1=8C=E8=A1=A8=E7=A4=BA=E3=82=92=E7=B5=B1?= =?UTF-8?q?=E4=B8=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Views/DashboardMetricViews.swift | 6 +- .../Features/Dashboard/Views/HomeView.swift | 95 ++++++++++------ .../Dashboard/Views/ServerHeroCard.swift | 20 ++-- .../Library/Views/AlbumDetailView.swift | 6 +- .../Library/Views/AlbumOverviewView.swift | 6 +- .../Library/Views/FolderDetailView.swift | 14 +-- .../Library/Views/LibraryCategoryView.swift | 2 +- .../Library/Views/MediaGallerySupport.swift | 4 +- .../Library/Views/MediaGridItem.swift | 4 +- .../Views/SimilarMediaView.swift | 8 +- .../Views/SketchCleanupView.swift | 2 +- .../Views/AnalysisPlayerView.swift | 2 +- .../Views/CandidateListView.swift | 10 +- .../Views/CandidateTimelineView.swift | 2 +- .../Views/SceneExtractionTutorialView.swift | 14 +-- .../Features/Server/Views/AccessLogView.swift | 8 +- .../Storage/Views/StorageManagerView.swift | 106 ++++++++---------- 17 files changed, 157 insertions(+), 152 deletions(-) diff --git a/ArkServer/Features/Dashboard/Views/DashboardMetricViews.swift b/ArkServer/Features/Dashboard/Views/DashboardMetricViews.swift index 7274754..d1def42 100644 --- a/ArkServer/Features/Dashboard/Views/DashboardMetricViews.swift +++ b/ArkServer/Features/Dashboard/Views/DashboardMetricViews.swift @@ -14,7 +14,7 @@ struct DuplicateCheckCountBadge: View { .font(.appCaption) .foregroundStyle(NeomorphicTheme.muted) Text(count.formatted()) - .font(.system(size: 22, weight: .semibold)) + .font(.appMetric) .monospacedDigit() .foregroundStyle(NeomorphicTheme.ink) } @@ -39,7 +39,7 @@ struct ResourceGauge: View { Text(label) } currentValueLabel: { Text("\(Int(value))%") - .font(.system(size: 11, weight: .bold)) + .font(.appMicroStrong) .monospacedDigit() } .gaugeStyle(.accessoryCircularCapacity) @@ -48,7 +48,7 @@ struct ResourceGauge: View { .frame(width: 52, height: 52) Text(label) - .font(.system(size: 11, weight: .medium)) + .font(.appMicroStrong) .foregroundStyle(.secondary) } } diff --git a/ArkServer/Features/Dashboard/Views/HomeView.swift b/ArkServer/Features/Dashboard/Views/HomeView.swift index d520d91..b91106a 100644 --- a/ArkServer/Features/Dashboard/Views/HomeView.swift +++ b/ArkServer/Features/Dashboard/Views/HomeView.swift @@ -24,6 +24,34 @@ struct HomeView: View { self.linkedFolderScanStatus = dataManager.linkedFolderScanStatus } + /// 2列にするときの、1列あたりの最低幅。サーバーカードの「停止中」と「開始」が省略されない幅。 + private static let homeColumnMinWidth: CGFloat = 400 + /// ページ周囲の余白(4pt刻み)。 + private static let homePagePadding: CGFloat = 32 + + /// 接続に必要な「サーバーの状態」を先頭に置く左の列。 + private var leftColumn: some View { + VStack(spacing: DS.cardSpacing) { + ServerHeroCard(webServerManager: webServerManager) + connectionCard + scheduleCard + duplicateCheckCard + storageCard + } + } + + private var rightColumn: some View { + VStack(spacing: DS.cardSpacing) { + securityCard + resourcesCard + linkedFolderCard + if !dataManager.linkedFolderConflicts.isEmpty { + linkedFolderConflictCard + } + logsCard + } + } + var body: some View { ZStack { NeomorphicHomeBackground() @@ -36,31 +64,24 @@ struct HomeView: View { // 左右のカラムを独立して積むことで,縦長カードの横に空白が残らない。 // 接続に必要な「サーバーの状態」と「PIN認証」を各カラムの先頭に置く // (以前の「設定の概要」は,すぐ下の設定カードと同じ項目の繰り返しだったので廃止)。 - HStack(alignment: .top, spacing: DS.cardSpacing) { - VStack(spacing: DS.cardSpacing) { - ServerHeroCard(webServerManager: webServerManager) - connectionCard - scheduleCard - duplicateCheckCard - storageCard + // 各列には、サーバー状態と「開始/停止」が文字で読める最低幅(homeColumnMinWidth)を確保する。 + // 2列分の幅がないときは、同じ順序のまま1列に積む(サイドバー表示つきの最小ウィンドウ幅など)。 + ViewThatFits(in: .horizontal) { + HStack(alignment: .top, spacing: DS.cardSpacing) { + leftColumn + .frame(minWidth: Self.homeColumnMinWidth, maxWidth: .infinity, alignment: .top) + rightColumn + .frame(minWidth: Self.homeColumnMinWidth, maxWidth: .infinity, alignment: .top) } - .frame(maxWidth: .infinity, alignment: .top) - VStack(spacing: DS.cardSpacing) { - securityCard - resourcesCard - linkedFolderCard - if !dataManager.linkedFolderConflicts.isEmpty { - linkedFolderConflictCard - } - logsCard + leftColumn + rightColumn } - .frame(maxWidth: .infinity, alignment: .top) } } .frame(maxWidth: 1040) - .padding(.horizontal, 30) - .padding(.vertical, 30) + .padding(.horizontal, Self.homePagePadding) + .padding(.vertical, Self.homePagePadding) .frame(maxWidth: .infinity) } } @@ -171,7 +192,7 @@ struct HomeView: View { SettingRow(label: "リンク中のフォルダ") { Text("\(count)フォルダ") - .font(.system(size: 13, weight: .semibold)) + .font(.appBodyStrong) .monospacedDigit() } @@ -227,11 +248,11 @@ struct HomeView: View { ProgressView() .controlSize(.small) Text("リンクフォルダを更新中…") - .font(.system(size: 12, weight: .semibold)) + .font(.appCaptionStrong) Spacer() if status.totalCount > 0 { Text("\(min(status.processedCount + 1, status.totalCount)) / \(status.totalCount)") - .font(.system(size: 11, design: .monospaced)) + .font(.appMonoMicro) .foregroundStyle(.secondary) } } @@ -253,7 +274,7 @@ struct HomeView: View { Spacer() if status.processedItemsInCurrentFolder > 0 { Text("\(status.processedItemsInCurrentFolder)件取り込み") - .font(.system(size: 11, design: .monospaced)) + .font(.appMonoMicro) .foregroundStyle(.secondary) } } @@ -284,7 +305,7 @@ struct HomeView: View { .foregroundStyle(.yellow) .font(.appCaption) Text(conflict.albumName) - .font(.system(size: 12, weight: .semibold)) + .font(.appCaptionStrong) .lineLimit(1) .truncationMode(.middle) Spacer() @@ -319,8 +340,10 @@ struct HomeView: View { .background( RoundedRectangle(cornerRadius: 8, style: .continuous) .fill(NeomorphicTheme.surface) - .shadow(color: .white.opacity(0.86), radius: 4, x: -3, y: -3) - .shadow(color: NeomorphicTheme.shadow.opacity(0.22), radius: 7, x: 4, y: 4) + .overlay( + RoundedRectangle(cornerRadius: 8, style: .continuous) + .strokeBorder(NeomorphicTheme.cardBorder, lineWidth: 1) + ) ) } } @@ -337,7 +360,7 @@ struct HomeView: View { private func duplicateAlbumList(title: String, albums: [Album], emptyMessage: String) -> some View { VStack(alignment: .leading, spacing: 6) { Text(title) - .font(.system(size: 11, weight: .semibold)) + .font(.appMicroStrong) .foregroundStyle(.secondary) if albums.isEmpty { @@ -353,7 +376,7 @@ struct HomeView: View { .truncationMode(.middle) Spacer() Text("\(album.videoIDs.count)件") - .font(.system(size: 11, design: .monospaced)) + .font(.appMonoMicro) .foregroundStyle(.secondary) } } @@ -546,7 +569,7 @@ struct HomeView: View { AxisMarks(values: [0, 50, 100]) { AxisGridLine(stroke: StrokeStyle(lineWidth: 0.5, dash: [3])) AxisValueLabel() - .font(.system(size: 8)) + .font(.appMicro.monospacedDigit()) } } .frame(height: 90) @@ -565,12 +588,12 @@ struct HomeView: View { SettingRow(label: "総アイテム数") { Text("\(dataManager.videos.count)件") - .font(.system(size: 13, weight: .semibold)) + .font(.appBodyStrong) .monospacedDigit() } SettingRow(label: "使用容量") { Text(dataManager.totalStorageSizeText) - .font(.system(size: 13, weight: .semibold)) + .font(.appBodyStrong) .monospacedDigit() } @@ -593,7 +616,7 @@ struct HomeView: View { CardHeader(icon: "network.badge.shield.half.filled", tint: NeomorphicTheme.accent, title: "最近のアクセス", subtitle: "端末からの通信履歴(接続台数ではありません)") Spacer() Button("すべて見る") { isShowingAccessLog = true } - .font(.system(size: 11, weight: .semibold)) + .font(.appMicroStrong) .buttonStyle(.plain) .foregroundStyle(NeomorphicTheme.muted) } @@ -626,7 +649,7 @@ struct HomeView: View { ForEach(filteredLogs.prefix(15)) { entry in HStack(spacing: 8) { Text(entry.date.formatted(.dateTime.hour().minute().second())) - .font(.system(size: 11, design: .monospaced)) + .font(.appMonoMicro) .foregroundStyle(.secondary) .frame(width: 58, alignment: .leading) @@ -635,7 +658,7 @@ struct HomeView: View { .font(.appMicro) Text(entry.method) - .font(.system(size: 11, weight: .bold, design: .monospaced)) + .font(.appMonoMicro.weight(.medium)) .foregroundStyle(entry.method == "GET" ? .blue : .purple) .frame(width: 36, alignment: .leading) @@ -648,7 +671,7 @@ struct HomeView: View { Spacer(minLength: 5) Text(entry.ip) - .font(.system(size: 11, design: .monospaced)) + .font(.appMonoMicro) .foregroundStyle(.tertiary) } .padding(.vertical, 4) @@ -656,8 +679,6 @@ struct HomeView: View { .background( RoundedRectangle(cornerRadius: 6, style: .continuous) .fill(NeomorphicTheme.surface) - .shadow(color: .white.opacity(0.72), radius: 2, x: -1, y: -1) - .shadow(color: NeomorphicTheme.shadow.opacity(0.16), radius: 4, x: 2, y: 2) ) } } diff --git a/ArkServer/Features/Dashboard/Views/ServerHeroCard.swift b/ArkServer/Features/Dashboard/Views/ServerHeroCard.swift index 880a943..c175c13 100644 --- a/ArkServer/Features/Dashboard/Views/ServerHeroCard.swift +++ b/ArkServer/Features/Dashboard/Views/ServerHeroCard.swift @@ -9,7 +9,7 @@ struct ServerHeroCard: View { var body: some View { NeomorphicTile(padding: DS.cardPadding) { - VStack(alignment: .leading, spacing: 18) { + VStack(alignment: .leading, spacing: 16) { CardHeader(icon: "network", tint: NeomorphicTheme.accent, title: "サーバーの状態") statusRow @@ -46,11 +46,11 @@ struct ServerHeroCard: View { HStack(spacing: 12) { StatusDot(active: webServerManager.isRunning) Text(webServerManager.isRunning ? "配信中" : "停止中") - .font(.system(size: 30, weight: .bold, design: .default)) + .font(.appStatus) if webServerManager.isRunning { // 稼働時間は補足なので、状態の文字より小さく控えめに添える。 Text("稼働 \(webServerManager.uptimeString)") - .font(.system(size: 13).monospacedDigit()) + .font(.appBody.monospacedDigit()) .foregroundStyle(NeomorphicTheme.muted) .padding(.top, 8) } @@ -59,7 +59,7 @@ struct ServerHeroCard: View { // 停止は主役の操作ではない(誤って押したくもない)ので、塗りつぶさない。 Button(action: toggleServer) { Label("停止", systemImage: "stop.fill") - .font(.system(size: 13, weight: .medium)) + .font(.appBodyStrong) .padding(.horizontal, 6) .padding(.vertical, 3) } @@ -69,7 +69,7 @@ struct ServerHeroCard: View { } else { Button(action: toggleServer) { Label("開始", systemImage: "power") - .font(.system(size: 13, weight: .semibold)) + .font(.appBodyStrong) .padding(.horizontal, 8) .padding(.vertical, 4) } @@ -82,7 +82,7 @@ struct ServerHeroCard: View { // MARK: 稼働中:いまの接続先 private var runningDetails: some View { - VStack(alignment: .leading, spacing: 14) { + VStack(alignment: .leading, spacing: 16) { VStack(alignment: .leading, spacing: 8) { Text("ブラウザの接続先") .font(.appCaption) @@ -101,7 +101,7 @@ struct ServerHeroCard: View { if let target = URL(string: url) { NSWorkspace.shared.open(target) } } label: { Label("開く", systemImage: "arrow.up.forward.app") - .font(.system(size: 13, weight: .medium)) + .font(.appBodyStrong) } .buttonStyle(.bordered) .tint(NeomorphicTheme.ink) @@ -124,7 +124,7 @@ struct ServerHeroCard: View { QRCodeView(text: url, size: 96) VStack(alignment: .leading, spacing: 6) { Text("スマホで読み取る") - .font(.system(size: 13, weight: .semibold)) + .font(.appBodyStrong) Text(webServerManager.authEnabled ? "カメラで読み取ると,ブラウザで接続先が開きます.開いたら「PIN認証」の6桁のPINを入力します." : "カメラで読み取ると,ブラウザで接続先が開きます.(PIN認証は無効です)") @@ -146,7 +146,7 @@ struct ServerHeroCard: View { private var connectionSteps: some View { VStack(alignment: .leading, spacing: 12) { Text("接続方法") - .font(.system(size: 13, weight: .semibold)) + .font(.appBodyStrong) step(1, "端末をMacと同じWi-Fiに接続します.") step(2, "iPhoneアプリでこのMacを選ぶか,ブラウザで接続先を開きます.") step(3, webServerManager.authEnabled @@ -163,7 +163,7 @@ struct ServerHeroCard: View { private func step(_ number: Int, _ text: String) -> some View { HStack(alignment: .firstTextBaseline, spacing: 10) { Text("\(number)") - .font(.system(size: 11, weight: .semibold).monospacedDigit()) + .font(.appMicroStrong.monospacedDigit()) .foregroundStyle(NeomorphicTheme.muted) .frame(width: 20, height: 20) .background(Circle().fill(NeomorphicTheme.control)) diff --git a/ArkServer/Features/Library/Views/AlbumDetailView.swift b/ArkServer/Features/Library/Views/AlbumDetailView.swift index 7b0caf7..41c0049 100644 --- a/ArkServer/Features/Library/Views/AlbumDetailView.swift +++ b/ArkServer/Features/Library/Views/AlbumDetailView.swift @@ -480,7 +480,7 @@ struct AlbumDetailView: View { .sheet(isPresented: $showSplitSheet) { VStack(spacing: 20) { Text("分割再生") - .font(.system(size: 17, weight: .semibold)) + .font(.appTitle) if let video = splitTargetVideo { Text(video.originalFilename) .font(.appBody) @@ -796,7 +796,7 @@ struct AlbumDetailView: View { .font(.system(size: 42, weight: .light)) .foregroundStyle(.secondary) Text("メディアがありません") - .font(.appTitle.weight(.semibold)) + .font(.appTitle) Text("ファイルやフォルダをここにドロップして追加") .font(.appBody) .foregroundStyle(.secondary) @@ -819,7 +819,7 @@ struct AlbumDetailView: View { .font(.system(size: 44)) .foregroundStyle(Color.accentColor) Text("ドロップして追加") - .font(.appTitle.weight(.semibold)) + .font(.appTitle) } } .overlay( diff --git a/ArkServer/Features/Library/Views/AlbumOverviewView.swift b/ArkServer/Features/Library/Views/AlbumOverviewView.swift index c9da5f9..e21d912 100644 --- a/ArkServer/Features/Library/Views/AlbumOverviewView.swift +++ b/ArkServer/Features/Library/Views/AlbumOverviewView.swift @@ -194,10 +194,10 @@ struct AlbumOverviewView: View { private func sectionTitle(_ title: String, count: Int) -> some View { HStack(spacing: 8) { Text(title) - .font(.system(size: 12, weight: .bold, design: .default)) - .foregroundStyle(.secondary) + .font(.appBody.weight(.medium)) + .foregroundStyle(NeomorphicTheme.muted) Text("\(count.formatted())") - .font(.system(size: 11, weight: .semibold, design: .monospaced)) + .font(.appMonoMicro.weight(.medium)) .foregroundStyle(.tertiary) } .padding(.leading, 4) diff --git a/ArkServer/Features/Library/Views/FolderDetailView.swift b/ArkServer/Features/Library/Views/FolderDetailView.swift index 7ee9077..ad5326b 100644 --- a/ArkServer/Features/Library/Views/FolderDetailView.swift +++ b/ArkServer/Features/Library/Views/FolderDetailView.swift @@ -163,10 +163,10 @@ struct FolderDetailView: View { private func sectionTitle(_ title: String, count: Int) -> some View { HStack(spacing: 8) { Text(title) - .font(.system(size: 12, weight: .bold, design: .default)) - .foregroundStyle(.secondary) + .font(.appBody.weight(.medium)) + .foregroundStyle(NeomorphicTheme.muted) Text("\(count)") - .font(.system(size: 11, weight: .semibold, design: .monospaced)) + .font(.appMonoMicro.weight(.medium)) .foregroundStyle(.tertiary) } .padding(.leading, 4) @@ -185,7 +185,7 @@ struct FolderDetailView: View { Image(systemName: isPhoto ? "photo.stack" : "film.stack") .font(.system(size: 11, weight: .semibold)) Text("アルバム") - .font(.system(size: 12, weight: .medium, design: .default)) + .font(.appCaptionStrong) } .foregroundStyle(.secondary) } @@ -210,7 +210,7 @@ struct FolderDetailView: View { ) } label: { Text(part) - .font(.system(size: 12, weight: isLast ? .bold : .medium, design: .default)) + .font(isLast ? Font.appCaptionStrong : Font.appCaption) .foregroundStyle(isLast ? Color.primary : Color.secondary) } .buttonStyle(.plain) @@ -444,7 +444,7 @@ struct FolderEntryTile: View { } .overlay(alignment: .topTrailing) { Text("\(entry.count)") - .font(.appMicro.weight(.semibold)) + .font(.appMicroStrong) .monospacedDigit() .foregroundStyle(.white) .padding(.horizontal, 6) @@ -456,7 +456,7 @@ struct FolderEntryTile: View { if showTitle { VStack(alignment: .leading, spacing: 1) { Text(entry.title) - .font(.system(size: 12, weight: .medium)) + .font(.appCaptionStrong) .lineLimit(1) .truncationMode(.middle) if showDetail { diff --git a/ArkServer/Features/Library/Views/LibraryCategoryView.swift b/ArkServer/Features/Library/Views/LibraryCategoryView.swift index 32be7ce..64e5428 100644 --- a/ArkServer/Features/Library/Views/LibraryCategoryView.swift +++ b/ArkServer/Features/Library/Views/LibraryCategoryView.swift @@ -370,7 +370,7 @@ struct LibraryCategoryView: View { .sheet(isPresented: $showSplitSheet) { VStack(spacing: 20) { Text("分割再生") - .font(.system(size: 17, weight: .semibold)) + .font(.appTitle) if let video = splitTargetVideo { Text(video.originalFilename) .font(.appBody) diff --git a/ArkServer/Features/Library/Views/MediaGallerySupport.swift b/ArkServer/Features/Library/Views/MediaGallerySupport.swift index 99a2b4b..a69c762 100644 --- a/ArkServer/Features/Library/Views/MediaGallerySupport.swift +++ b/ArkServer/Features/Library/Views/MediaGallerySupport.swift @@ -84,10 +84,10 @@ struct MediaDeletionConfirmationSheet: View { VStack(alignment: .leading, spacing: 16) { HStack(spacing: 10) { Label("削除方法を選んでください", systemImage: "trash") - .font(.system(size: 17, weight: .semibold)) + .font(.appTitle) Spacer() Text("\(items.count.formatted())件を選択中") - .font(.system(size: 13).monospacedDigit()) + .font(.appBody.monospacedDigit()) .foregroundStyle(NeomorphicTheme.muted) } diff --git a/ArkServer/Features/Library/Views/MediaGridItem.swift b/ArkServer/Features/Library/Views/MediaGridItem.swift index 9b22c7c..0fc65e9 100644 --- a/ArkServer/Features/Library/Views/MediaGridItem.swift +++ b/ArkServer/Features/Library/Views/MediaGridItem.swift @@ -118,7 +118,7 @@ struct MediaGridItem: View { .overlay(alignment: .bottomTrailing) { if video.mediaType == .video, video.duration > 0 { Text(formatDuration(video.duration)) - .font(.system(size: 11, weight: .medium)) + .font(.appMicroStrong) .monospacedDigit() .foregroundStyle(.white) .padding(.horizontal, 6) @@ -152,7 +152,7 @@ struct MediaGridItem: View { VStack(alignment: .leading, spacing: 2) { if showTitle { Text(video.originalFilename) - .font(.system(size: 12, weight: .medium)) + .font(.appCaptionStrong) .foregroundStyle(NeomorphicTheme.ink) .lineLimit(1) .truncationMode(.middle) diff --git a/ArkServer/Features/MediaAnalysis/Views/SimilarMediaView.swift b/ArkServer/Features/MediaAnalysis/Views/SimilarMediaView.swift index 9692726..ef4288e 100644 --- a/ArkServer/Features/MediaAnalysis/Views/SimilarMediaView.swift +++ b/ArkServer/Features/MediaAnalysis/Views/SimilarMediaView.swift @@ -101,7 +101,7 @@ struct SimilarMediaView: View { .foregroundStyle(.secondary) if group.hasAudioDifferences { Label("音声が異なる版を含みます", systemImage: "waveform.badge.exclamationmark") - .font(.appMicro.weight(.semibold)) + .font(.appMicroStrong) .foregroundStyle(.orange) } } @@ -135,7 +135,7 @@ struct SimilarMediaView: View { ) .overlay(alignment: .bottomLeading) { Text(isKept ? "残す候補" : (isSelected ? "削除" : "対象外")) - .font(.appMicro.weight(.bold)) + .font(.appMicroStrong) .foregroundStyle(.white) .padding(.horizontal, 6) .padding(.vertical, 3) @@ -174,7 +174,7 @@ struct SimilarMediaView: View { Text(String(format: "映像 %.1f Mbps", details.videoBitrate / 1_000_000)) } } - .font(.system(size: 11).monospacedDigit()) + .font(.appMicro.monospacedDigit()) .foregroundStyle(.secondary) .frame(width: thumbnailSide) } @@ -204,7 +204,7 @@ struct SimilarMediaView: View { private func metadataBadge(_ title: String, systemImage: String, color: Color) -> some View { Label(title, systemImage: systemImage) - .font(.system(size: 11, weight: .medium)) + .font(.appMicroStrong) .foregroundStyle(color) .padding(.horizontal, 6) .padding(.vertical, 3) diff --git a/ArkServer/Features/MediaAnalysis/Views/SketchCleanupView.swift b/ArkServer/Features/MediaAnalysis/Views/SketchCleanupView.swift index 36a6983..5b944bd 100644 --- a/ArkServer/Features/MediaAnalysis/Views/SketchCleanupView.swift +++ b/ArkServer/Features/MediaAnalysis/Views/SketchCleanupView.swift @@ -116,7 +116,7 @@ struct SketchCleanupView: View { } .overlay(alignment: .bottomTrailing) { Text("\(candidate.judgement.kind.displayName) \(Int(candidate.judgement.score * 100))%") - .font(.appMicro.weight(.semibold)) + .font(.appMicroStrong) .foregroundStyle(.white) .padding(.horizontal, 6) .padding(.vertical, 3) diff --git a/ArkServer/Features/SceneExtraction/Views/AnalysisPlayerView.swift b/ArkServer/Features/SceneExtraction/Views/AnalysisPlayerView.swift index f6f4699..b45b05a 100644 --- a/ArkServer/Features/SceneExtraction/Views/AnalysisPlayerView.swift +++ b/ArkServer/Features/SceneExtraction/Views/AnalysisPlayerView.swift @@ -98,7 +98,7 @@ struct AnalysisPlayerView: View { Spacer() Text("\(timeText(viewModel.currentTime)) / \(timeText(viewModel.duration))") - .font(.system(size: 13, design: .monospaced)) + .font(.appMonoBody) .foregroundStyle(NeomorphicTheme.muted) } .buttonStyle(.borderless) diff --git a/ArkServer/Features/SceneExtraction/Views/CandidateListView.swift b/ArkServer/Features/SceneExtraction/Views/CandidateListView.swift index ce05fde..159b11d 100644 --- a/ArkServer/Features/SceneExtraction/Views/CandidateListView.swift +++ b/ArkServer/Features/SceneExtraction/Views/CandidateListView.swift @@ -129,9 +129,9 @@ struct CandidateListView: View { VStack(alignment: .leading, spacing: 4) { HStack(spacing: 10) { Text("ピーク \(timeText(candidate.peakTime))") - .font(.appBody.weight(.semibold)) + .font(.appBodyStrong) Text(String(format: "score %.3f", candidate.score)) - .font(.system(size: 12, design: .monospaced)) + .font(.appMonoCaption) .foregroundStyle(.secondary) labelBadge(candidate.userLabel) } @@ -156,7 +156,7 @@ struct CandidateListView: View { format: .number.precision(.fractionLength(2)) ) } - .font(.system(size: 12, design: .monospaced)) + .font(.appMonoCaption) .textFieldStyle(.roundedBorder) .frame(maxWidth: 245) @@ -169,7 +169,7 @@ struct CandidateListView: View { Spacer() Text(String(format: "A %.2f B %.2f C %.2f", candidate.audioScore, candidate.visualScore, candidate.transitionScore)) - .font(.system(size: 11, design: .monospaced)) + .font(.appMonoMicro) .foregroundStyle(NeomorphicTheme.muted) HStack(spacing: 5) { @@ -257,7 +257,7 @@ struct CandidateListView: View { private func labelBadge(_ label: CandidateLabel?) -> some View { Text(label?.displayName ?? "未判定") - .font(.appMicro.weight(.semibold)) + .font(.appMicroStrong) .foregroundStyle(label.map(labelColor) ?? NeomorphicTheme.muted) .padding(.horizontal, 7) .padding(.vertical, 2) diff --git a/ArkServer/Features/SceneExtraction/Views/CandidateTimelineView.swift b/ArkServer/Features/SceneExtraction/Views/CandidateTimelineView.swift index 2fde4b1..b14786a 100644 --- a/ArkServer/Features/SceneExtraction/Views/CandidateTimelineView.swift +++ b/ArkServer/Features/SceneExtraction/Views/CandidateTimelineView.swift @@ -62,7 +62,7 @@ struct CandidateTimelineView: View { .fill(.white.opacity(0.2)) .frame(width: 1, height: 28) Text(timeText(tickTime)) - .font(.system(size: 11, design: .monospaced)) + .font(.appMonoMicro) .foregroundStyle(NeomorphicTheme.muted) } .offset(x: max(0, xPosition(for: tickTime, width: width) - 18)) diff --git a/ArkServer/Features/SceneExtraction/Views/SceneExtractionTutorialView.swift b/ArkServer/Features/SceneExtraction/Views/SceneExtractionTutorialView.swift index 405c52a..8ed2e82 100644 --- a/ArkServer/Features/SceneExtraction/Views/SceneExtractionTutorialView.swift +++ b/ArkServer/Features/SceneExtraction/Views/SceneExtractionTutorialView.swift @@ -253,12 +253,12 @@ struct SceneExtractionTutorialView: View { VStack(alignment: .leading, spacing: 7) { Text("STEP \(step.id)") - .font(.system(size: 12, weight: .semibold)) + .font(.appCaptionStrong) .foregroundStyle(NeomorphicTheme.muted) Text(step.title) .font(.appLargeTitle) Text(step.summary) - .font(.system(size: 15)) + .font(.appHeadline.weight(.regular)) .foregroundStyle(NeomorphicTheme.muted) } } @@ -280,7 +280,7 @@ struct SceneExtractionTutorialView: View { .foregroundStyle(NeomorphicTheme.caution) VStack(alignment: .leading, spacing: 3) { Text("ヒント") - .font(.appBody.weight(.semibold)) + .font(.appBodyStrong) Text(step.tip) .font(.appBody) .foregroundStyle(NeomorphicTheme.muted) @@ -306,7 +306,7 @@ struct SceneExtractionTutorialView: View { } label: { VStack(spacing: 5) { Text("\(step.id)") - .font(.appCaption.bold()) + .font(.appCaptionStrong) .frame(width: 28, height: 28) // いまの手順は白い丸に暗い数字(再生ボタンと同じ表し方)、ほかは薄い面。 .background( @@ -342,7 +342,7 @@ struct SceneExtractionTutorialView: View { Spacer() Text("\(selectedStepIndex + 1) / \(SceneExtractionTutorialContent.steps.count)") - .font(.system(size: 12).monospacedDigit()) + .font(.appCaption.monospacedDigit()) .foregroundStyle(NeomorphicTheme.muted) Spacer() @@ -411,9 +411,9 @@ struct SceneExtractionTutorialView: View { VStack(alignment: .leading, spacing: 8) { HStack { Text(glossaryTerm.term) - .font(.appBody.weight(.semibold)) + .font(.appBodyStrong) Text(glossaryTerm.category.rawValue) - .font(.system(size: 11, weight: .medium)) + .font(.appMicroStrong) .foregroundStyle(NeomorphicTheme.muted) .padding(.horizontal, 7) .padding(.vertical, 3) diff --git a/ArkServer/Features/Server/Views/AccessLogView.swift b/ArkServer/Features/Server/Views/AccessLogView.swift index 69f39bb..0d631ec 100644 --- a/ArkServer/Features/Server/Views/AccessLogView.swift +++ b/ArkServer/Features/Server/Views/AccessLogView.swift @@ -54,16 +54,16 @@ struct AccessLogView: View { Table(filteredLogs) { TableColumn("時刻") { entry in Text(AccessLogView.timeFormatter.string(from: entry.date)) - .font(.system(size: 12, design: .monospaced)) + .font(.appMonoCaption) } .width(110) TableColumn("IP") { entry in - Text(entry.ip).font(.system(size: 12, design: .monospaced)) + Text(entry.ip).font(.appMonoCaption) } .width(110) TableColumn("メソッド") { entry in Text(entry.method) - .font(.appMicro.weight(.semibold)) + .font(.appMicroStrong) .padding(.horizontal, 6) .padding(.vertical, 2) .background(Capsule().fill(NeomorphicTheme.control)) @@ -75,7 +75,7 @@ struct AccessLogView: View { } TableColumn("認証") { entry in Text(entry.authorized ? "許可" : "拒否") - .font(.appMicro.weight(.semibold)) + .font(.appMicroStrong) .padding(.horizontal, 6) .padding(.vertical, 2) .background(Capsule().fill((entry.authorized ? NeomorphicTheme.online : Color.red).opacity(0.15))) diff --git a/ArkServer/Features/Storage/Views/StorageManagerView.swift b/ArkServer/Features/Storage/Views/StorageManagerView.swift index 8c3ab21..d142100 100644 --- a/ArkServer/Features/Storage/Views/StorageManagerView.swift +++ b/ArkServer/Features/Storage/Views/StorageManagerView.swift @@ -12,15 +12,18 @@ struct StorageManagerView: View { } var body: some View { - VStack(spacing: 18) { + VStack(spacing: 20) { SheetHeader( icon: "internaldrive", title: "ストレージ管理", subtitle: "このアプリがMac内に保存しているデータの内訳" ) - VStack(alignment: .leading, spacing: 14) { + // 設定画面と同じ「行を重ねた面」で、内訳(左に名前、右に容量)を見せる。 + SettingsGroup { usageBar + .padding(.horizontal, 16) + .padding(.vertical, 16) breakdownRow( color: Self.usageColors[0], @@ -38,73 +41,52 @@ struct StorageManagerView: View { size: viewModel.usage.downloadsSize ) - Divider() - - HStack { - Text("総使用容量") - .font(.system(size: 13, weight: .semibold)) - Spacer() + SettingsRow(title: "総使用容量") { Text(viewModel.formatBytes(viewModel.usage.appTotalSize)) - .font(.appTitle.bold()) + .font(.appTitle.weight(.semibold)) .monospacedDigit() .foregroundStyle( viewModel.usage.appTotalSize > 10_000_000_000 ? .red - : .primary + : NeomorphicTheme.ink ) } } - .dashboardCard() if viewModel.isOptimizing { VStack(spacing: 8) { ProgressView() Text(viewModel.optimizationMessage) .font(.appCaption) - .foregroundStyle(.secondary) + .foregroundStyle(NeomorphicTheme.muted) } .frame(maxWidth: .infinity, minHeight: 130) } else { - VStack(spacing: 10) { - Button(action: viewModel.cleanupMissingFiles) { - Label("リンク切れメディアを整理", systemImage: "link.badge.minus") - .frame(maxWidth: .infinity) - } - .buttonStyle(.bordered) - .controlSize(.large) - - Text("Mac上の元ファイルが削除されて「見つかりません」になったデータを一括整理します.") - .font(.appCaption) - .foregroundStyle(NeomorphicTheme.muted) - .multilineTextAlignment(.center) - .fixedSize(horizontal: false, vertical: true) - - Button(action: viewModel.removeDuplicates) { - Label("重複動画を検出して削除", systemImage: "sparkles") - .frame(maxWidth: .infinity) - } - .buttonStyle(.bordered) - .controlSize(.large) - - Text("タイトルが違っても内容が完全に一致する動画を自動で整理します.") - .font(.appCaption) - .foregroundStyle(NeomorphicTheme.muted) - .multilineTextAlignment(.center) - .fixedSize(horizontal: false, vertical: true) - - HStack(spacing: 10) { - Button(action: viewModel.openDataFolder) { - Label("データフォルダを開く", systemImage: "folder") - .frame(maxWidth: .infinity) + SettingsSection(title: "整理") { + SettingsGroup { + SettingsRow( + title: "リンク切れメディアを整理", + detail: "Mac上の元ファイルが削除されて「見つかりません」になったデータを一括整理します." + ) { + Button("整理", action: viewModel.cleanupMissingFiles) + .buttonStyle(.quiet) } - Button(action: viewModel.openTemporaryFolder) { - Label("一時キャッシュを開く", systemImage: "folder.badge.gearshape") - .frame(maxWidth: .infinity) + SettingsRow( + title: "重複動画を検出して削除", + detail: "タイトルが違っても内容が完全に一致する動画を自動で整理します." + ) { + Button("検出して削除", action: viewModel.removeDuplicates) + .buttonStyle(.quiet) + } + SettingsRow(title: "フォルダを開く") { + HStack(spacing: 8) { + Button("データ", action: viewModel.openDataFolder) + Button("一時キャッシュ", action: viewModel.openTemporaryFolder) + } + .buttonStyle(.quiet) } } - .controlSize(.large) } - .frame(maxWidth: .infinity, minHeight: 130) } Spacer(minLength: 0) @@ -115,8 +97,8 @@ struct StorageManagerView: View { .keyboardShortcut(.defaultAction) } } - .padding(22) - .frame(width: 480, height: 500) + .padding(24) + .frame(width: 540, height: 660) .appSheet() .onAppear(perform: viewModel.refreshUsage) .alert("クリーンアップ完了", isPresented: $viewModel.isShowingResultAlert) { @@ -175,17 +157,19 @@ struct StorageManagerView: View { } private func breakdownRow(color: Color, label: String, size: Int64) -> some View { - HStack(spacing: 8) { - Circle() - .fill(color) - .frame(width: 8, height: 8) - Text(label) - .font(.appBody) - Spacer() - Text(viewModel.formatBytes(size)) - .font(.system(size: 13, weight: .semibold)) - .monospacedDigit() - } + SettingsRow( + title: label, + leading: { + Circle() + .fill(color) + .frame(width: 8, height: 8) + }, + control: { + Text(viewModel.formatBytes(size)) + .font(.appBodyStrong) + .monospacedDigit() + } + ) } } From e30710ee25ac0d8f992d3794e9505ff34f45277d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8E=9F=E3=80=80=E9=A2=AF=E7=99=BB?= Date: Wed, 4 Nov 2026 13:22:55 +0900 Subject: [PATCH 5/9] =?UTF-8?q?feat(musicvideo):=20=E6=9B=B2=E9=81=B8?= =?UTF-8?q?=E6=8A=9E=E6=99=82=E3=81=AE=E8=A9=A6=E8=81=B4=E5=8C=BA=E9=96=93?= =?UTF-8?q?=E8=A8=88=E7=AE=97=E3=83=BB=E8=A9=A6=E8=81=B4=E3=83=97=E3=83=AC?= =?UTF-8?q?=E3=82=A4=E3=83=A4=E3=83=BC=E3=83=BB=E8=A9=A6=E8=81=B4=E3=83=9C?= =?UTF-8?q?=E3=82=BF=E3=83=B3=E3=82=92=E8=BF=BD=E5=8A=A0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../MusicVideo/Models/MusicPreviewPlan.swift | 54 +++++ .../Services/MusicPreviewPlayer.swift | 140 +++++++++++ .../MusicVideo/Views/MusicPreviewButton.swift | 41 ++++ ArkServerTests/MusicPreviewTests.swift | 229 ++++++++++++++++++ 4 files changed, 464 insertions(+) create mode 100644 ArkServer/Features/MusicVideo/Models/MusicPreviewPlan.swift create mode 100644 ArkServer/Features/MusicVideo/Services/MusicPreviewPlayer.swift create mode 100644 ArkServer/Features/MusicVideo/Views/MusicPreviewButton.swift create mode 100644 ArkServerTests/MusicPreviewTests.swift diff --git a/ArkServer/Features/MusicVideo/Models/MusicPreviewPlan.swift b/ArkServer/Features/MusicVideo/Models/MusicPreviewPlan.swift new file mode 100644 index 0000000..8e3f4c6 --- /dev/null +++ b/ArkServer/Features/MusicVideo/Models/MusicPreviewPlan.swift @@ -0,0 +1,54 @@ +// ArkServer/Features/MusicVideo/Models/MusicPreviewPlan.swift + +import Foundation + +/// 曲を選ぶときの試聴で、どこを何秒聞くかを決める純粋ロジック。 +nonisolated enum MusicPreviewPlan { + /// 試聴の長さ(秒)。 + static let defaultLength = 15.0 + + struct Excerpt: Equatable, Sendable { + /// 曲の中の開始位置(秒)。 + var start: Double + /// 聞く長さ(秒)。 + var length: Double + } + + /// 曲をまだ解析していないとき。曲の3分の1あたりから聞く(冒頭の静かな導入部を避けるため)。 + /// 曲が短ければ頭から、曲の終わりを越えないように調整する。 + static func excerpt(forDuration duration: Double, length: Double = defaultLength) -> Excerpt { + guard duration > 0, length > 0 else { return Excerpt(start: 0, length: 0) } + let playable = min(length, duration) + let start = min(duration / 3, duration - playable) + return Excerpt(start: max(0, start), length: playable) + } + + /// 曲を解析済みのとき。盛り上がりの平均が最も大きい区間を聞く(映像のカットが速くなる所を確かめられる)。 + /// - Parameters: + /// - energy: 盛り上がりの連続値。`energyHop` 秒ごと。 + static func excerpt( + forDuration duration: Double, + energy: [Double], + energyHop: Double, + length: Double = defaultLength + ) -> Excerpt { + let fallback = excerpt(forDuration: duration, length: length) + guard fallback.length > 0, energyHop > 0, energy.count > 1 else { return fallback } + + let window = max(1, min(energy.count, Int((fallback.length / energyHop).rounded()))) + var prefix = [Double](repeating: 0, count: energy.count + 1) + for (index, value) in energy.enumerated() { prefix[index + 1] = prefix[index] + value } + + var bestStart = 0 + var bestSum = -Double.infinity + for start in 0...(energy.count - window) { + let sum = prefix[start + window] - prefix[start] + if sum > bestSum + 1e-9 { + bestSum = sum + bestStart = start + } + } + let start = min(Double(bestStart) * energyHop, duration - fallback.length) + return Excerpt(start: max(0, start), length: fallback.length) + } +} diff --git a/ArkServer/Features/MusicVideo/Services/MusicPreviewPlayer.swift b/ArkServer/Features/MusicVideo/Services/MusicPreviewPlayer.swift new file mode 100644 index 0000000..3761ec2 --- /dev/null +++ b/ArkServer/Features/MusicVideo/Services/MusicPreviewPlayer.swift @@ -0,0 +1,140 @@ +// ArkServer/Features/MusicVideo/Services/MusicPreviewPlayer.swift + +import AVFoundation +import Combine +import Foundation + +/// 試聴に使う音声。本物は AVAudioPlayer で、テストでは差し替える。 +@MainActor +protocol PreviewAudio: AnyObject { + var duration: TimeInterval { get } + var currentTime: TimeInterval { get set } + var isPlaying: Bool { get } + func play() -> Bool + func stop() + func fadeOut(over seconds: TimeInterval) +} + +@MainActor +final class SystemPreviewAudio: PreviewAudio { + private let player: AVAudioPlayer + + init(url: URL) throws { + player = try AVAudioPlayer(contentsOf: url) + player.prepareToPlay() + } + + var duration: TimeInterval { player.duration } + var currentTime: TimeInterval { + get { player.currentTime } + set { player.currentTime = newValue } + } + var isPlaying: Bool { player.isPlaying } + func play() -> Bool { player.play() } + func stop() { player.stop() } + func fadeOut(over seconds: TimeInterval) { player.setVolume(0, fadeDuration: seconds) } +} + +/// 曲を選ぶときの試聴。1度に1曲だけ、短い区間を流して自動で止まる。 +@MainActor +final class MusicPreviewPlayer: ObservableObject { + /// いま試聴している曲。 + @Published private(set) var playingURL: URL? + /// 試聴区間の中での進み具合(0〜1)。 + @Published private(set) var progress: Double = 0 + /// 再生できなかった曲(その曲のボタンに注意を出す)。 + @Published private(set) var failedURL: URL? + @Published private(set) var failureMessage: String? + + private let makeAudio: (URL) throws -> PreviewAudio + private var audio: PreviewAudio? + private var timer: Timer? + private var excerpt = MusicPreviewPlan.Excerpt(start: 0, length: 0) + private var isFadingOut = false + + /// 終わりぎわに音量を下げる時間(秒)。 + static let fadeSeconds = 1.0 + + /// - Parameter makeAudio: 音声の作り方。省略すると AVAudioPlayer を使う(テストでは差し替える)。 + init(makeAudio: ((URL) throws -> PreviewAudio)? = nil) { + self.makeAudio = makeAudio ?? { try SystemPreviewAudio(url: $0) } + } + + deinit { + timer?.invalidate() + } + + func isPlaying(_ url: URL) -> Bool { playingURL == url } + + /// 同じ曲なら止め、別の曲なら切り替えて流す。 + /// - Parameter analysis: 解析済みならその盛り上がりから、聞く区間を決める。 + func toggle(_ url: URL, analysis: MusicAnalysis? = nil) { + if playingURL == url { + stop() + } else { + play(url, analysis: analysis) + } + } + + func play(_ url: URL, analysis: MusicAnalysis? = nil) { + stop() + failedURL = nil + failureMessage = nil + do { + let audio = try makeAudio(url) + guard audio.duration > 0 else { throw PreviewError.empty } + + let excerpt: MusicPreviewPlan.Excerpt + if let analysis, !analysis.energy.isEmpty { + excerpt = MusicPreviewPlan.excerpt(forDuration: audio.duration, energy: analysis.energy, energyHop: analysis.energyHop) + } else { + excerpt = MusicPreviewPlan.excerpt(forDuration: audio.duration) + } + audio.currentTime = excerpt.start + guard audio.play() else { throw PreviewError.cannotStart } + + self.audio = audio + self.excerpt = excerpt + playingURL = url + progress = 0 + isFadingOut = false + timer = Timer.scheduledTimer(withTimeInterval: 0.1, repeats: true) { [weak self] _ in + MainActor.assumeIsolated { self?.tick() } + } + } catch { + failedURL = url + failureMessage = "試聴できませんでした.ファイルを読み込めない可能性があります." + } + } + + func stop() { + timer?.invalidate() + timer = nil + audio?.stop() + audio = nil + playingURL = nil + progress = 0 + isFadingOut = false + } + + /// 0.1秒ごとの更新。進み具合を出し、区間の終わりで止める。テストからも呼べる。 + func tick() { + guard let audio, playingURL != nil else { return } + let elapsed = audio.currentTime - excerpt.start + progress = min(1, max(0, elapsed / max(excerpt.length, 0.001))) + if !audio.isPlaying || elapsed >= excerpt.length { + stop() + return + } + let remaining = excerpt.length - elapsed + if !isFadingOut, remaining <= Self.fadeSeconds { + isFadingOut = true + audio.fadeOut(over: max(0.1, remaining)) + } + } + + private enum PreviewError: Error { + case empty + case cannotStart + } +} diff --git a/ArkServer/Features/MusicVideo/Views/MusicPreviewButton.swift b/ArkServer/Features/MusicVideo/Views/MusicPreviewButton.swift new file mode 100644 index 0000000..8bc17bc --- /dev/null +++ b/ArkServer/Features/MusicVideo/Views/MusicPreviewButton.swift @@ -0,0 +1,41 @@ +// ArkServer/Features/MusicVideo/Views/MusicPreviewButton.swift + +import SwiftUI + +/// 曲の横に置く、試聴の再生/停止ボタン。再生中は、まわりに進み具合を出す。 +struct MusicPreviewButton: View { + @ObservedObject var preview: MusicPreviewPlayer + let url: URL + let action: () -> Void + + var body: some View { + let isPlaying = preview.isPlaying(url) + let failed = preview.failedURL == url + + Button(action: action) { + ZStack { + Circle().fill(NeomorphicTheme.control) + if isPlaying { + Circle() + .trim(from: 0, to: preview.progress) + .stroke(NeomorphicTheme.accent, style: StrokeStyle(lineWidth: 2, lineCap: .round)) + .rotationEffect(.degrees(-90)) + } + Image(systemName: failed ? "exclamationmark.triangle.fill" : (isPlaying ? "stop.fill" : "play.fill")) + .font(.system(size: 10)) + .foregroundStyle(failed ? NeomorphicTheme.caution : NeomorphicTheme.ink) + } + .frame(width: 26, height: 26) + .contentShape(Circle()) + } + .buttonStyle(.plain) + .help(helpText(isPlaying: isPlaying, failed: failed)) + .accessibilityLabel(isPlaying ? "試聴を止める" : "試聴する") + .accessibilityIdentifier("musicvideo.preview") + } + + private func helpText(isPlaying: Bool, failed: Bool) -> String { + if failed, let message = preview.failureMessage { return message } + return isPlaying ? "試聴を止める" : "15秒ほど試聴する" + } +} diff --git a/ArkServerTests/MusicPreviewTests.swift b/ArkServerTests/MusicPreviewTests.swift new file mode 100644 index 0000000..eb851df --- /dev/null +++ b/ArkServerTests/MusicPreviewTests.swift @@ -0,0 +1,229 @@ +// ArkServerTests/MusicPreviewTests.swift + +import Foundation +import Testing +@testable import ArkServer + +// MARK: - 聞く区間の決め方 + +@Suite(.serialized) +struct MusicPreviewPlanTests { + @Test + func startsAboutAThirdIntoTheSongAndKeepsToTheLength() { + let excerpt = MusicPreviewPlan.excerpt(forDuration: 200) + + #expect(abs(excerpt.start - 200.0 / 3) < 1e-9) + #expect(excerpt.length == MusicPreviewPlan.defaultLength) + } + + @Test + func neverRunsPastTheEndOfAShortSong() { + // 15秒より短い曲は、頭から最後まで。 + #expect(MusicPreviewPlan.excerpt(forDuration: 10) == .init(start: 0, length: 10)) + // 少し長いだけの曲は、終わりを越えないよう開始を前へ寄せる。 + #expect(MusicPreviewPlan.excerpt(forDuration: 20) == .init(start: 5, length: 15)) + for duration in stride(from: 1.0, through: 600.0, by: 7.3) { + let excerpt = MusicPreviewPlan.excerpt(forDuration: duration) + #expect(excerpt.start >= 0) + #expect(excerpt.start + excerpt.length <= duration + 1e-9) + } + } + + @Test + func degenerateInputsGiveAnEmptyExcerpt() { + #expect(MusicPreviewPlan.excerpt(forDuration: 0).length == 0) + #expect(MusicPreviewPlan.excerpt(forDuration: -5).length == 0) + #expect(MusicPreviewPlan.excerpt(forDuration: 100, length: 0).length == 0) + } + + @Test + func picksTheLoudestStretchWhenTheSongHasBeenAnalysed() { + // 1秒ごとの盛り上がり。100〜130秒だけ大きい。 + var energy = [Double](repeating: 0.1, count: 240) + for second in 100..<130 { energy[second] = 0.9 } + + let excerpt = MusicPreviewPlan.excerpt(forDuration: 240, energy: energy, energyHop: 1) + + #expect(excerpt.length == MusicPreviewPlan.defaultLength) + #expect(excerpt.start >= 100 && excerpt.start + excerpt.length <= 130 + 1e-9) + } + + @Test + func theLoudestStretchNearTheEndStillStaysInsideTheSong() { + var energy = [Double](repeating: 0.1, count: 100) + for second in 95..<100 { energy[second] = 1.0 } + + let excerpt = MusicPreviewPlan.excerpt(forDuration: 100, energy: energy, energyHop: 1) + + #expect(excerpt.start + excerpt.length <= 100 + 1e-9) + #expect(excerpt.start >= 85 - 1e-9) + } + + @Test + func fallsBackToTheSimpleRuleWithoutUsableEnergy() { + let simple = MusicPreviewPlan.excerpt(forDuration: 180) + + #expect(MusicPreviewPlan.excerpt(forDuration: 180, energy: [], energyHop: 0.1) == simple) + #expect(MusicPreviewPlan.excerpt(forDuration: 180, energy: [0.5], energyHop: 0.1) == simple) + #expect(MusicPreviewPlan.excerpt(forDuration: 180, energy: [0.2, 0.9, 0.4], energyHop: 0) == simple) + } +} + +// MARK: - 試聴の再生状態 + +@MainActor +private final class FakePreviewAudio: PreviewAudio { + var duration: TimeInterval + var currentTime: TimeInterval = 0 + var isPlaying = false + var canPlay = true + var fadeOutDuration: TimeInterval? + var fadeOutCount = 0 + var stopCount = 0 + + init(duration: TimeInterval) { self.duration = duration } + + func play() -> Bool { + guard canPlay else { return false } + isPlaying = true + return true + } + func stop() { isPlaying = false; stopCount += 1 } + func fadeOut(over seconds: TimeInterval) { fadeOutDuration = seconds; fadeOutCount += 1 } +} + +private enum FakeAudioError: Error { case unreadable } + +@Suite(.serialized) +struct MusicPreviewPlayerTests { + private let songA = URL(fileURLWithPath: "/music/a.mp3") + private let songB = URL(fileURLWithPath: "/music/b.mp3") + + @MainActor + private func makePlayer(_ audios: [URL: FakePreviewAudio]) -> MusicPreviewPlayer { + MusicPreviewPlayer { url in + guard let audio = audios[url] else { throw FakeAudioError.unreadable } + return audio + } + } + + @Test @MainActor + func startsAtTheExcerptAndShowsProgressUntilItStopsByItself() { + let audio = FakePreviewAudio(duration: 180) + let player = makePlayer([songA: audio]) + + player.play(songA) + + #expect(player.playingURL == songA) + #expect(abs(audio.currentTime - 60) < 1e-9) // 180秒の曲の3分の1 = 60秒から + #expect(audio.isPlaying) + + audio.currentTime = 60 + 7.5 + player.tick() + #expect(abs(player.progress - 0.5) < 1e-9) + #expect(player.playingURL == songA) + + audio.currentTime = 60 + 15 + player.tick() + #expect(player.playingURL == nil) + #expect(player.progress == 0) + #expect(!audio.isPlaying) + } + + @Test @MainActor + func fadesOutOnceInTheLastSecond() { + let audio = FakePreviewAudio(duration: 180) + let player = makePlayer([songA: audio]) + player.play(songA) + + audio.currentTime = 60 + 10 + player.tick() + #expect(audio.fadeOutCount == 0) + + audio.currentTime = 60 + 14.2 + player.tick() + player.tick() + #expect(audio.fadeOutCount == 1) + #expect(abs((audio.fadeOutDuration ?? 0) - 0.8) < 1e-6) + } + + @Test @MainActor + func togglingTheSameSongStopsItAndAnotherSongSwitchesOver() { + let audioA = FakePreviewAudio(duration: 120) + let audioB = FakePreviewAudio(duration: 120) + let player = makePlayer([songA: audioA, songB: audioB]) + + player.toggle(songA) + #expect(player.isPlaying(songA)) + + player.toggle(songB) + #expect(player.isPlaying(songB)) + #expect(!player.isPlaying(songA)) + #expect(audioA.stopCount >= 1 && !audioA.isPlaying) + #expect(audioB.isPlaying) + + player.toggle(songB) + #expect(player.playingURL == nil) + #expect(!audioB.isPlaying) + } + + @Test @MainActor + func usesTheAnalysedLoudestStretchWhenGiven() { + let audio = FakePreviewAudio(duration: 240) + let player = makePlayer([songA: audio]) + var energy = [Double](repeating: 0.1, count: 240) + for second in 150..<180 { energy[second] = 0.9 } + let analysis = MusicAnalysis( + duration: 240, tempo: 120, beats: [], energy: energy, + intensity: [MusicIntensity](repeating: .medium, count: 240), energyHop: 1 + ) + + player.play(songA, analysis: analysis) + + #expect(audio.currentTime >= 150 && audio.currentTime + 15 <= 180 + 1e-9) + } + + @Test @MainActor + func stopsWhenTheAudioEndsOnItsOwn() { + let audio = FakePreviewAudio(duration: 8) + let player = makePlayer([songA: audio]) + player.play(songA) + + audio.isPlaying = false // 曲の終わりで再生が終わった + player.tick() + + #expect(player.playingURL == nil) + } + + @Test @MainActor + func reportsAFailureOnTheSongThatCouldNotBePlayedAndRecoversNextTime() { + let silent = FakePreviewAudio(duration: 0) + let blocked = FakePreviewAudio(duration: 60) + blocked.canPlay = false + let good = FakePreviewAudio(duration: 60) + let player = makePlayer([songA: silent, songB: blocked, URL(fileURLWithPath: "/music/c.mp3"): good]) + + player.play(songA) + #expect(player.playingURL == nil && player.failedURL == songA && player.failureMessage != nil) + + player.play(songB) + #expect(player.playingURL == nil && player.failedURL == songB) + + // 読めない曲(未登録) + player.play(URL(fileURLWithPath: "/music/missing.mp3")) + #expect(player.failedURL?.lastPathComponent == "missing.mp3") + + // 次に成功したら、失敗の表示は消える。 + player.play(URL(fileURLWithPath: "/music/c.mp3")) + #expect(player.playingURL?.lastPathComponent == "c.mp3") + #expect(player.failedURL == nil && player.failureMessage == nil) + } + + @Test @MainActor + func stopIsSafeWhenNothingIsPlaying() { + let player = makePlayer([:]) + player.stop() + player.tick() + #expect(player.playingURL == nil && player.progress == 0) + } +} From f8df0e9a68b650d1f30d45c3272c3777934d5637 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8E=9F=E3=80=80=E9=A2=AF=E7=99=BB?= Date: Wed, 4 Nov 2026 13:23:06 +0900 Subject: [PATCH 6/9] =?UTF-8?q?feat(musicvideo):=20=E6=9B=B8=E3=81=8D?= =?UTF-8?q?=E5=87=BA=E3=81=97=E5=85=88=E3=82=A2=E3=83=AB=E3=83=90=E3=83=A0?= =?UTF-8?q?=E3=81=AE=E9=81=B8=E6=8A=9E=E3=83=BB=E6=96=B0=E8=A6=8F=E4=BD=9C?= =?UTF-8?q?=E6=88=90=E3=82=B7=E3=83=BC=E3=83=88=E3=81=A8=E3=82=A2=E3=83=AB?= =?UTF-8?q?=E3=83=90=E3=83=A0=E5=90=8D=E6=A4=9C=E8=A8=BC=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 --- .../Models/MusicVideoExportDestination.swift | 107 ++++++++ .../Views/MusicVideoExportAlbumSheet.swift | 235 ++++++++++++++++++ .../MusicVideoExportDestinationTests.swift | 154 ++++++++++++ 3 files changed, 496 insertions(+) create mode 100644 ArkServer/Features/MusicVideo/Models/MusicVideoExportDestination.swift create mode 100644 ArkServer/Features/MusicVideo/Views/MusicVideoExportAlbumSheet.swift create mode 100644 ArkServerTests/MusicVideoExportDestinationTests.swift diff --git a/ArkServer/Features/MusicVideo/Models/MusicVideoExportDestination.swift b/ArkServer/Features/MusicVideo/Models/MusicVideoExportDestination.swift new file mode 100644 index 0000000..a8254ab --- /dev/null +++ b/ArkServer/Features/MusicVideo/Models/MusicVideoExportDestination.swift @@ -0,0 +1,107 @@ +// ArkServer/Features/MusicVideo/Models/MusicVideoExportDestination.swift + +import Foundation + +/// 「ライブラリに追加」で書き出した動画の追加先。追加のたびに利用者が選ぶ(アプリが勝手に決めない)。 +nonisolated enum MusicVideoExportDestination: Equatable, Sendable { + /// すでにあるアルバムへ追加する。 + case existing(albumID: UUID) + /// 利用者が名前を付けた新しいアルバムを作って追加する。書き出しが成功した後で作る。 + case new(name: String) +} + +/// 新しいアルバム名の検査。アルバムは "/" 区切りの名前でフォルダ階層を表すので,その決まりも確かめる. +nonisolated enum MusicVideoExportAlbumName { + enum Problem: Error, Equatable, Sendable { + case empty + case reserved + case emptyComponent + case alreadyExists + + var message: String { + switch self { + case .empty: return "アルバム名を入力してください." + case .reserved: return "この名前はアプリが使うため,アルバム名にできません." + case .emptyComponent: return "「/」の前後には名前が必要です." + case .alreadyExists: return "同じ名前のアルバムがすでにあります." + } + } + } + + /// 前後の空白を除いた名前を返す。使えないときは理由を返す。 + static func validate(_ rawName: String, existingNames: [String]) -> Result { + let name = rawName.trimmingCharacters(in: .whitespacesAndNewlines) + if name.isEmpty { return .failure(.empty) } + if reservedNames.contains(name) { return .failure(.reserved) } + let components = name.components(separatedBy: "/") + if components.contains(where: { $0.trimmingCharacters(in: .whitespaces).isEmpty }) { + return .failure(.emptyComponent) + } + if existingNames.contains(where: { $0.caseInsensitiveCompare(name) == .orderedSame }) { + return .failure(.alreadyExists) + } + return .success(name) + } + + /// ライブラリが内部で使う名前。追加先や新規作成の名前にはできない。 + static let reservedNames: Set = [ + LibraryViewModel.allVideosAlbumName, + LibraryViewModel.allPhotosAlbumName, + ] +} + +/// アルバム一覧の1行ぶん。素材を選ぶシートと追加先を選ぶシートで共通に使う。 +nonisolated struct MusicVideoAlbumEntry: Identifiable, Equatable, Sendable { + let id: UUID + /// アルバムの完全な名前("/" 区切り)。 + let name: String + /// 表示用の名前(階層の最後の部分)。 + let title: String + /// 親の階層(" / " 区切り)。階層がなければ空。 + let parent: String + /// ゴミ箱以外の動画の本数。 + let count: Int + let totalDuration: Double + let latestImport: Date + + /// 写真だけのアルバムを除いた一覧を作る。表示名(`Album.displayTitle`)がメインアクター上なので,こちらもそうする。 + @MainActor + static func entries(albums: [Album], videos: [VideoItem]) -> [MusicVideoAlbumEntry] { + let byID = Dictionary(videos.map { ($0.id, $0) }, uniquingKeysWith: { first, _ in first }) + return albums + .filter { $0.type != .photo } + .map { album in + var count = 0 + var total = 0.0 + var latest = Date.distantPast + for id in album.videoIDs { + guard let item = byID[id], item.mediaType == .video, !item.isInTrash else { continue } + count += 1 + total += item.duration + latest = max(latest, item.importDate) + } + let components = album.name.components(separatedBy: "/") + return MusicVideoAlbumEntry( + id: album.id, + name: album.name, + title: album.displayTitle, + parent: components.count > 1 ? components.dropLast().joined(separator: " / ") : "", + count: count, + totalDuration: total, + latestImport: latest + ) + } + } + + /// 検索語に合うか。名前と階層のどちらかに含まれていればよい。空の検索語はすべて合う。 + func matches(query: String) -> Bool { + let trimmed = query.trimmingCharacters(in: .whitespacesAndNewlines) + if trimmed.isEmpty { return true } + return title.localizedCaseInsensitiveContains(trimmed) || parent.localizedCaseInsensitiveContains(trimmed) + } + + /// 追加先に選べるアルバム。ライブラリが内部で使う「すべて」系のアルバムは除く。 + var isSelectableDestination: Bool { + !MusicVideoExportAlbumName.reservedNames.contains(name) + } +} diff --git a/ArkServer/Features/MusicVideo/Views/MusicVideoExportAlbumSheet.swift b/ArkServer/Features/MusicVideo/Views/MusicVideoExportAlbumSheet.swift new file mode 100644 index 0000000..a5e8e05 --- /dev/null +++ b/ArkServer/Features/MusicVideo/Views/MusicVideoExportAlbumSheet.swift @@ -0,0 +1,235 @@ +// ArkServer/Features/MusicVideo/Views/MusicVideoExportAlbumSheet.swift + +import SwiftUI + +/// 書き出した動画を入れるアルバムを選ぶシート。追加のたびに利用者が選ぶ(アプリは追加先を決めない)。 +/// 既存のアルバムから探すか,名前を付けて新しいアルバムを作る。 +struct MusicVideoExportAlbumSheet: View { + @ObservedObject var dataManager: LibraryViewModel + /// 追加するファイルの名前。何を追加するのかをヘッダーで示す。 + let fileName: String + let onConfirm: (MusicVideoExportDestination) -> Void + @Environment(\.dismiss) private var dismiss + + private enum Choice: Hashable { + case existing(UUID) + case newAlbum + } + + private enum Order: String, CaseIterable, Identifiable { + case name = "名前" + case recent = "最近追加した順" + var id: String { rawValue } + } + + @State private var choice: Choice? + @State private var newName = "" + @State private var searchText = "" + @AppStorage("musicVideo.exportPicker.order") private var order: Order = .name + @State private var entries: [MusicVideoAlbumEntry] = [] + @FocusState private var isNameFocused: Bool + + var body: some View { + VStack(spacing: 0) { + SheetHeader( + icon: "rectangle.stack.badge.plus", + title: "追加先のアルバムを選ぶ", + subtitle: "\(fileName) を入れるアルバムを選んでください" + ) + .padding(20) + + HStack(spacing: 12) { + TextField("アルバム名で検索", text: $searchText) + .textFieldStyle(.roundedBorder) + Picker("並べ替え", selection: $order) { + ForEach(Order.allCases) { Text($0.rawValue).tag($0) } + } + .frame(width: 210) + } + .padding(.horizontal, 20) + .padding(.bottom, 12) + + Divider() + + List { + newAlbumRow + ForEach(visibleEntries) { entry in + albumRow(entry) + } + } + .listStyle(.plain) + + Divider() + footer + .padding(16) + } + .frame(minWidth: 560, idealWidth: 600, minHeight: 520, idealHeight: 580) + .appSheet() + .onAppear(perform: rebuild) + .onChange(of: dataManager.albums) { rebuild() } + .onChange(of: dataManager.videos) { rebuild() } + } + + // MARK: - 一覧 + + private var visibleEntries: [MusicVideoAlbumEntry] { + var rows = entries.filter { $0.isSelectableDestination && $0.matches(query: searchText) } + switch order { + case .name: + rows.sort { ($0.parent + "/" + $0.title).localizedStandardCompare($1.parent + "/" + $1.title) == .orderedAscending } + case .recent: + rows.sort { $0.latestImport > $1.latestImport } + } + return rows + } + + private var newAlbumRow: some View { + VStack(alignment: .leading, spacing: 8) { + Button { + choice = .newAlbum + isNameFocused = true + } label: { + HStack(spacing: 10) { + radio(choice == .newAlbum) + Text("新しいアルバムを作る") + .font(.appBody) + Spacer(minLength: 8) + Image(systemName: "plus") + .font(.appCaption) + .foregroundStyle(NeomorphicTheme.muted) + } + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + .accessibilityIdentifier("musicvideo.exportAlbum.new") + .accessibilityAddTraits(choice == .newAlbum ? .isSelected : []) + + if choice == .newAlbum { + VStack(alignment: .leading, spacing: 4) { + TextField("アルバム名(「/」で階層を作れます)", text: $newName) + .textFieldStyle(.roundedBorder) + .focused($isNameFocused) + .onSubmit(confirm) + .accessibilityIdentifier("musicvideo.exportAlbum.newName") + if let message = newNameMessage { + Text(message) + .font(.appMicro) + .foregroundStyle(.red) + } + } + .padding(.leading, 28) + } + } + .padding(.vertical, 4) + } + + private func albumRow(_ entry: MusicVideoAlbumEntry) -> some View { + let isSelected = choice == .existing(entry.id) + return Button { + choice = .existing(entry.id) + } label: { + HStack(spacing: 10) { + radio(isSelected) + VStack(alignment: .leading, spacing: 2) { + Text(entry.title) + .font(.appBody) + .lineLimit(1) + .truncationMode(.middle) + if !entry.parent.isEmpty { + Text(entry.parent) + .font(.appMicro) + .foregroundStyle(NeomorphicTheme.muted) + .lineLimit(1) + .truncationMode(.head) + } + } + Spacer(minLength: 8) + Text("\(entry.count)本") + .font(.appCaption.monospacedDigit()) + .foregroundStyle(NeomorphicTheme.muted) + } + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + .accessibilityLabel("\(entry.title) \(entry.count)本") + .accessibilityAddTraits(isSelected ? .isSelected : []) + } + + /// 選択の印。素材を選ぶシートと同じく,色を付けず,選択中は文字色・未選択は控えめな色にする。 + private func radio(_ isSelected: Bool) -> some View { + Image(systemName: isSelected ? "checkmark.circle.fill" : "circle") + .font(.system(size: 15)) + .foregroundStyle(isSelected ? NeomorphicTheme.ink : NeomorphicTheme.muted) + .frame(width: 18) + } + + // MARK: - 下の帯 + + private var footer: some View { + HStack(spacing: 12) { + Text(summary) + .font(.appCaption) + .foregroundStyle(NeomorphicTheme.muted) + .lineLimit(1) + .truncationMode(.middle) + .frame(maxWidth: .infinity, alignment: .leading) + Button("キャンセル") { dismiss() } + .keyboardShortcut(.cancelAction) + .accessibilityIdentifier("musicvideo.exportAlbum.cancel") + Button("書き出して追加") { confirm() } + .buttonStyle(.borderedProminent) + .keyboardShortcut(.defaultAction) + .disabled(destination == nil) + .accessibilityIdentifier("musicvideo.exportAlbum.confirm") + } + } + + private var summary: String { + switch choice { + case .none: + return "アルバムを選んでください" + case .newAlbum: + if case .success(let name) = nameResult { return "新しいアルバム「\(name)」を作って追加します" } + return "新しいアルバムの名前を入力してください" + case .existing(let id): + guard let entry = entries.first(where: { $0.id == id }) else { return "アルバムを選んでください" } + return "「\(entry.title)」に追加します" + } + } + + // MARK: - 選択と確定 + + private var nameResult: Result { + MusicVideoExportAlbumName.validate(newName, existingNames: dataManager.albums.map(\.name)) + } + + /// 入力があるのに使えないときだけ理由を出す(何も入力していない間は黙っている)。 + private var newNameMessage: String? { + guard !newName.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { return nil } + if case .failure(let problem) = nameResult { return problem.message } + return nil + } + + /// いま確定できる追加先。選んでいない・名前が使えない・選んだアルバムが消えたときは nil。 + private var destination: MusicVideoExportDestination? { + switch choice { + case .none: + return nil + case .newAlbum: + if case .success(let name) = nameResult { return .new(name: name) } + return nil + case .existing(let id): + return entries.contains(where: { $0.id == id }) ? .existing(albumID: id) : nil + } + } + + private func confirm() { + guard let destination else { return } + dismiss() + onConfirm(destination) + } + + private func rebuild() { + entries = MusicVideoAlbumEntry.entries(albums: dataManager.albums, videos: dataManager.videos) + } +} diff --git a/ArkServerTests/MusicVideoExportDestinationTests.swift b/ArkServerTests/MusicVideoExportDestinationTests.swift new file mode 100644 index 0000000..2c351c4 --- /dev/null +++ b/ArkServerTests/MusicVideoExportDestinationTests.swift @@ -0,0 +1,154 @@ +// ArkServerTests/MusicVideoExportDestinationTests.swift + +import Foundation +import Testing +@testable import ArkServer + +// MARK: - 新しいアルバム名の検査 + +@Suite +struct MusicVideoExportAlbumNameTests { + @Test + func acceptsAndTrimsAnOrdinaryName() { + #expect(MusicVideoExportAlbumName.validate(" 旅行の曲 ", existingNames: []) == .success("旅行の曲")) + } + + @Test + func acceptsHierarchyWithSlash() { + #expect(MusicVideoExportAlbumName.validate("作品/2026", existingNames: ["作品"]) == .success("作品/2026")) + } + + @Test + func rejectsEmptyOrBlankNames() { + #expect(MusicVideoExportAlbumName.validate("", existingNames: []) == .failure(.empty)) + #expect(MusicVideoExportAlbumName.validate(" \n ", existingNames: []) == .failure(.empty)) + } + + @Test + func rejectsNamesTheLibraryUsesInternally() { + #expect(MusicVideoExportAlbumName.validate("ALL VIDEOS", existingNames: []) == .failure(.reserved)) + #expect(MusicVideoExportAlbumName.validate(" ALL PHOTOS ", existingNames: []) == .failure(.reserved)) + } + + @Test + func rejectsEmptyHierarchyComponents() { + #expect(MusicVideoExportAlbumName.validate("/a", existingNames: []) == .failure(.emptyComponent)) + #expect(MusicVideoExportAlbumName.validate("a/", existingNames: []) == .failure(.emptyComponent)) + #expect(MusicVideoExportAlbumName.validate("a//b", existingNames: []) == .failure(.emptyComponent)) + #expect(MusicVideoExportAlbumName.validate("a/ /b", existingNames: []) == .failure(.emptyComponent)) + } + + @Test + func rejectsNamesAlreadyInTheLibraryIgnoringCase() { + #expect(MusicVideoExportAlbumName.validate("Trip", existingNames: ["Trip"]) == .failure(.alreadyExists)) + #expect(MusicVideoExportAlbumName.validate("trip", existingNames: ["Trip"]) == .failure(.alreadyExists)) + #expect(MusicVideoExportAlbumName.validate(" Trip ", existingNames: ["Trip"]) == .failure(.alreadyExists)) + } + + @Test + func everyProblemHasAMessage() { + let problems: [MusicVideoExportAlbumName.Problem] = [.empty, .reserved, .emptyComponent, .alreadyExists] + for problem in problems { + #expect(!problem.message.isEmpty) + } + } +} + +// MARK: - アルバム一覧の組み立て + +@Suite +@MainActor +struct MusicVideoAlbumEntryTests { + private func video( + _ id: UUID = UUID(), + duration: Double = 10, + importedAt: Date, + mediaType: MediaType = .video, + isInTrash: Bool = false + ) -> VideoItem { + VideoItem( + id: id, + originalFilename: "\(id.uuidString).mp4", + internalFilename: "\(id.uuidString).mp4", + duration: duration, + importDate: importedAt, + creationDate: nil, + fileHash: id.uuidString, + mediaType: mediaType, + isInTrash: isInTrash + ) + } + + @Test + func countsOnlyVideosOutsideTheTrashAndLeavesPhotoAlbumsOut() { + let early = Date(timeIntervalSince1970: 1_000) + let late = Date(timeIntervalSince1970: 2_000) + let a = video(duration: 30, importedAt: early) + let b = video(duration: 20, importedAt: late) + let trashed = video(duration: 99, importedAt: late, isInTrash: true) + let photo = video(duration: 0, importedAt: late, mediaType: .photo) + + let albums = [ + Album(id: UUID(), name: "旅行", videoIDs: [a.id, b.id, trashed.id, photo.id], type: .video), + Album(id: UUID(), name: "写真だけ", videoIDs: [photo.id], type: .photo), + ] + let entries = MusicVideoAlbumEntry.entries(albums: albums, videos: [a, b, trashed, photo]) + + #expect(entries.count == 1) + #expect(entries[0].title == "旅行") + #expect(entries[0].count == 2) + #expect(entries[0].totalDuration == 50) + #expect(entries[0].latestImport == late) + } + + @Test + func keepsEmptyAlbumsSoTheyCanBeChosenAsDestinations() { + let entries = MusicVideoAlbumEntry.entries( + albums: [Album(id: UUID(), name: "空", videoIDs: [], type: .video)], + videos: [] + ) + + #expect(entries.map(\.count) == [0]) + #expect(entries[0].latestImport == .distantPast) + #expect(entries[0].isSelectableDestination) + } + + @Test + func splitsHierarchyIntoTitleAndParent() { + let entries = MusicVideoAlbumEntry.entries( + albums: [Album(id: UUID(), name: "作品/2026/春", videoIDs: [], type: .mixed)], + videos: [] + ) + + #expect(entries[0].name == "作品/2026/春") + #expect(entries[0].title == "春") + #expect(entries[0].parent == "作品 / 2026") + } + + @Test + func systemAlbumsAreNotSelectableAsDestinations() { + let entries = MusicVideoAlbumEntry.entries( + albums: [ + Album(id: UUID(), name: LibraryViewModel.allVideosAlbumName, videoIDs: [], type: .video), + Album(id: UUID(), name: "自作", videoIDs: [], type: .video), + ], + videos: [] + ) + + #expect(entries.filter(\.isSelectableDestination).map(\.name) == ["自作"]) + } + + @Test + func searchMatchesTitleOrParentAndIgnoresCase() { + let entry = MusicVideoAlbumEntry.entries( + albums: [Album(id: UUID(), name: "Works/Spring Trip", videoIDs: [], type: .video)], + videos: [] + )[0] + + #expect(entry.matches(query: "")) + #expect(entry.matches(query: " ")) + #expect(entry.matches(query: "spring")) + #expect(entry.matches(query: "WORKS")) + #expect(!entry.matches(query: "winter")) + } +} From 8287d2e069a6aa68738eca983e0ac7485284eace Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8E=9F=E3=80=80=E9=A2=AF=E7=99=BB?= Date: Wed, 4 Nov 2026 13:23:16 +0900 Subject: [PATCH 7/9] =?UTF-8?q?feat(musicvideo):=20=E3=82=AB=E3=83=83?= =?UTF-8?q?=E3=83=88=E5=89=B2=E3=82=8A=E3=83=BB=E7=94=BB=E9=9D=A2=E8=A1=A8?= =?UTF-8?q?=E7=A4=BA=E3=83=BB=E5=88=87=E3=82=8A=E6=9B=BF=E3=81=88=E5=8A=B9?= =?UTF-8?q?=E6=9E=9C=E3=83=BB=E3=83=95=E3=82=A7=E3=83=BC=E3=83=89=E3=83=BB?= =?UTF-8?q?=E6=9B=B2=E7=AF=84=E5=9B=B2=E3=81=AE=E8=AA=BF=E6=95=B4=E3=83=A2?= =?UTF-8?q?=E3=83=87=E3=83=AB=E3=81=A8=E5=90=88=E6=88=90=E5=87=A6=E7=90=86?= =?UTF-8?q?=E3=82=92=E8=BF=BD=E5=8A=A0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Models/MusicVideoPlanStats.swift | 91 ++++ .../Models/MusicVideoPreferences.swift | 14 +- .../MusicVideo/Models/MusicVideoTuning.swift | 288 +++++++++++++ .../MusicVideo/Services/CutPlanner.swift | 105 +++-- .../Services/MusicVideoComposer.swift | 390 +++++++++++++++--- 5 files changed, 808 insertions(+), 80 deletions(-) create mode 100644 ArkServer/Features/MusicVideo/Models/MusicVideoPlanStats.swift create mode 100644 ArkServer/Features/MusicVideo/Models/MusicVideoTuning.swift diff --git a/ArkServer/Features/MusicVideo/Models/MusicVideoPlanStats.swift b/ArkServer/Features/MusicVideo/Models/MusicVideoPlanStats.swift new file mode 100644 index 0000000..8915f3e --- /dev/null +++ b/ArkServer/Features/MusicVideo/Models/MusicVideoPlanStats.swift @@ -0,0 +1,91 @@ +// ArkServer/Features/MusicVideo/Models/MusicVideoPlanStats.swift + +import Foundation + +/// いまのカット割りの結果を表す数値。調整項目の横に出して、「変えるとどうなるか」を目で確かめられるようにする。 +nonisolated struct MusicVideoPlanStats: Equatable, Sendable { + var cutCount: Int + var averageCutDuration: Double + var shortestCutDuration: Double + var longestCutDuration: Double + /// 実際に使った動画の本数。 + var usedVideoCount: Int + /// 素材として使える動画の本数。 + var poolVideoCount: Int + /// 映像の動きが、曲の盛り上がりにどれだけ合っているか(0〜1)。調べられないときは nil。 + var motionMatch: Double? + + init(plan: CutPlan, pool: [SourceMotionProfile], analysis: MusicAnalysis?) { + let durations = plan.cuts.map(\.duration) + cutCount = durations.count + averageCutDuration = durations.isEmpty ? 0 : durations.reduce(0, +) / Double(durations.count) + shortestCutDuration = durations.min() ?? 0 + longestCutDuration = durations.max() ?? 0 + usedVideoCount = Set(plan.cuts.map(\.videoID)).count + poolVideoCount = Set(pool.map(\.videoID)).count + motionMatch = analysis.flatMap { Self.motionMatch(plan: plan, pool: pool, analysis: $0) } + } + + /// 各カットの素材の動きと、狙った動きとの差の平均を、1 から引いた値。 + /// 素材の動きを調べた区間(窓)に収まっていないカットは数えない。 + static func motionMatch(plan: CutPlan, pool: [SourceMotionProfile], analysis: MusicAnalysis) -> Double? { + var windowsByVideo: [UUID: [SourceMotionProfile]] = [:] + for profile in pool { windowsByVideo[profile.videoID, default: []].append(profile) } + + var totalGap = 0.0 + var counted = 0 + for cut in plan.cuts { + let end = cut.sourceStart + cut.duration + guard let window = windowsByVideo[cut.videoID]?.first(where: { + $0.offset <= cut.sourceStart + 1e-6 && end <= $0.offset + $0.duration + 1e-6 + }) else { continue } + let motion = window.meanMotion(start: cut.sourceStart - window.offset, length: cut.duration) + let target = CutPlanner.targetMotion( + intensity: cut.intensity, + start: cut.timelineStart, + length: cut.duration, + analysis: analysis + ) + totalGap += abs(motion - target) + counted += 1 + } + guard counted > 0 else { return nil } + return min(1, max(0, 1 - totalGap / Double(counted))) + } +} + +/// 調整項目を変えたときの、変更前と変更後の違い。「どう変わったか」を一行で見せる。 +nonisolated struct MusicVideoChangeSummary: Equatable, Sendable { + /// 変えた項目の名前(「動画のばらけ具合」など)。 + var title: String + var before: MusicVideoPlanStats + var after: MusicVideoPlanStats + + /// 例: 「カット 64 → 48・平均 1.4秒 → 1.9秒・使った動画 9 → 14本」。変わらなかった数値は出さない。 + var text: String { + var parts: [String] = [] + if before.cutCount != after.cutCount { + parts.append("カット \(before.cutCount) → \(after.cutCount)") + } + if abs(before.averageCutDuration - after.averageCutDuration) >= 0.05 { + parts.append("平均 \(Self.seconds(before.averageCutDuration)) → \(Self.seconds(after.averageCutDuration))") + } + if before.usedVideoCount != after.usedVideoCount { + parts.append("使った動画 \(before.usedVideoCount) → \(after.usedVideoCount)本") + } + if let oldMatch = before.motionMatch, let newMatch = after.motionMatch, + abs(oldMatch - newMatch) >= 0.01 { + parts.append("動きの一致 \(Self.percent(oldMatch)) → \(Self.percent(newMatch))") + } + if parts.isEmpty { return "「\(title)」を変えました.数値の上では大きな違いはありません." } + return "「\(title)」を変えました:" + parts.joined(separator: "・") + } + + static func seconds(_ value: Double) -> String { + String(format: "%.1f秒", value) + } + + static func percent(_ value: Double) -> String { + "\(Int((value * 100).rounded()))%" + } +} diff --git a/ArkServer/Features/MusicVideo/Models/MusicVideoPreferences.swift b/ArkServer/Features/MusicVideo/Models/MusicVideoPreferences.swift index 3ec15d7..63d13da 100644 --- a/ArkServer/Features/MusicVideo/Models/MusicVideoPreferences.swift +++ b/ArkServer/Features/MusicVideo/Models/MusicVideoPreferences.swift @@ -7,6 +7,12 @@ nonisolated struct MusicVideoPreferences: Codable, Equatable, Sendable { var cutStyle: MusicVideoCutStyle = .standard var renderPreset: MusicVideoRenderPreset = .landscapeFullHD var exportQuality: MusicVideoExportQuality = .high + /// カット割りの調整項目(最短・最長のカット長、動きの合わせ方、動画のばらけ具合、切り替えのタイミング)。 + var cutTuning = MusicVideoCutTuning() + /// 見た目と音の調整項目(画面の合わせ方、切り替え効果、フェード)。 + var lookTuning = MusicVideoLookTuning() + /// 解析に使う素材動画の本数。 + var sourceLimit = MusicVideoSourceLimit.standard var selectedAlbumIDs: [UUID] = [] var selectedVideoIDs: [UUID] = [] var includeFavorites = false @@ -36,7 +42,8 @@ nonisolated struct MusicVideoPreferences: Codable, Equatable, Sendable { // 後から項目を足しても、古い保存データを読めるようにする(無い項目は既定値)。 private enum CodingKeys: String, CodingKey { - case cutStyle, renderPreset, exportQuality, selectedAlbumIDs, selectedVideoIDs, includeFavorites + case cutStyle, renderPreset, exportQuality, cutTuning, lookTuning, sourceLimit + case selectedAlbumIDs, selectedVideoIDs, includeFavorites case musicFolderPath, recentMusicPaths } @@ -47,6 +54,11 @@ nonisolated struct MusicVideoPreferences: Codable, Equatable, Sendable { cutStyle = try container.decodeIfPresent(MusicVideoCutStyle.self, forKey: .cutStyle) ?? .standard renderPreset = try container.decodeIfPresent(MusicVideoRenderPreset.self, forKey: .renderPreset) ?? .landscapeFullHD exportQuality = try container.decodeIfPresent(MusicVideoExportQuality.self, forKey: .exportQuality) ?? .high + cutTuning = try container.decodeIfPresent(MusicVideoCutTuning.self, forKey: .cutTuning) ?? MusicVideoCutTuning() + lookTuning = try container.decodeIfPresent(MusicVideoLookTuning.self, forKey: .lookTuning) ?? MusicVideoLookTuning() + sourceLimit = MusicVideoSourceLimit.normalized( + try container.decodeIfPresent(Int.self, forKey: .sourceLimit) ?? MusicVideoSourceLimit.standard + ) selectedAlbumIDs = try container.decodeIfPresent([UUID].self, forKey: .selectedAlbumIDs) ?? [] selectedVideoIDs = try container.decodeIfPresent([UUID].self, forKey: .selectedVideoIDs) ?? [] includeFavorites = try container.decodeIfPresent(Bool.self, forKey: .includeFavorites) ?? false diff --git a/ArkServer/Features/MusicVideo/Models/MusicVideoTuning.swift b/ArkServer/Features/MusicVideo/Models/MusicVideoTuning.swift new file mode 100644 index 0000000..2cfbf57 --- /dev/null +++ b/ArkServer/Features/MusicVideo/Models/MusicVideoTuning.swift @@ -0,0 +1,288 @@ +// ArkServer/Features/MusicVideo/Models/MusicVideoTuning.swift + +import Foundation + +// ミュージックビデオの調整項目。 +// 「カット割り」に効くもの(MusicVideoCutTuning)と、「見た目と音」に効くもの(MusicVideoLookTuning)に分ける。 +// どの項目も既定値は、この項目を足す前の動作と同じにしてある。 + +/// 曲の盛り上がりに、映像の動きの大きさをどのくらい合わせるか。 +nonisolated enum MotionMatching: String, Codable, CaseIterable, Hashable, Sendable { + case off + case weak + case standard + case strong + + var displayName: String { + switch self { + case .off: return "合わせない" + case .weak: return "弱い" + case .standard: return "標準" + case .strong: return "強い" + } + } + + /// 動きの差(0〜1)に掛ける重み。大きいほど、狙った動きに近い素材を選ぶ。 + var weight: Double { + switch self { + case .off: return 0 + case .weak: return 1 + case .standard: return 2 + case .strong: return 4 + } + } + + var summary: String { + switch self { + case .off: return "動きの大きさは見ず、素材をばらけさせて選びます." + case .weak: return "動きの大きさを少しだけ考えて選びます." + case .standard: return "盛り上がる所では動きの大きい映像、静かな所では動きの少ない映像を選びます." + case .strong: return "動きの大きさを最優先で合わせます.素材が偏ることがあります." + } + } +} + +/// 同じ動画を、どれだけ避けるか(どれだけいろいろな動画を使うか)。 +nonisolated enum VideoVariety: String, Codable, CaseIterable, Hashable, Sendable { + case wide + case standard + case repeating + + var displayName: String { + switch self { + case .wide: return "いろいろ" + case .standard: return "標準" + case .repeating: return "多めに使い回す" + } + } + + /// 直前のカットと同じ動画を選んだときの減点。 + var avoidLastPenalty: Double { + switch self { + case .wide: return 2.0 + case .standard: return 1.0 + case .repeating: return 0.2 + } + } + + /// すでに使った回数 1 回ごとの減点。大きいほど、まだ使っていない動画を選ぶ。 + var usagePenalty: Double { + switch self { + case .wide: return 0.3 + case .standard: return 0.05 + case .repeating: return 0 + } + } + + /// すでに使った区間と重なる位置を選んだときの減点。 + var overlapPenalty: Double { + switch self { + case .wide: return 1.5 + case .standard: return 0.8 + case .repeating: return 0.4 + } + } + + var summary: String { + switch self { + case .wide: return "できるだけ違う動画を使います.使う動画の本数が増えます." + case .standard: return "同じ動画が続かない程度に、自然にばらけさせます." + case .repeating: return "動きが合う動画を、何度でも使います.使う動画の本数が減ります." + } + } +} + +/// 切り替えの位置を、どう決めるか。 +nonisolated enum CutAlignment: String, Codable, CaseIterable, Hashable, Sendable { + /// 2拍以上のカットは、区切りのよい拍(小節の頭)に境界をそろえる。 + case bar + /// 設定した拍数ぴったりで切る。 + case free + + var displayName: String { + switch self { + case .bar: return "区切りにそろえる" + case .free: return "拍の数どおり" + } + } + + var summary: String { + switch self { + case .bar: return "盛り上がりが変わる所で、切り替えを区切りのよい拍に寄せます.リズムが整います." + case .free: return "決めた拍の数ぴったりで切ります.変わり目で、区切りとずれることがあります." + } + } +} + +/// カット割りに効く調整項目。変えると、素材の解析はそのままで、カット割りだけを作り直せる。 +nonisolated struct MusicVideoCutTuning: Codable, Equatable, Sendable { + /// これより短いカットは作らない(秒)。 + var minimumCutDuration: Double = 0.3 + /// これより長いカットは作らない(秒)。nil なら制限しない。 + var maximumCutDuration: Double? + var motionMatching: MotionMatching = .standard + var variety: VideoVariety = .standard + var alignment: CutAlignment = .bar + + static let minimumChoices: [Double] = [0.3, 0.5, 0.8, 1.0, 1.5, 2.0] + static let maximumChoices: [Double] = [1.0, 1.5, 2.0, 3.0, 4.0, 6.0, 8.0] + + /// 最短を変える。最長より長くなるときは、最長も合わせて延ばす。 + mutating func setMinimum(_ value: Double) { + minimumCutDuration = value + if let maximum = maximumCutDuration, maximum < value { maximumCutDuration = value } + } + + /// 最長を変える。最短より短くなるときは、最短も合わせて縮める。 + mutating func setMaximum(_ value: Double?) { + maximumCutDuration = value + if let value, value < minimumCutDuration { minimumCutDuration = value } + } +} + +/// 画面に素材をどう収めるか。 +nonisolated enum MusicVideoFitMode: String, Codable, CaseIterable, Hashable, Sendable { + /// 画面いっぱいに敷き詰める(はみ出す部分は切り落とす)。 + case fill + /// 素材の全体を見せる(余った所は黒帯)。 + case fit + + var displayName: String { + switch self { + case .fill: return "画面いっぱい" + case .fit: return "全体を見せる" + } + } + + var summary: String { + switch self { + case .fill: return "素材を拡大して画面を埋めます.はみ出す部分は切り取られます." + case .fit: return "素材の全体を見せます.縦横比が違う素材には黒い帯が出ます." + } + } +} + +/// カットの切り替え方。 +nonisolated enum MusicVideoTransition: String, Codable, CaseIterable, Hashable, Sendable { + case cut + case crossfade + case flash + + var displayName: String { + switch self { + case .cut: return "そのまま" + case .crossfade: return "クロスフェード" + case .flash: return "フラッシュ" + } + } + + /// 切り替えにかける時間(秒)。そのままは 0。 + var duration: Double { + switch self { + case .cut: return 0 + case .crossfade: return 0.3 + case .flash: return 0.12 + } + } + + var summary: String { + switch self { + case .cut: return "拍の位置で、ぱっと切り替えます." + case .crossfade: return "拍の位置を中心に、前後の映像を\(Self.secondsText(0.3))秒かけて重ねます." + case .flash: return "拍の位置で、画面を白く光らせてから切り替えます." + } + } + + private static func secondsText(_ value: Double) -> String { + String(format: "%.1f", value) + } +} + +/// 見た目と音に効く調整項目。カット割りは変わらず、合成だけをやり直す。 +nonisolated struct MusicVideoLookTuning: Codable, Equatable, Sendable { + var fitMode: MusicVideoFitMode = .fill + var transition: MusicVideoTransition = .cut + /// 映像と音の、最初と最後のフェード(秒)。0 ならフェードしない。 + var fadeSeconds: Double = 0 + + static let fadeChoices: [Double] = [0, 0.5, 1, 2] +} + +/// 曲のうち、映像にする範囲(秒)。 +nonisolated struct MusicRange: Equatable, Sendable { + var start: Double + var end: Double + + var length: Double { end - start } + + /// これより短い範囲は選べない。 + static let minimumLength = 5.0 + + /// 曲の長さに収めた範囲。短すぎるときは、最短の長さまで広げる。全体と同じなら nil。 + static func clamped(start: Double, end: Double, songDuration: Double) -> MusicRange? { + guard songDuration > minimumLength else { return nil } + var lower = min(max(0, start), songDuration - minimumLength) + var upper = min(max(end, lower + minimumLength), songDuration) + lower = min(lower, upper - minimumLength) + upper = max(upper, lower + minimumLength) + if lower <= 0.001, upper >= songDuration - 0.001 { return nil } + return MusicRange(start: lower, end: upper) + } +} + +/// 解析に使う素材動画の本数の選択肢。選んだ動画がこれより多いときは、無作為にこの本数へ絞る。 +/// 多いほど変化に富むが、初回の解析に時間がかかる(解析した結果は保存され、次回から速い)。 +nonisolated enum MusicVideoSourceLimit { + static let choices = [10, 20, 40, 80, 120, 200] + static let standard = 40 + + /// 選択肢にない値(古い保存データなど)は、最も近い選択肢に直す。 + static func normalized(_ value: Int) -> Int { + choices.min { abs($0 - value) < abs($1 - value) } ?? standard + } +} + +/// カット割りを作ったときの設定。取り消し・やり直しで、カット割りと一緒に元へ戻す。 +nonisolated struct MusicVideoPlanSettings: Equatable, Sendable { + var cutStyle: MusicVideoCutStyle + var cutTuning: MusicVideoCutTuning + var musicRange: MusicRange? +} + +extension MusicAnalysis { + /// 曲の `range` の部分だけを取り出した解析結果。時刻は範囲の先頭が 0 秒になるようにずらす。 + func trimmed(to range: MusicRange) -> MusicAnalysis { + let start = min(max(0, range.start), duration) + let end = min(max(start, range.end), duration) + let length = end - start + guard length > 0 else { return self } + + let newBeats = beats.filter { $0 >= start && $0 < end }.map { $0 - start } + guard energyHop > 0, !energy.isEmpty else { + return MusicAnalysis(duration: length, tempo: tempo, beats: newBeats, energy: energy, intensity: intensity, energyHop: energyHop) + } + let count = max(1, Int((length / energyHop).rounded(.up))) + var newEnergy: [Double] = [] + var newIntensity: [MusicIntensity] = [] + newEnergy.reserveCapacity(count) + newIntensity.reserveCapacity(count) + for index in 0.. Double { + beats.min { abs($0 - time) < abs($1 - time) } ?? time + } +} diff --git a/ArkServer/Features/MusicVideo/Services/CutPlanner.swift b/ArkServer/Features/MusicVideo/Services/CutPlanner.swift index de5ed9a..5f892e2 100644 --- a/ArkServer/Features/MusicVideo/Services/CutPlanner.swift +++ b/ArkServer/Features/MusicVideo/Services/CutPlanner.swift @@ -8,9 +8,29 @@ nonisolated struct CutPlanner: Sendable { var style: MusicVideoCutStyle = .standard /// これより短いカットは作らない(拍が速すぎる曲では切り替えの間隔を倍にする)。 var minimumCutDuration = 0.3 + /// これより長いカットは作らない(nil なら制限しない)。拍の数を減らして収める。 + /// 最短と同時に守れないときは、最長を優先する。 + var maximumCutDuration: Double? + /// 盛り上がりに映像の動きを合わせる強さ。 + var motionMatching: MotionMatching = .standard + /// 同じ動画をどれだけ避けるか。 + var variety: VideoVariety = .standard + /// 切り替えの位置を、小節の頭にそろえるか。 + var alignment: CutAlignment = .bar /// 1カットごとに試す素材候補の数。多いほど動きの一致度が上がる。 var candidateAttemptsPerCut = 40 + init() {} + + init(style: MusicVideoCutStyle, tuning: MusicVideoCutTuning) { + self.style = style + minimumCutDuration = tuning.minimumCutDuration + maximumCutDuration = tuning.maximumCutDuration + motionMatching = tuning.motionMatching + variety = tuning.variety + alignment = tuning.alignment + } + func plan( analysis: MusicAnalysis, pool: [SourceMotionProfile], @@ -39,19 +59,17 @@ nonisolated struct CutPlanner: Sendable { } // 曲の終わりに短い余りが出るなら、今のカットを曲の終わりまで延ばして吸収する。 + // 最長を決めているときは、最長を超えるなら吸収しない。 let remainingAfter = analysis.duration - end if remainingAfter > 0, remainingAfter < minimumCutDuration, - pool.contains(where: { $0.duration >= analysis.duration - start }) { + pool.contains(where: { $0.duration >= analysis.duration - start }), + maximumCutDuration.map({ analysis.duration - start <= $0 + 1e-9 }) ?? true { end = analysis.duration } let length = end - start guard length > 0 else { break } - // 狙う動きの大きさ: 段階ごとの目安と、その時点の連続的な盛り上がりの平均。 - let midpoint: Double = start + length / 2 - let levelTarget: Double = intensity.targetMotion - let energyTarget: Double = analysis.energy(at: midpoint) - let target: Double = (levelTarget + energyTarget) / 2 + let target = Self.targetMotion(intensity: intensity, start: start, length: length, analysis: analysis) guard let choice = pickClip( length: length, target: target, @@ -92,33 +110,64 @@ nonisolated struct CutPlanner: Sendable { return grid } - /// 現在位置から次のカット境界までの拍数。 - /// 長いカット(2拍以上)は小節の頭に揃え、拍が速すぎる曲では最短時間を満たすまで倍にする。 - private func nextStep(from index: Int, intensity: MusicIntensity, grid: [Double]) -> Int { + /// 盛り上がりの段階 `intensity` で、1カットに使う拍の数。 + /// 拍が速すぎる曲では最短時間を満たすまで倍にし、最長が決まっていれば、その長さに収まるまで減らす。 + /// 画面の説明(「静かな所は約2.0秒ごと」)にも同じ計算を使う。 + func effectiveBeats(for intensity: MusicIntensity, beatInterval: Double) -> Int { var beats = max(1, style.beatsPerCut(for: intensity)) - let beatInterval = averageInterval(grid: grid, around: index) while Double(beats) * beatInterval < minimumCutDuration, beats < 16 { beats *= 2 } + if let maximumCutDuration, beatInterval > 0 { + let allowed = max(1, Int((maximumCutDuration / beatInterval + 1e-9).rounded(.down))) + beats = min(beats, allowed) + } + return beats + } + + /// 現在位置から次のカット境界までの拍数。 + /// 長いカット(2拍以上)は小節の頭に揃える(`alignment` が `.bar` のとき)。 + private func nextStep(from index: Int, intensity: MusicIntensity, grid: [Double]) -> Int { + let beatInterval = averageInterval(grid: grid, around: index) + let beats = effectiveBeats(for: intensity, beatInterval: beatInterval) let remainingSteps = max(1, grid.count - 1 - index) - // 格子の先頭(0秒)は拍ではない。最初のカットは1拍目までの導入部にするか、 - // 導入部が短すぎるなら最初の小節の終わりまで続ける。 + var step = beats if index == 0 { + // 格子の先頭(0秒)は拍ではない。最初のカットは1拍目までの導入部にするか、 + // 導入部が短すぎるなら最初の小節の終わりまで続ける。 let introGap = grid[1] - grid[0] - return min(introGap >= minimumCutDuration ? 1 : beats + 1, remainingSteps) - } - - // 以降は、小節(beats 拍)の頭に境界を揃える。拍の番号は格子の番号 - 1。 - var step = beats - if beats >= 2 { + step = introGap >= minimumCutDuration ? 1 : beats + 1 + } else if beats >= 2, alignment == .bar { + // 以降は、小節(beats 拍)の頭に境界を揃える。拍の番号は格子の番号 - 1。 let remainder = (index - 1) % beats if remainder != 0 { let toBoundary = beats - remainder step = toBoundary >= max(1, beats / 2) ? toBoundary : toBoundary + beats } } - return min(step, remainingSteps) + step = min(step, remainingSteps) + + // 揃えた結果が最短に足りないときは、拍の位置を保ったまま延ばす。 + while step < remainingSteps, grid[index + step] - grid[index] < minimumCutDuration - 1e-9 { + step += 1 + } + + // 揃えた結果が最長を超えるときは、拍の位置を保ったまま短くする(最短と両立しないときは最長を優先)。 + if let maximumCutDuration { + while step > 1, grid[index + step] - grid[index] > maximumCutDuration + 1e-9 { + step -= 1 + } + } + return step + } + + /// カットが狙う動きの大きさ(0〜1)。段階ごとの目安と、その時点の連続的な盛り上がりの平均。 + static func targetMotion(intensity: MusicIntensity, start: Double, length: Double, analysis: MusicAnalysis) -> Double { + let midpoint: Double = start + length / 2 + let levelTarget: Double = intensity.targetMotion + let energyTarget: Double = analysis.energy(at: midpoint) + return (levelTarget + energyTarget) / 2 } private func averageInterval(grid: [Double], around index: Int) -> Double { @@ -170,10 +219,10 @@ nonisolated struct CutPlanner: Sendable { continue } - var score = -2 * abs(motion - target) - if hasAlternative, avoidVideoIDs.contains(profile.videoID) { score -= 1.0 } - score -= 0.05 * Double(usage[profile.videoID] ?? 0) - if (usedRanges[profile.videoID] ?? []).contains(where: { $0.overlaps(range) }) { score -= 0.8 } + var score = -motionMatching.weight * abs(motion - target) + if hasAlternative, avoidVideoIDs.contains(profile.videoID) { score -= variety.avoidLastPenalty } + score -= variety.usagePenalty * Double(usage[profile.videoID] ?? 0) + if (usedRanges[profile.videoID] ?? []).contains(where: { $0.overlaps(range) }) { score -= variety.overlapPenalty } score += 0.05 * Double.random(in: 0...1, using: &generator) if best == nil || score > best!.score { @@ -224,10 +273,12 @@ nonisolated struct CutPlanner: Sendable { if index + 1 < plan.cuts.count { avoid.insert(plan.cuts[index + 1].videoID) } } - let midpoint: Double = original.timelineStart + original.duration / 2 - let levelTarget: Double = original.intensity.targetMotion - let energyTarget: Double = analysis.energy(at: midpoint) - let target: Double = (levelTarget + energyTarget) / 2 + let target = Self.targetMotion( + intensity: original.intensity, + start: original.timelineStart, + length: original.duration, + analysis: analysis + ) // カットの番号ごとに乱数を変える(同じ種でも、別のカットは別の選び方になる)。 var generator = SeededGenerator(seed: seed &+ UInt64(index) &* 0x9E37_79B9_7F4A_7C15) diff --git a/ArkServer/Features/MusicVideo/Services/MusicVideoComposer.swift b/ArkServer/Features/MusicVideo/Services/MusicVideoComposer.swift index ecf5247..4198776 100644 --- a/ArkServer/Features/MusicVideo/Services/MusicVideoComposer.swift +++ b/ArkServer/Features/MusicVideo/Services/MusicVideoComposer.swift @@ -54,6 +54,8 @@ nonisolated enum MusicVideoComposerError: LocalizedError { nonisolated struct MusicVideoComposition: @unchecked Sendable { let composition: AVMutableComposition let videoComposition: AVMutableVideoComposition + /// 音のフェード。フェードしないときは nil。 + var audioMix: AVAudioMix? /// 完成映像の長さ(秒)。 let duration: Double /// 画面サイズとフレームレート。書き出しのビットレートの計算にも使う。 @@ -62,29 +64,141 @@ nonisolated struct MusicVideoComposition: @unchecked Sendable { func makePlayerItem() -> AVPlayerItem { let item = AVPlayerItem(asset: composition) item.videoComposition = videoComposition + item.audioMix = audioMix return item } } /// `CutPlan` から1本の映像を組み立て、mp3 などの音楽を付けて書き出す。 /// -/// 1拍ごとのカットだと数百カットになるので、映像トラックは1本を使い回し、 -/// 画面いっぱいに拡大する変換だけをカットの切り替え時刻ごとに差し替える。 +/// 1拍ごとのカットだと数百カットになるので、既定では映像トラックを1本使い回し、 +/// 画面に収める変換だけをカットの切り替え時刻ごとに差し替える。クロスフェードのときだけ、前後を重ねるために2本を交互に使う。 nonisolated struct MusicVideoComposer: Sendable { /// 時刻を丸める分解能。30/24/25fps のどれの1フレームも割り切れる値。 private static let timescale: CMTimeScale = 600 // MARK: - 合成 + /// `plan` のカット割りから、プレビューと書き出しに使う合成を組み立てる。 + /// - Parameters: + /// - look: 画面の合わせ方・切り替え効果・フェード。既定(画面いっぱい・そのまま切り替え・フェードなし)では、 + /// 映像トラックを1本だけ使う。 + /// - audioStart: 音楽ファイルの何秒目を、映像の 0 秒に合わせるか(曲の一部だけを使うとき)。 func makeComposition( plan: CutPlan, sourceURLs: [UUID: URL], audioURL: URL, - render: MusicVideoRenderSettings + render: MusicVideoRenderSettings, + look: MusicVideoLookTuning = MusicVideoLookTuning(), + audioStart: Double = 0 ) async throws -> MusicVideoComposition { guard !plan.cuts.isEmpty else { throw MusicVideoComposerError.emptyPlan } let composition = AVMutableComposition() + let fade = min(max(0, look.fadeSeconds), plan.duration / 2) + + let placement: Placement + switch look.transition { + case .crossfade: + placement = try await placeCrossfade(plan: plan, sourceURLs: sourceURLs, render: render, look: look, fade: fade, into: composition) + case .cut, .flash: + placement = try await placeSingleTrack(plan: plan, sourceURLs: sourceURLs, render: render, look: look, fade: fade, into: composition) + } + + let audioMix = try await addAudio( + from: audioURL, + to: composition, + duration: Self.time(plan.duration), + startOffset: audioStart, + fade: fade + ) + + // 音声のほうが長いときも、映像の指示が全体を覆うように、最後の区間を合成の終わりまで延ばす。 + var segments = placement.segments + if let last = segments.last, composition.duration > last.range.end { + segments[segments.count - 1].range = CMTimeRange(start: last.range.start, end: composition.duration) + } + + let videoComposition = AVMutableVideoComposition() + videoComposition.instructions = Self.makeInstructions( + segments: segments, + totalDuration: composition.duration, + fade: fade + ) + videoComposition.renderSize = render.size + videoComposition.frameDuration = CMTime(value: 1, timescale: CMTimeScale(render.framesPerSecond)) + // 色の扱いを BT.709 に固定する(書き出し側の指定と揃えて、色味が変わらないようにする)。 + videoComposition.colorPrimaries = AVVideoColorPrimaries_ITU_R_709_2 + videoComposition.colorTransferFunction = AVVideoTransferFunction_ITU_R_709_2 + videoComposition.colorYCbCrMatrix = AVVideoYCbCrMatrix_ITU_R_709_2 + + return MusicVideoComposition( + composition: composition, + videoComposition: videoComposition, + audioMix: audioMix, + duration: composition.duration.seconds, + render: render + ) + } + + // MARK: 合成の部品 + + private struct SourceTrack { + /// トラックは元のアセットが解放されると使えなくなる(挿入時に -12780 で失敗する)ので、アセットも持ち続ける。 + let asset: AVURLAsset + let track: AVAssetTrack + let timeRange: CMTimeRange + let naturalSize: CGSize + let preferredTransform: CGAffineTransform + } + + /// 映像の1つの層。どのトラックを、どの変換で映すか。 + private struct LayerSpec { + var track: AVMutableCompositionTrack + /// (時刻, 変換)。カットが替わる時刻で変換を差し替える。 + var transforms: [(time: CMTime, transform: CGAffineTransform)] + /// この区間のあいだに 1→0 へ消える(クロスフェードで、前の映像を消す側)。 + var fadesOut = false + /// この区間のあいだに 0→1 へ現れる(フラッシュのあと、映像が戻る側)。 + var fadesIn = false + } + + /// 同じ見え方が続く時間の区間。`layers` の先頭が一番上に重なる。 + private struct Segment { + var range: CMTimeRange + var layers: [LayerSpec] + var background: CGColor + } + + private struct Placement { + var segments: [Segment] + } + + // 背景色は RGB で指定する(グレースケールの色は AVFoundation に無視されて、常に黒になる)。 + private static let black = CGColor(srgbRed: 0, green: 0, blue: 0, alpha: 1) + private static let white = CGColor(srgbRed: 1, green: 1, blue: 1, alpha: 1) + + private func loadedSource( + for videoID: UUID, + urls: [UUID: URL], + cache: inout [UUID: SourceTrack] + ) async throws -> SourceTrack { + if let known = cache[videoID] { return known } + guard let url = urls[videoID] else { throw MusicVideoComposerError.missingSource(videoID) } + let loaded = try await loadSource(url: url) + cache[videoID] = loaded + return loaded + } + + /// 映像トラックを1本だけ使う。そのまま切り替える(既定)か、切り替えのたびに白く光らせる。 + private func placeSingleTrack( + plan: CutPlan, + sourceURLs: [UUID: URL], + render: MusicVideoRenderSettings, + look: MusicVideoLookTuning, + fade: Double, + into composition: AVMutableComposition + ) async throws -> Placement { guard let videoTrack = composition.addMutableTrack( withMediaType: .video, preferredTrackID: kCMPersistentTrackID_Invalid @@ -93,20 +207,11 @@ nonisolated struct MusicVideoComposer: Sendable { } var sources: [UUID: SourceTrack] = [:] - let layerInstruction = AVMutableVideoCompositionLayerInstruction(assetTrack: videoTrack) + var placed: [(cutIndex: Int, start: CMTime, transform: CGAffineTransform)] = [] - for cut in plan.cuts { + for (index, cut) in plan.cuts.enumerated() { try Task.checkCancellation() - let source: SourceTrack - if let known = sources[cut.videoID] { - source = known - } else { - guard let url = sourceURLs[cut.videoID] else { - throw MusicVideoComposerError.missingSource(cut.videoID) - } - source = try await loadSource(url: url) - sources[cut.videoID] = source - } + let source = try await loadedSource(for: cut.videoID, urls: sourceURLs, cache: &sources) // 開始・終了をそれぞれ丸めて差を長さにすることで、カット間に隙間やずれを作らない。 let start = Self.time(cut.timelineStart) @@ -125,44 +230,202 @@ nonisolated struct MusicVideoComposer: Sendable { of: source.track, at: start ) - layerInstruction.setTransform( - Self.fillTransform(for: source, renderSize: render.size), - at: start + placed.append((index, start, Self.transform(for: source, renderSize: render.size, fit: look.fitMode))) + } + + let videoEnd = videoTrack.timeRange.end + guard !placed.isEmpty else { throw MusicVideoComposerError.emptyPlan } + + // そのまま切り替えるなら、全体で1つの区間にして、変換だけを時刻ごとに差し替える。 + if look.transition == .cut { + let layer = LayerSpec(track: videoTrack, transforms: placed.map { ($0.start, $0.transform) }) + return Placement(segments: [ + Segment(range: CMTimeRange(start: .zero, end: videoEnd), layers: [layer], background: Self.black) + ]) + } + + // フラッシュ: 各カットの頭で、白い背景から映像が 0→1 に戻る短い区間を挟む。 + var segments: [Segment] = [] + for (position, item) in placed.enumerated() { + let segmentStart = position == 0 ? CMTime.zero : item.start + let segmentEnd = position + 1 < placed.count ? placed[position + 1].start : videoEnd + guard segmentEnd > segmentStart else { continue } + let boundary = plan.cuts[item.cutIndex].timelineStart + let length = (segmentEnd - segmentStart).seconds + let flashLength = min(look.transition.duration, length / 2) + let flashes = position > 0 && flashLength >= 0.04 && !Self.isInFadeZone( + boundary, halfWidth: flashLength, fade: fade, total: plan.duration ) + + if flashes { + let flashEnd = CMTimeAdd(segmentStart, Self.time(flashLength)) + segments.append(Segment( + range: CMTimeRange(start: segmentStart, end: flashEnd), + layers: [LayerSpec(track: videoTrack, transforms: [(segmentStart, item.transform)], fadesIn: true)], + background: Self.white + )) + segments.append(Segment( + range: CMTimeRange(start: flashEnd, end: segmentEnd), + layers: [LayerSpec(track: videoTrack, transforms: [(flashEnd, item.transform)])], + background: Self.black + )) + } else { + segments.append(Segment( + range: CMTimeRange(start: segmentStart, end: segmentEnd), + layers: [LayerSpec(track: videoTrack, transforms: [(segmentStart, item.transform)])], + background: Self.black + )) + } } + return Placement(segments: segments) + } - let totalDuration = Self.time(plan.duration) - try await addAudio(from: audioURL, to: composition, duration: totalDuration) + /// 映像トラックを2本、交互に使い、切り替えの前後を重ねて消し合う(クロスフェード)。 + /// 切り替えは拍の位置を中心にし、前のカットは拍のあとへ、次のカットは拍の前へ、素材を少しはみ出して使う。 + private func placeCrossfade( + plan: CutPlan, + sourceURLs: [UUID: URL], + render: MusicVideoRenderSettings, + look: MusicVideoLookTuning, + fade: Double, + into composition: AVMutableComposition + ) async throws -> Placement { + guard + let trackA = composition.addMutableTrack(withMediaType: .video, preferredTrackID: kCMPersistentTrackID_Invalid), + let trackB = composition.addMutableTrack(withMediaType: .video, preferredTrackID: kCMPersistentTrackID_Invalid) + else { + throw MusicVideoComposerError.cannotCreateTrack + } + let tracks = [trackA, trackB] + let cuts = plan.cuts + let count = cuts.count + + // 各カットの開始位置。最後のカットの終わりも含める。時刻は一度だけ丸め、前後の区間で同じ値を使う。 + var bounds = cuts.map { Self.time($0.timelineStart) } + bounds.append(Self.time(cuts[count - 1].timelineEnd)) + + // overlap[i]: i 番目のカットの頭の切り替えの長さ(秒)。0 なら重ねない。 + var overlap = [Double](repeating: 0, count: count + 1) + if count > 1 { + for index in 1..= 0.04, !Self.isInFadeZone(cuts[index].timelineStart, halfWidth: length / 2, fade: fade, total: plan.duration) { + overlap[index] = length + } + } + } + func half(_ index: Int) -> CMTime { Self.time(overlap[index] / 2) } - let instruction = AVMutableVideoCompositionInstruction() - instruction.timeRange = CMTimeRange(start: .zero, duration: composition.duration) - instruction.backgroundColor = CGColor(gray: 0, alpha: 1) - instruction.layerInstructions = [layerInstruction] + var sources: [UUID: SourceTrack] = [:] + var transforms: [CGAffineTransform] = [] + for (index, cut) in cuts.enumerated() { + try Task.checkCancellation() + let source = try await loadedSource(for: cut.videoID, urls: sourceURLs, cache: &sources) + transforms.append(Self.transform(for: source, renderSize: render.size, fit: look.fitMode)) - let videoComposition = AVMutableVideoComposition() - videoComposition.instructions = [instruction] - videoComposition.renderSize = render.size - videoComposition.frameDuration = CMTime(value: 1, timescale: CMTimeScale(render.framesPerSecond)) - // 色の扱いを BT.709 に固定する(書き出し側の指定と揃えて、色味が変わらないようにする)。 - videoComposition.colorPrimaries = AVVideoColorPrimaries_ITU_R_709_2 - videoComposition.colorTransferFunction = AVVideoTransferFunction_ITU_R_709_2 - videoComposition.colorYCbCrMatrix = AVVideoYCbCrMatrix_ITU_R_709_2 + // このカットが占める時間: 前の切り替えの半分だけ早く始まり、次の切り替えの半分だけ遅く終わる。 + let timelineStart = CMTimeSubtract(bounds[index], half(index)) + let timelineEnd = CMTimeAdd(bounds[index + 1], half(index + 1)) + let length = CMTimeSubtract(timelineEnd, timelineStart) + guard length > .zero else { continue } - return MusicVideoComposition( - composition: composition, - videoComposition: videoComposition, - duration: composition.duration.seconds, - render: render - ) + // 素材も同じだけ前にずらして使う。素材の範囲を越えるときは、収まるまで動かす。 + var sourceStart = CMTimeSubtract(Self.time(cut.sourceStart), half(index)) + if sourceStart < source.timeRange.start { sourceStart = source.timeRange.start } + if CMTimeAdd(sourceStart, length) > source.timeRange.end { + sourceStart = max(source.timeRange.start, CMTimeSubtract(source.timeRange.end, length)) + } + try tracks[index % 2].insertTimeRange( + CMTimeRange(start: sourceStart, duration: length), + of: source.track, + at: timelineStart + ) + } + + var segments: [Segment] = [] + for index in 0.. 0, overlap[index] > 0 { + // 切り替え: 前のカットを上に重ね、1→0 に消していく。 + let start = CMTimeSubtract(bounds[index], half(index)) + let end = CMTimeAdd(bounds[index], half(index)) + segments.append(Segment( + range: CMTimeRange(start: start, end: end), + layers: [ + LayerSpec(track: tracks[(index - 1) % 2], transforms: [(start, transforms[index - 1])], fadesOut: true), + LayerSpec(track: tracks[index % 2], transforms: [(start, transforms[index])]) + ], + background: Self.black + )) + } + let soloStart = CMTimeAdd(bounds[index], half(index)) + let soloEnd = CMTimeSubtract(bounds[index + 1], half(index + 1)) + guard soloEnd > soloStart else { continue } + segments.append(Segment( + range: CMTimeRange(start: soloStart, end: soloEnd), + layers: [LayerSpec(track: tracks[index % 2], transforms: [(soloStart, transforms[index])])], + background: Self.black + )) + } + guard !segments.isEmpty else { throw MusicVideoComposerError.emptyPlan } + return Placement(segments: segments) } - private struct SourceTrack { - /// トラックは元のアセットが解放されると使えなくなる(挿入時に -12780 で失敗する)ので、アセットも持ち続ける。 - let asset: AVURLAsset - let track: AVAssetTrack - let timeRange: CMTimeRange - let naturalSize: CGSize - let preferredTransform: CGAffineTransform + /// 切り替えが、最初・最後のフェードと重なるか。重なるときは、切り替えの効果は付けない(透明度の指定が競合するため)。 + private static func isInFadeZone(_ boundary: Double, halfWidth: Double, fade: Double, total: Double) -> Bool { + guard fade > 0 else { return false } + return boundary - halfWidth < fade || boundary + halfWidth > total - fade + } + + /// 区間ごとの指示を作る。最初と最後の `fade` 秒は、全体の透明度を 0↔1 に変える。 + private static func makeInstructions( + segments: [Segment], + totalDuration: CMTime, + fade: Double + ) -> [AVMutableVideoCompositionInstruction] { + let total = totalDuration.seconds + let fadeTime = time(fade) + let fadeInZone = CMTimeRange(start: .zero, duration: fadeTime) + let fadeOutZone = CMTimeRange(start: CMTimeSubtract(totalDuration, fadeTime), duration: fadeTime) + + return segments.map { segment in + let instruction = AVMutableVideoCompositionInstruction() + instruction.timeRange = segment.range + instruction.backgroundColor = segment.background + + instruction.layerInstructions = segment.layers.map { layer in + let layerInstruction = AVMutableVideoCompositionLayerInstruction(assetTrack: layer.track) + for entry in layer.transforms { + layerInstruction.setTransform(entry.transform, at: entry.time) + } + if layer.fadesOut { + layerInstruction.setOpacityRamp(fromStartOpacity: 1, toEndOpacity: 0, timeRange: segment.range) + } + if layer.fadesIn { + layerInstruction.setOpacityRamp(fromStartOpacity: 0, toEndOpacity: 1, timeRange: segment.range) + } + if fade > 0 { + let intoVideo = segment.range.intersection(fadeInZone) + if intoVideo.duration > .zero { + layerInstruction.setOpacityRamp( + fromStartOpacity: Float(intoVideo.start.seconds / fade), + toEndOpacity: Float(intoVideo.end.seconds / fade), + timeRange: intoVideo + ) + } + let outOfVideo = segment.range.intersection(fadeOutZone) + if outOfVideo.duration > .zero { + layerInstruction.setOpacityRamp( + fromStartOpacity: Float((total - outOfVideo.start.seconds) / fade), + toEndOpacity: Float((total - outOfVideo.end.seconds) / fade), + timeRange: outOfVideo + ) + } + } + return layerInstruction + } + return instruction + } } private func loadSource(url: URL) async throws -> SourceTrack { @@ -180,11 +443,14 @@ nonisolated struct MusicVideoComposer: Sendable { ) } + /// 音楽を映像の 0 秒に合わせて入れる。`fade` が 0 より大きければ、最初と最後で音量を 0↔1 に変える。 private func addAudio( from url: URL, to composition: AVMutableComposition, - duration: CMTime - ) async throws { + duration: CMTime, + startOffset: Double, + fade: Double + ) async throws -> AVAudioMix? { let asset = AVURLAsset(url: url) guard let sourceTrack = try await asset.loadTracks(withMediaType: .audio).first else { throw MusicVideoComposerError.noAudioTrack @@ -196,21 +462,40 @@ nonisolated struct MusicVideoComposer: Sendable { throw MusicVideoComposerError.cannotCreateTrack } let available = try await sourceTrack.load(.timeRange) - let length = min(duration, available.duration) + let offset = Self.time(max(0, startOffset)) + let start = min(CMTimeAdd(available.start, offset), available.end) + let length = min(duration, CMTimeSubtract(available.end, start)) + guard length > .zero else { throw MusicVideoComposerError.noAudioTrack } try audioTrack.insertTimeRange( - CMTimeRange(start: available.start, duration: length), + CMTimeRange(start: start, duration: length), of: sourceTrack, at: .zero ) + + guard fade > 0 else { return nil } + let fadeTime = Self.time(fade) + let parameters = AVMutableAudioMixInputParameters(track: audioTrack) + parameters.setVolumeRamp(fromStartVolume: 0, toEndVolume: 1, timeRange: CMTimeRange(start: .zero, duration: fadeTime)) + parameters.setVolumeRamp( + fromStartVolume: 1, + toEndVolume: 0, + timeRange: CMTimeRange(start: CMTimeSubtract(length, fadeTime), duration: fadeTime) + ) + let mix = AVMutableAudioMix() + mix.inputParameters = [parameters] + return mix } - /// 素材を画面いっぱいに(はみ出す部分は切り落として)敷き詰める変換。向き(回転)も反映する。 - private static func fillTransform(for source: SourceTrack, renderSize: CGSize) -> CGAffineTransform { + /// 素材を画面に収める変換。向き(回転)も反映する。 + /// `.fill` は画面いっぱいに(はみ出す部分は切り落として)敷き詰め、`.fit` は全体が収まる大きさにして中央に置く。 + private static func transform(for source: SourceTrack, renderSize: CGSize, fit: MusicVideoFitMode) -> CGAffineTransform { let rotated = source.naturalSize.applying(source.preferredTransform) let displaySize = CGSize(width: abs(rotated.width), height: abs(rotated.height)) guard displaySize.width > 0, displaySize.height > 0 else { return .identity } - let scale = max(renderSize.width / displaySize.width, renderSize.height / displaySize.height) + let widthScale = renderSize.width / displaySize.width + let heightScale = renderSize.height / displaySize.height + let scale = fit == .fill ? max(widthScale, heightScale) : min(widthScale, heightScale) let scaledSize = CGSize(width: displaySize.width * scale, height: displaySize.height * scale) let translation = CGAffineTransform( translationX: (renderSize.width - scaledSize.width) / 2, @@ -309,6 +594,7 @@ nonisolated struct MusicVideoComposer: Sendable { AVNumberOfChannelsKey: 2 ] ) + output.audioMix = composed.audioMix output.alwaysCopiesSampleData = false guard reader.canAdd(output) else { throw MusicVideoComposerError.cannotCreateExporter } reader.add(output) From 9dba3c3516a179b0acbf9f637ea9b6a1f20c0972 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8E=9F=E3=80=80=E9=A2=AF=E7=99=BB?= Date: Wed, 4 Nov 2026 13:23:25 +0900 Subject: [PATCH 8/9] =?UTF-8?q?feat(musicvideo):=20=E3=83=97=E3=83=AC?= =?UTF-8?q?=E3=83=93=E3=83=A5=E3=83=BC=E6=93=8D=E4=BD=9C=E3=83=BB=E5=85=A8?= =?UTF-8?q?=E7=94=BB=E9=9D=A2=E8=A1=A8=E7=A4=BA=E3=83=BB=E3=83=AA=E3=82=A2?= =?UTF-8?q?=E3=83=AB=E3=82=BF=E3=82=A4=E3=83=A0=E8=AA=BF=E6=95=B4=E3=82=BB?= =?UTF-8?q?=E3=82=AF=E3=82=B7=E3=83=A7=E3=83=B3=E3=82=92=E7=94=BB=E9=9D=A2?= =?UTF-8?q?=E3=81=A8ViewModel=E3=81=AB=E7=B5=B1=E5=90=88?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../ViewModels/MusicVideoViewModel.swift | 421 +++++++++++++++-- .../Views/MusicVideoCutEditorView.swift | 28 +- .../Views/MusicVideoFullScreenPresenter.swift | 66 +++ .../Views/MusicVideoMusicPickerSheet.swift | 53 ++- .../Views/MusicVideoPlayerViews.swift | 439 ++++++++++++++++++ .../Views/MusicVideoSourcePickerSheet.swift | 47 +- .../Views/MusicVideoTuningSections.swift | 322 +++++++++++++ .../MusicVideo/Views/MusicVideoView.swift | 361 ++++++++------ 8 files changed, 1493 insertions(+), 244 deletions(-) create mode 100644 ArkServer/Features/MusicVideo/Views/MusicVideoFullScreenPresenter.swift create mode 100644 ArkServer/Features/MusicVideo/Views/MusicVideoPlayerViews.swift create mode 100644 ArkServer/Features/MusicVideo/Views/MusicVideoTuningSections.swift diff --git a/ArkServer/Features/MusicVideo/ViewModels/MusicVideoViewModel.swift b/ArkServer/Features/MusicVideo/ViewModels/MusicVideoViewModel.swift index 0468e48..829b084 100644 --- a/ArkServer/Features/MusicVideo/ViewModels/MusicVideoViewModel.swift +++ b/ArkServer/Features/MusicVideo/ViewModels/MusicVideoViewModel.swift @@ -20,7 +20,21 @@ struct MusicVideoPoolVideo: Identifiable, Equatable { let name: String } -/// 音楽に合わせた映像(HMV)の作成を進める。 +/// 取り消し・やり直しの1段階。カット割りと、それを作ったときの設定。 +private struct PlanSnapshot { + var plan: CutPlan + var settings: MusicVideoPlanSettings +} + +/// 調整項目を変えたときの、作り直しの範囲。値が大きいほど大がかり。 +private enum TuningEffect: Int { + /// 合成だけをやり直す(カット割りはそのまま)。 + case composition = 0 + /// カット割りを作り直す(素材の解析は使い回す)。 + case plan = 1 +} + +/// 音楽に合わせた映像(ミュージックビデオ)の作成を進める。 /// 曲の解析・素材の解析・カット割り・編集・プレビュー・書き出しの状態をここが持ち、画面を切り替えても保たれる。 @MainActor final class MusicVideoViewModel: ObservableObject { @@ -29,19 +43,68 @@ final class MusicVideoViewModel: ObservableObject { @Published var selectedAlbumIDs: Set = [] { didSet { selectionDidChange() } } @Published var selectedVideoIDs: Set = [] { didSet { selectionDidChange() } } @Published var includeFavorites = false { didSet { selectionDidChange() } } - @Published var cutStyle: MusicVideoCutStyle = .standard { didSet { savePreferences() } } - @Published var renderPreset: MusicVideoRenderPreset = .landscapeFullHD { didSet { savePreferences() } } + // 調整項目。映像ができているときは、変えると少し待ってから(250ms)、自動で反映する。 + @Published var cutStyle: MusicVideoCutStyle = .standard { + didSet { + guard cutStyle != oldValue else { return } + savePreferences() + tuningDidChange(.plan, title: "カットの細かさ") + } + } + @Published var renderPreset: MusicVideoRenderPreset = .landscapeFullHD { + didSet { + guard renderPreset != oldValue else { return } + savePreferences() + tuningDidChange(.composition, title: "画面サイズ") + } + } @Published var exportQuality: MusicVideoExportQuality = .high { didSet { savePreferences() } } + /// カット割りに効く項目(最短・最長のカット長、動きの合わせ方、動画のばらけ具合、切り替えのタイミング)。 + @Published var cutTuning = MusicVideoCutTuning() { + didSet { + guard cutTuning != oldValue else { return } + savePreferences() + tuningDidChange(.plan, title: Self.changedTitle(from: oldValue, to: cutTuning)) + } + } + /// 見た目と音に効く項目(画面の合わせ方、切り替え効果、フェード)。 + @Published var lookTuning = MusicVideoLookTuning() { + didSet { + guard lookTuning != oldValue else { return } + savePreferences() + tuningDidChange(.composition, title: Self.changedTitle(from: oldValue, to: lookTuning)) + } + } + /// 解析に使う素材動画の本数。素材の解析が要るので、変えたあとは「作り直す」で反映する。 + @Published var sourceLimit = MusicVideoSourceLimit.standard { + didSet { + guard sourceLimit != oldValue else { return } + savePreferences() + } + } @Published private(set) var musicFolderURL: URL? @Published private(set) var recentMusicURLs: [URL] = [] /// 選んだ素材のうち、条件(動画・ゴミ箱外・長さ)を満たす動画の本数。ファイルの存在は確認していない。 @Published private(set) var candidateCount = 0 // MARK: 結果 + /// 曲全体の解析結果。 + @Published private(set) var fullAnalysis: MusicAnalysis? + /// いまのカット割りを作った範囲の解析結果。曲の一部だけを使うときは、その範囲に切り出したもの。 @Published private(set) var analysis: MusicAnalysis? + /// 映像にする曲の範囲。nil なら曲の全体。 + @Published private(set) var musicRange: MusicRange? @Published private(set) var plan: CutPlan? + /// いまのカット割りの結果を表す数値(カット数・平均の長さ・使った動画の本数・動きの一致度)。 + @Published private(set) var planStats: MusicVideoPlanStats? + /// 直前に調整項目を変えたときの、結果の違い。「作り直す」や曲の変更で消える。 + @Published private(set) var lastChangeNote: String? @Published private(set) var phase: MusicVideoPhase = .idle @Published private(set) var playbackTime: Double = 0 + /// 映像を再生中か(読み込み待ちも含む)。 + @Published private(set) var isPlaying = false + /// 映像の音を消しているか。 + @Published var isMuted = false { didSet { player.isMuted = isMuted } } @Published var errorMessage: String? @Published var resultMessage: String? /// 実際に使った動画の本数。 @@ -60,10 +123,12 @@ final class MusicVideoViewModel: ObservableObject { @Published private(set) var redoDepth = 0 let player = AVPlayer() + /// 曲を選ぶときの試聴。 + let preview = MusicPreviewPlayer() private weak var dataManager: LibraryViewModel? private var libraryObservation: AnyCancellable? - private let preferencesStore = MusicVideoPreferencesStore() + private let preferencesStore: MusicVideoPreferencesStore private var preferences = MusicVideoPreferences() private var isRestoringPreferences = false @@ -75,11 +140,21 @@ final class MusicVideoViewModel: ObservableObject { private var seed: UInt64 = UInt64.random(in: 0...UInt64.max) private var editCounter: UInt64 = 0 private var composed: MusicVideoComposition? - private var undoStack: [CutPlan] = [] - private var redoStack: [CutPlan] = [] + private var undoStack: [PlanSnapshot] = [] + private var redoStack: [PlanSnapshot] = [] + /// `pool` を作ったときの、素材の本数の上限。 + private var poolSourceLimit = MusicVideoSourceLimit.standard + /// いまのカット割りを作ったときの設定。取り消しで元に戻す設定の基準になる。 + private var appliedSettings: MusicVideoPlanSettings? + /// 取り消し・やり直しで設定を戻している間は、設定の変更を反映の対象にしない。 + private var isRestoringSettings = false + private var pendingEffect: TuningEffect? + private var pendingTitle: String? + private var tuningTask: Task? private var workTask: Task? private var editTask: Task? private var timeObserver: Any? + private var playingObservation: AnyCancellable? private static let undoLimit = 50 @@ -105,6 +180,26 @@ final class MusicVideoViewModel: ObservableObject { } var canGenerate: Bool { generateBlocker == nil && !isWorking } + + /// 映像にする長さ(秒)。曲の一部だけを使うときは、その長さ。 + var targetDuration: Double? { musicRange?.length ?? fullAnalysis?.duration } + + /// いま画面で選んでいる、カット割りに効く設定。 + var currentSettings: MusicVideoPlanSettings { + MusicVideoPlanSettings(cutStyle: cutStyle, cutTuning: cutTuning, musicRange: musicRange) + } + + /// 素材の本数を変えたのに、いまの映像にはまだ反映されていないか。 + /// 選んだ動画が両方の上限以下なら、本数は変わらないので反映の必要はない。 + var sourceLimitNeedsRebuild: Bool { + plan != nil && min(candidateCount, sourceLimit) != min(candidateCount, poolSourceLimit) + } + + /// 曲全体の解析結果を `range` に切り出したもの。nil なら曲の全体。 + private func trimmedAnalysis(for range: MusicRange?) -> MusicAnalysis? { + guard let fullAnalysis else { return nil } + return range.map { fullAnalysis.trimmed(to: $0) } ?? fullAnalysis + } var canExport: Bool { composed != nil && plan != nil && !isWorking && !isApplyingEdit } var canEdit: Bool { plan != nil && !isWorking && !isApplyingEdit } var canUndo: Bool { canEdit && undoDepth > 0 } @@ -120,13 +215,20 @@ final class MusicVideoViewModel: ObservableObject { recentMusicURLs.first { $0 != musicURL } } - init() { + /// - Parameter preferencesStore: 設定の保存先。テストでは、実際の設定を書き換えないよう別の保存先を渡す。 + init(preferencesStore: MusicVideoPreferencesStore = MusicVideoPreferencesStore()) { + self.preferencesStore = preferencesStore let interval = CMTime(seconds: 0.05, preferredTimescale: 600) timeObserver = player.addPeriodicTimeObserver(forInterval: interval, queue: .main) { [weak self] time in MainActor.assumeIsolated { self?.playbackTime = time.seconds.isFinite ? time.seconds : 0 } } + playingObservation = player.publisher(for: \.timeControlStatus) + .receive(on: DispatchQueue.main) + .sink { [weak self] status in + MainActor.assumeIsolated { self?.isPlaying = status != .paused } + } } deinit { @@ -162,6 +264,9 @@ final class MusicVideoViewModel: ObservableObject { cutStyle = stored.cutStyle renderPreset = stored.renderPreset exportQuality = stored.exportQuality + cutTuning = stored.cutTuning + lookTuning = stored.lookTuning + sourceLimit = stored.sourceLimit selectedAlbumIDs = Set(stored.selectedAlbumIDs) selectedVideoIDs = Set(stored.selectedVideoIDs) includeFavorites = stored.includeFavorites @@ -176,6 +281,9 @@ final class MusicVideoViewModel: ObservableObject { preferences.cutStyle = cutStyle preferences.renderPreset = renderPreset preferences.exportQuality = exportQuality + preferences.cutTuning = cutTuning + preferences.lookTuning = lookTuning + preferences.sourceLimit = sourceLimit preferences.selectedAlbumIDs = Array(selectedAlbumIDs) preferences.selectedVideoIDs = Array(selectedVideoIDs) preferences.includeFavorites = includeFavorites @@ -223,10 +331,13 @@ final class MusicVideoViewModel: ObservableObject { // MARK: - 音楽 func chooseMusic(_ url: URL) { + preview.stop() cancelWork() clearResult() musicURL = url analysis = nil + fullAnalysis = nil + musicRange = nil preferences.recordRecentMusic(url.path) preferencesStore.save(preferences) refreshRecentMusic() @@ -235,6 +346,7 @@ final class MusicVideoViewModel: ObservableObject { do { let result = try await BeatAnalyzer().analyze(url: url) guard let self, !Task.isCancelled else { return } + self.fullAnalysis = result self.analysis = result self.phase = .idle } catch is CancellationError { @@ -252,7 +364,14 @@ final class MusicVideoViewModel: ObservableObject { /// 選んだ素材から映像を作る。素材の組み合わせが前回と同じなら、解析済みの動きを使い回す。 func generate(dataManager: LibraryViewModel, newSeed: Bool = true) { - guard let musicURL, let analysis, !isWorking else { return } + guard let musicURL, let fullAnalysis, !isWorking else { return } + // 反映待ちの調整は捨てる(これから、いまの設定でまとめて作る)。 + tuningTask?.cancel() + pendingEffect = nil + pendingTitle = nil + // 曲の一部だけを使うときは、その範囲に切り出した解析結果で作る。 + let analysis = trimmedAnalysis(for: musicRange) ?? fullAnalysis + preview.stop() let resolved = resolveSources(dataManager: dataManager) let sources = resolved.sources guard !sources.isEmpty else { @@ -265,15 +384,20 @@ final class MusicVideoViewModel: ObservableObject { let seed = self.seed let style = cutStyle + let tuning = cutTuning + let look = lookTuning + let settings = currentSettings + let sourceLimit = self.sourceLimit let render = renderPreset.settings let sourceIDs = Set(sources.map(\.videoID)) - let reusablePool = (sourceIDs == poolSourceIDs && !pool.isEmpty) ? pool : nil + // 素材の組み合わせも、素材の本数の上限も前回と同じなら、解析済みの動きを使い回す。 + let reusablePool = (sourceIDs == poolSourceIDs && sourceLimit == poolSourceLimit && !pool.isEmpty) ? pool : nil let cacheDirectory = dataManager.appRootURL.appendingPathComponent("MusicVideoCache") let items = resolved.items // 二重に開始されないよう、タスクを作る前に作業中の状態にしておく。 phase = reusablePool == nil - ? .analyzingSources(completed: 0, total: min(sources.count, ClipPoolBuilder().maxVideos)) + ? .analyzingSources(completed: 0, total: min(sources.count, sourceLimit)) : .composing estimatedRemaining = nil let startedAt = Date() @@ -285,6 +409,7 @@ final class MusicVideoViewModel: ObservableObject { motion = reusablePool } else { var builder = ClipPoolBuilder() + builder.maxVideos = sourceLimit builder.cacheDirectory = cacheDirectory motion = try await builder.build(sources: sources, seed: seed) { completed, total in await MainActor.run { @@ -297,21 +422,27 @@ final class MusicVideoViewModel: ObservableObject { self?.phase = .composing self?.estimatedRemaining = nil - var planner = CutPlanner() - planner.style = style + let planner = CutPlanner(style: style, tuning: tuning) let cutPlan = try planner.plan(analysis: analysis, pool: motion, seed: seed) let urls = Dictionary(uniqueKeysWithValues: sources.map { ($0.videoID, $0.url) }) let result = try await MusicVideoComposer().makeComposition( plan: cutPlan, sourceURLs: urls, audioURL: musicURL, - render: render + render: render, + look: look, + audioStart: settings.musicRange?.start ?? 0 ) try Task.checkCancellation() guard let self else { return } self.pool = motion self.poolSourceIDs = sourceIDs + self.poolSourceLimit = sourceLimit + self.analysis = analysis + self.appliedSettings = settings + self.lastChangeNote = nil + self.planStats = MusicVideoPlanStats(plan: cutPlan, pool: motion, analysis: analysis) self.sourceURLs = urls self.sourceItems = items self.undoStack = [] @@ -421,16 +552,120 @@ final class MusicVideoViewModel: ObservableObject { func undo() { guard canUndo, let current = plan, let previous = undoStack.popLast() else { return } - redoStack.append(current) - syncHistoryDepth() - recompose(previous) + redoStack.append(snapshot(of: current)) + restore(previous) } func redo() { guard canRedo, let current = plan, let next = redoStack.popLast() else { return } - undoStack.append(current) + undoStack.append(snapshot(of: current)) + restore(next) + } + + private func snapshot(of plan: CutPlan) -> PlanSnapshot { + PlanSnapshot(plan: plan, settings: appliedSettings ?? currentSettings) + } + + /// カット割りと、それを作ったときの設定を、そろえて元へ戻す。 + private func restore(_ snapshot: PlanSnapshot) { + tuningTask?.cancel() + pendingEffect = nil + pendingTitle = nil + applySettings(snapshot.settings) + appliedSettings = snapshot.settings + lastChangeNote = nil syncHistoryDepth() - recompose(next) + recompose(snapshot.plan, analysis: trimmedAnalysis(for: snapshot.settings.musicRange)) + } + + /// 設定だけを戻す。設定の変更として反映し直さない。 + private func applySettings(_ settings: MusicVideoPlanSettings) { + isRestoringSettings = true + cutStyle = settings.cutStyle + cutTuning = settings.cutTuning + musicRange = settings.musicRange + isRestoringSettings = false + savePreferences() + } + + // MARK: - 調整項目の反映 + + /// 映像の曲の範囲を決める。曲の全体と同じなら範囲なしになる。開始は、曲の拍にそろえる。 + func setMusicRange(start: Double, end: Double) { + guard let fullAnalysis, !isWorking else { return } + let snappedStart = start <= 0 ? 0 : fullAnalysis.nearestBeat(to: start) + let newRange = MusicRange.clamped(start: snappedStart, end: end, songDuration: fullAnalysis.duration) + guard newRange != musicRange else { return } + musicRange = newRange + tuningDidChange(.plan, title: "曲の範囲") + } + + /// 調整項目が変わった。映像ができているときだけ、少し待ってから反映する(つまみを動かしている間の連続した変更をまとめる)。 + private func tuningDidChange(_ effect: TuningEffect, title: String) { + guard !isRestoringPreferences, !isRestoringSettings, plan != nil else { return } + if (pendingEffect?.rawValue ?? -1) < effect.rawValue { pendingEffect = effect } + pendingTitle = title + tuningTask?.cancel() + tuningTask = Task { [weak self] in + try? await Task.sleep(for: .milliseconds(250)) + guard !Task.isCancelled else { return } + self?.applyPendingTuning() + } + } + + /// 反映待ちの調整を適用する。乱数の種は変えないので、変えた項目だけの違いが出る。 + private func applyPendingTuning() { + guard let effect = pendingEffect, let current = plan, !isWorking else { return } + let title = pendingTitle ?? "設定" + pendingEffect = nil + pendingTitle = nil + + switch effect { + case .composition: + lastChangeNote = "「\(title)」を変えました.カット割りはそのままで、見た目と音だけが変わります." + recompose(current) + + case .plan: + let settings = currentSettings + guard let newAnalysis = trimmedAnalysis(for: settings.musicRange) else { return } + let activePool = pool.filter { !excludedVideoIDs.contains($0.videoID) } + do { + let planner = CutPlanner(style: settings.cutStyle, tuning: settings.cutTuning) + let newPlan = try planner.plan(analysis: newAnalysis, pool: activePool, seed: seed) + + let before = planStats ?? MusicVideoPlanStats(plan: current, pool: activePool, analysis: analysis) + let after = MusicVideoPlanStats(plan: newPlan, pool: activePool, analysis: newAnalysis) + lastChangeNote = MusicVideoChangeSummary(title: title, before: before, after: after).text + + // 設定を変えたカット割りも、取り消しで元の設定ごと戻せるようにする。 + undoStack.append(snapshot(of: current)) + if undoStack.count > Self.undoLimit { undoStack.removeFirst(undoStack.count - Self.undoLimit) } + redoStack = [] + appliedSettings = settings + syncHistoryDepth() + selectedCutIndex = nil + recompose(newPlan, analysis: newAnalysis) + } catch { + // 作れなかったときは、設定を直前の状態へ戻す。 + if let appliedSettings { applySettings(appliedSettings) } + lastChangeNote = nil + errorMessage = error.localizedDescription + } + } + } + + private static func changedTitle(from old: MusicVideoCutTuning, to new: MusicVideoCutTuning) -> String { + if old.minimumCutDuration != new.minimumCutDuration { return "最短のカット長" } + if old.maximumCutDuration != new.maximumCutDuration { return "最長のカット長" } + if old.motionMatching != new.motionMatching { return "動きの合わせ方" } + if old.variety != new.variety { return "動画のばらけ具合" } + return "切り替えのタイミング" + } + + private static func changedTitle(from old: MusicVideoLookTuning, to new: MusicVideoLookTuning) -> String { + if old.fitMode != new.fitMode { return "画面の合わせ方" } + if old.transition != new.transition { return "切り替え効果" } + return "フェード" } private func syncHistoryDepth() { @@ -445,11 +680,10 @@ final class MusicVideoViewModel: ObservableObject { editCounter += 1 let editSeed = seed &+ editCounter &* 0xD1B5_4A32_D192_ED03 do { - var planner = CutPlanner() - planner.style = cutStyle + let planner = CutPlanner(style: cutStyle, tuning: cutTuning) let edited = try transform(planner, current, analysis, pool, editSeed, excludedVideoIDs) guard edited != current else { return } - undoStack.append(current) + undoStack.append(snapshot(of: current)) if undoStack.count > Self.undoLimit { undoStack.removeFirst(undoStack.count - Self.undoLimit) } redoStack = [] syncHistoryDepth() @@ -460,21 +694,26 @@ final class MusicVideoViewModel: ObservableObject { } /// カット割りを入れ替えて合成し直し、再生位置と再生状態を保ったままプレイヤーを差し替える。 - private func recompose(_ newPlan: CutPlan) { + /// - Parameter newAnalysis: カット割りを作った範囲の解析結果。曲の範囲を変えたときだけ渡す。 + private func recompose(_ newPlan: CutPlan, analysis newAnalysis: MusicAnalysis? = nil) { guard let musicURL else { return } let render = renderPreset.settings + let look = lookTuning + let audioStart = appliedSettings?.musicRange?.start ?? 0 let urls = sourceURLs isApplyingEdit = true editTask?.cancel() editTask = Task { [weak self] in do { let result = try await MusicVideoComposer().makeComposition( - plan: newPlan, sourceURLs: urls, audioURL: musicURL, render: render + plan: newPlan, sourceURLs: urls, audioURL: musicURL, render: render, look: look, audioStart: audioStart ) guard let self, !Task.isCancelled else { return } let time = self.player.currentTime() let wasPlaying = self.player.timeControlStatus != .paused + if let newAnalysis { self.analysis = newAnalysis } self.plan = newPlan + self.planStats = MusicVideoPlanStats(plan: newPlan, pool: self.pool, analysis: self.analysis) self.composed = result self.usedVideoCount = Set(newPlan.cuts.map(\.videoID)).count self.player.replaceCurrentItem(with: result.makePlayerItem()) @@ -492,17 +731,13 @@ final class MusicVideoViewModel: ObservableObject { // MARK: - 書き出し - /// 書き出して「HMV」アルバムに追加する。 - func exportToLibrary(dataManager: LibraryViewModel) { + /// 書き出して、利用者が選んだアルバムに追加する。追加先は呼び出しのたびに利用者が決める。 + /// 新しいアルバムは,書き出しが終わって追加する直前に作る(途中で中止しても空のアルバムが残らない)。 + func exportToLibrary(dataManager: LibraryViewModel, destination: MusicVideoExportDestination) { guard let musicTitle else { return } let fileName = Self.outputFileName(musicTitle: musicTitle) export { url in - guard let albumID = self.hmvAlbumID(in: dataManager) else { - throw MusicVideoComposerError.exportFailed("「HMV」アルバムを作成できませんでした.") - } - let added = await dataManager.importMedia(from: url, to: albumID, customFilename: fileName) - guard added else { throw MusicVideoComposerError.exportFailed("ライブラリへ追加できませんでした.") } - return "「\(Self.hmvAlbumName)」アルバムに \(fileName) を追加しました." + try await Self.addToLibrary(url, fileName: fileName, destination: destination, dataManager: dataManager) } } @@ -521,10 +756,11 @@ final class MusicVideoViewModel: ObservableObject { private func export(finish: @escaping @MainActor (URL) async throws -> String) { guard let composed, canExport else { return } + preview.stop() player.pause() phase = .exporting(progress: 0) let temporaryURL = FileManager.default.temporaryDirectory - .appendingPathComponent("hmv-\(UUID().uuidString).mp4") + .appendingPathComponent("musicvideo-\(UUID().uuidString).mp4") let quality = exportQuality workTask = Task { [weak self] in @@ -546,14 +782,43 @@ final class MusicVideoViewModel: ObservableObject { } } - private func hmvAlbumID(in dataManager: LibraryViewModel) -> UUID? { - if let existing = dataManager.albums.first(where: { $0.name == Self.hmvAlbumName && $0.type == .video }) { - return existing.id + /// 書き出した動画を追加先のアルバムへ入れ,完了メッセージを返す。 + private static func addToLibrary( + _ url: URL, + fileName: String, + destination: MusicVideoExportDestination, + dataManager: LibraryViewModel + ) async throws -> String { + let albumID: UUID + var createdAlbum = false + switch destination { + case .existing(let id): + guard dataManager.albums.contains(where: { $0.id == id }) else { + throw MusicVideoComposerError.exportFailed("選んだアルバムが見つかりません.ライブラリで削除された可能性があります.") + } + albumID = id + case .new(let name): + switch MusicVideoExportAlbumName.validate(name, existingNames: dataManager.albums.map(\.name)) { + case .failure(let problem): + throw MusicVideoComposerError.exportFailed(problem.message) + case .success(let validName): + guard let id = dataManager.createAlbum(name: validName, type: .video) else { + throw MusicVideoComposerError.exportFailed("アルバムを作成できませんでした.") + } + albumID = id + createdAlbum = true + } } - return dataManager.createAlbum(name: Self.hmvAlbumName, type: .video) - } - static let hmvAlbumName = "HMV" + let added = await dataManager.importMedia(from: url, to: albumID, customFilename: fileName) + guard added else { + // 追加に失敗したときは,このために作ったアルバムを残さない。 + if createdAlbum { dataManager.deleteAlbum(albumID: albumID) } + throw MusicVideoComposerError.exportFailed("ライブラリへ追加できませんでした.") + } + let title = dataManager.albums.first { $0.id == albumID }?.displayTitle ?? "選んだ" + return "「\(title)」アルバムに \(fileName) を追加しました." + } static func outputFileName(musicTitle: String, date: Date = Date()) -> String { let formatter = DateFormatter() @@ -562,7 +827,7 @@ final class MusicVideoViewModel: ObservableObject { // ファイル名に使えない文字を取り除く。 let invalid = CharacterSet(charactersIn: "/:\\?%*|\"<>").union(.controlCharacters) let safeTitle = musicTitle.components(separatedBy: invalid).joined(separator: "_") - return "HMV_\(safeTitle)_\(formatter.string(from: date)).mp4" + return "MusicVideo_\(safeTitle)_\(formatter.string(from: date)).mp4" } // MARK: - 素材の解決 @@ -603,6 +868,78 @@ final class MusicVideoViewModel: ObservableObject { player.pause() } + // MARK: 再生の操作(小さなプレビューと全画面で共通) + + /// 完成映像の長さ(秒)。映像がまだ無ければ 0。 + var playbackDuration: Double { plan?.duration ?? 0 } + + /// いま再生している位置にあるカットの番号(1から)。 + var currentCutNumber: Int? { + plan?.cutIndex(at: playbackTime).map { $0 + 1 } + } + + /// 再生/一時停止。終わりまで再生していたら、先頭から再生し直す。曲の試聴が鳴っていれば止める。 + func togglePlayback() { + guard plan != nil else { return } + if player.timeControlStatus != .paused { + player.pause() + return + } + preview.stop() + if playbackTime >= playbackDuration - 0.05 { seek(to: 0) } + player.play() + } + + /// 再生位置を `seconds` 秒だけ動かす(負なら戻る)。映像の範囲に収める。 + func skip(by seconds: Double) { + guard plan != nil else { return } + seek(to: min(max(0, playbackTime + seconds), max(0, playbackDuration - 0.05))) + } + + /// `direction` が正なら次のカットの頭へ、負なら前へ移る。 + /// カットの途中(頭から1秒より後)で戻るときは、まずそのカットの頭へ戻る。 + func skipToCut(_ direction: Int) { + guard let plan, !plan.cuts.isEmpty else { return } + // 再生位置は1/600秒に丸められるので、カットの頭に移ったあとでも、頭よりごくわずかに手前になることがある。 + // 手前のカットと取り違えないよう、判定には少し余裕(20ms。最短のカットより十分短い)を持たせる。 + let current = plan.cutIndex(at: playbackTime + 0.02) ?? 0 + let start = plan.cuts[current].timelineStart + let target: Int + if direction > 0 { + target = min(current + 1, plan.cuts.count - 1) + } else if playbackTime - start > 1.0 { + target = current + } else { + target = max(current - 1, 0) + } + seek(to: plan.cuts[target].timelineStart) + } + + /// つまみを動かしている間の移動。コマ単位までは合わせず、軽く動かす(離したときに `seek(to:)` で合わせる)。 + func scrub(to seconds: Double) { + guard plan != nil else { return } + let target = min(max(0, seconds), max(0, playbackDuration - 0.05)) + let tolerance = CMTime(seconds: 0.25, preferredTimescale: 600) + player.seek( + to: CMTime(seconds: target, preferredTimescale: 600), + toleranceBefore: tolerance, + toleranceAfter: tolerance + ) + } + + /// 曲の試聴を始める/止める。映像のプレビューが鳴っていれば止める。 + /// いま選んでいる曲なら、解析した盛り上がりから聞く区間を決める。 + func togglePreview(_ url: URL) { + pausePlayback() + preview.toggle(url, analysis: url == musicURL ? analysis : nil) + } + + /// 画面を離れるときなど、映像のプレビューも曲の試聴も止める。 + func stopAllPlayback() { + player.pause() + preview.stop() + } + func cancelWork() { workTask?.cancel() workTask = nil @@ -612,6 +949,12 @@ final class MusicVideoViewModel: ObservableObject { private func clearResult() { editTask?.cancel() + tuningTask?.cancel() + pendingEffect = nil + pendingTitle = nil + planStats = nil + lastChangeNote = nil + appliedSettings = nil isApplyingEdit = false player.pause() player.replaceCurrentItem(with: nil) diff --git a/ArkServer/Features/MusicVideo/Views/MusicVideoCutEditorView.swift b/ArkServer/Features/MusicVideo/Views/MusicVideoCutEditorView.swift index 3a4827c..d3aa6fb 100644 --- a/ArkServer/Features/MusicVideo/Views/MusicVideoCutEditorView.swift +++ b/ArkServer/Features/MusicVideo/Views/MusicVideoCutEditorView.swift @@ -8,40 +8,40 @@ struct MusicVideoCutEditorView: View { @ObservedObject var dataManager: LibraryViewModel var body: some View { - MVSection(title: "カットの編集") { - MVRowGroup { + SettingsSection(title: "カットの編集") { + SettingsGroup { if let cut = viewModel.selectedCut, let plan = viewModel.plan, let index = viewModel.selectedCutIndex { - MVRow( + SettingsRow( title: viewModel.sourceItem(for: cut.videoID)?.originalFilename ?? "(不明な動画)", detail: "カット \(index + 1) / \(plan.cuts.count)・\(fineTime(cut.timelineStart)) から \(String(format: "%.2f", cut.duration)) 秒・\(cut.intensity.displayName)\n元動画の \(fineTime(cut.sourceStart)) 付近を使用", leading: { thumbnail(for: cut) }, control: { EmptyView() } ) - MVRow(title: "このカット", detail: "同じ長さのまま,別の映像に差し替えます.") { + SettingsRow(title: "このカット", detail: "同じ長さのまま,別の映像に差し替えます.") { HStack(spacing: 8) { Button("差し替える") { viewModel.replaceSelectedCut() } - .buttonStyle(.mvSmall) + .buttonStyle(.quiet) .accessibilityIdentifier("musicvideo.replaceCut") moreMenu } .disabled(!viewModel.canEdit) } } else { - MVRow( + SettingsRow( title: "カットを選んでください", detail: "上のタイムラインをクリックすると,その位置のカットを選べます.選んだカットだけを差し替えられます." ) { EmptyView() } } - MVRow(title: "移動と履歴") { + SettingsRow(title: "移動と履歴") { HStack(spacing: 8) { Button { viewModel.selectAdjacentCut(by: -1) } label: { Image(systemName: "chevron.left") } - .buttonStyle(.mvSmall) + .buttonStyle(.quiet) .help("前のカット") .accessibilityLabel("前のカット") Button { @@ -49,7 +49,7 @@ struct MusicVideoCutEditorView: View { } label: { Image(systemName: "chevron.right") } - .buttonStyle(.mvSmall) + .buttonStyle(.quiet) .help("次のカット") .accessibilityLabel("次のカット") @@ -58,22 +58,22 @@ struct MusicVideoCutEditorView: View { } Button("元に戻す") { viewModel.undo() } - .buttonStyle(.mvSmall) + .buttonStyle(.quiet) .disabled(!viewModel.canUndo) .accessibilityIdentifier("musicvideo.undo") Button("やり直す") { viewModel.redo() } - .buttonStyle(.mvSmall) + .buttonStyle(.quiet) .disabled(!viewModel.canRedo) } .disabled(viewModel.plan == nil) } if !viewModel.excludedVideoIDs.isEmpty { - MVRow( + SettingsRow( title: "除外した動画 \(viewModel.excludedVideoIDs.count)本", detail: "次に映像を作るときも使いません." ) { Button("除外を解除") { viewModel.clearExclusions() } - .buttonStyle(.mvSmall) + .buttonStyle(.quiet) } } } @@ -94,7 +94,7 @@ struct MusicVideoCutEditorView: View { Text("その他") } .menuStyle(.button) - .buttonStyle(.mvSmall) + .buttonStyle(.quiet) .menuIndicator(.visible) .fixedSize() } diff --git a/ArkServer/Features/MusicVideo/Views/MusicVideoFullScreenPresenter.swift b/ArkServer/Features/MusicVideo/Views/MusicVideoFullScreenPresenter.swift new file mode 100644 index 0000000..60e33c2 --- /dev/null +++ b/ArkServer/Features/MusicVideo/Views/MusicVideoFullScreenPresenter.swift @@ -0,0 +1,66 @@ +// ArkServer/Features/MusicVideo/Views/MusicVideoFullScreenPresenter.swift + +import AppKit +import SwiftUI + +/// プレビューを、macOS 標準の全画面ウィンドウで開く。 +/// 全画面をやめる(Esc・F・ダブルクリック・操作部のボタン)と、ウィンドウごと閉じて、元の画面へ戻る。 +@MainActor +final class MusicVideoFullScreenPresenter: NSObject, NSWindowDelegate { + private var window: NSWindow? + + var isPresented: Bool { window != nil } + + func present(viewModel: MusicVideoViewModel) { + // 映像ができていないときや、すでに開いているときは、何もしない(開いていれば前面に出す)。 + guard viewModel.plan != nil else { return } + if let window { + window.makeKeyAndOrderFront(nil) + 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], + backing: .buffered, + defer: false + ) + window.title = "プレビュー" + window.titleVisibility = .hidden + window.titlebarAppearsTransparent = true + window.isReleasedWhenClosed = false + window.backgroundColor = .black + window.collectionBehavior = [.fullScreenPrimary] + 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() + } + self.window = window + + window.makeKeyAndOrderFront(nil) + window.toggleFullScreen(nil) + } + + func close() { + window?.close() + } + + // MARK: NSWindowDelegate + + func windowWillClose(_ notification: Notification) { + window = nil + } + + /// 全画面をやめたら、通常サイズのウィンドウは残さず閉じる。 + func windowDidExitFullScreen(_ notification: Notification) { + close() + } +} diff --git a/ArkServer/Features/MusicVideo/Views/MusicVideoMusicPickerSheet.swift b/ArkServer/Features/MusicVideo/Views/MusicVideoMusicPickerSheet.swift index 452545c..b5a0e79 100644 --- a/ArkServer/Features/MusicVideo/Views/MusicVideoMusicPickerSheet.swift +++ b/ArkServer/Features/MusicVideo/Views/MusicVideoMusicPickerSheet.swift @@ -7,8 +7,15 @@ import UniformTypeIdentifiers /// 曲を置いてあるフォルダから、曲を探して選ぶシート。フォルダは一度選べば覚える。 struct MusicVideoMusicPickerSheet: View { @ObservedObject var viewModel: MusicVideoViewModel + /// 試聴の状態。画面の更新を受けるため、ViewModel の中のものをここでも監視する。 + @ObservedObject private var preview: MusicPreviewPlayer @Environment(\.dismiss) private var dismiss + init(viewModel: MusicVideoViewModel) { + self.viewModel = viewModel + _preview = ObservedObject(wrappedValue: viewModel.preview) + } + struct MusicFile: Identifiable, Hashable, Sendable { let url: URL let size: Int64 @@ -71,6 +78,11 @@ struct MusicVideoMusicPickerSheet: View { Text(footerText) .font(.appCaption) .foregroundStyle(NeomorphicTheme.muted) + if let message = preview.failureMessage { + Label(message, systemImage: "exclamationmark.triangle.fill") + .font(.appCaption) + .foregroundStyle(NeomorphicTheme.caution) + } Spacer() Button("閉じる") { dismiss() } .keyboardShortcut(.cancelAction) @@ -80,6 +92,8 @@ struct MusicVideoMusicPickerSheet: View { .frame(minWidth: 640, idealWidth: 700, minHeight: 520, idealHeight: 620) .appSheet() .task(id: viewModel.musicFolderURL) { await load() } + // シートを閉じたら、試聴の音も止める。 + .onDisappear { viewModel.preview.stop() } } @ViewBuilder @@ -96,27 +110,28 @@ struct MusicVideoMusicPickerSheet: View { placeholder(icon: "music.note", message: files.isEmpty ? "このフォルダに曲が見つかりませんでした" : "条件に合う曲がありません") } else { List(visibleFiles) { file in - Button { - viewModel.chooseMusic(file.url) - dismiss() - } label: { - HStack(spacing: 10) { - Image(systemName: "music.note") - .foregroundStyle(NeomorphicTheme.muted) - .frame(width: 18) - Text(file.title) - .font(.appBody) - .lineLimit(1) - .truncationMode(.middle) - Spacer(minLength: 8) - Text(ByteCountFormatter.string(fromByteCount: file.size, countStyle: .file)) - .font(.appMicro.monospacedDigit()) - .foregroundStyle(NeomorphicTheme.muted) + HStack(spacing: 10) { + // 左の再生ボタンで試聴、曲名の側を押すとその曲を使う。 + MusicPreviewButton(preview: preview, url: file.url) { viewModel.togglePreview(file.url) } + Button { + viewModel.chooseMusic(file.url) + dismiss() + } label: { + HStack(spacing: 10) { + Text(file.title) + .font(.appBody) + .lineLimit(1) + .truncationMode(.middle) + Spacer(minLength: 8) + Text(ByteCountFormatter.string(fromByteCount: file.size, countStyle: .file)) + .font(.appMicro.monospacedDigit()) + .foregroundStyle(NeomorphicTheme.muted) + } + .contentShape(Rectangle()) } - .contentShape(Rectangle()) + .buttonStyle(.plain) + .accessibilityLabel("\(file.title)を使う") } - .buttonStyle(.plain) - .accessibilityLabel(file.title) } .listStyle(.plain) } diff --git a/ArkServer/Features/MusicVideo/Views/MusicVideoPlayerViews.swift b/ArkServer/Features/MusicVideo/Views/MusicVideoPlayerViews.swift new file mode 100644 index 0000000..645552a --- /dev/null +++ b/ArkServer/Features/MusicVideo/Views/MusicVideoPlayerViews.swift @@ -0,0 +1,439 @@ +// ArkServer/Features/MusicVideo/Views/MusicVideoPlayerViews.swift + +import AppKit +import AVKit +import SwiftUI + +// プレビューの映像と、再生の操作部。小さなプレビュー(MusicVideoPlayerPane)と全画面(MusicVideoFullScreenView)で、 +// 同じ操作部(MusicVideoPlayerControls)を使う。映像の上に重ねるので、色は背景のテーマに依らず白と黒にする。 + +// MARK: - 映像の表示 + +/// クリックとダブルクリックを、AppKit の `clickCount` で受ける `AVPlayerView`。 +/// (SwiftUI のダブルタップは、1回タップの操作と一緒に付けると検知されないことがあるため) +/// 上に重ねた SwiftUI の操作部(ボタンなど)は、SwiftUI 側が先に受けるので、そのまま押せる。 +private final class ClickableAVPlayerView: AVPlayerView { + var onClick: (() -> Void)? + var onDoubleClick: (() -> Void)? + /// 下の端から、この高さまでは、クリックを受けずに通す(上に重ねた操作部のボタンが押せるように)。 + var passThroughBottom: CGFloat = 0 + + override func mouseDown(with event: NSEvent) { + if event.clickCount >= 2 { + onDoubleClick?() + } else { + onClick?() + } + } + + /// 表示面の中のクリックは、AVPlayerView の内部の部品ではなく、このビューが受ける。 + /// ただし、操作部が重なっている下の帯は受けずに通し、SwiftUI のボタンに任せる。 + override func hitTest(_ point: NSPoint) -> NSView? { + let local = convert(point, from: superview) + guard bounds.contains(local) else { return nil } + let distanceFromBottom = isFlipped ? bounds.height - local.y : local.y + return distanceFromBottom < passThroughBottom ? nil : self + } + + /// ウィンドウが前面でなくても、最初のクリックをそのまま操作として受ける。 + override func acceptsFirstMouse(for event: NSEvent?) -> Bool { true } + + /// キーは SwiftUI のショートカットで受ける(AVPlayerView 標準のキー操作は使わない)。 + override var acceptsFirstResponder: Bool { false } +} + +/// 操作部を持たない、映像だけの表示面。操作は自前の操作部で行う(AVKit 標準の操作部にはスキップなどが無いため)。 +/// - Parameters: +/// - onClick: 映像をクリックしたとき。 +/// - onDoubleClick: ダブルクリックしたとき。1回目のクリックで `onClick` も呼ばれている。 +struct MusicVideoPlayerSurface: NSViewRepresentable { + let player: AVPlayer + /// 下の端から、この高さまでは、操作部が重なっているのでクリックを通す。操作部が隠れているときは 0。 + var passThroughBottom: CGFloat = 0 + var onClick: () -> Void = {} + var onDoubleClick: () -> Void = {} + + func makeNSView(context: Context) -> AVPlayerView { + let view = ClickableAVPlayerView() + view.controlsStyle = .none + view.videoGravity = .resizeAspect + view.showsFullScreenToggleButton = false + view.player = player + view.onClick = onClick + view.onDoubleClick = onDoubleClick + view.passThroughBottom = passThroughBottom + return view + } + + func updateNSView(_ view: AVPlayerView, context: Context) { + if view.player !== player { view.player = player } + guard let view = view as? ClickableAVPlayerView else { return } + view.onClick = onClick + view.onDoubleClick = onDoubleClick + view.passThroughBottom = passThroughBottom + } +} + +// MARK: - 小さなプレビュー + +/// 映像と、その下に重ねる操作部。一時停止中かマウスを乗せたときだけ操作部を出す。 +/// クリックで再生/一時停止、ダブルクリックで全画面。 +struct MusicVideoPlayerPane: View { + @ObservedObject var viewModel: MusicVideoViewModel + let onFullScreen: () -> Void + @State private var isHovering = false + /// 操作部の高さ(操作部が出ているあいだ、表示面はその帯のクリックを通す)。 + @State private var controlsHeight: CGFloat = 0 + + private var showsControls: Bool { isHovering || !viewModel.isPlaying } + + var body: some View { + ZStack(alignment: .bottom) { + MusicVideoPlayerSurface( + player: viewModel.player, + passThroughBottom: showsControls ? controlsHeight : 0, + onClick: { viewModel.togglePlayback() }, + onDoubleClick: { + // 1回目のクリックで切り替えた再生/一時停止を戻してから、全画面にする。 + viewModel.togglePlayback() + onFullScreen() + } + ) + if showsControls { + MusicVideoPlayerControls(viewModel: viewModel, style: .compact, isFullScreen: false, onToggleFullScreen: onFullScreen) + .onGeometryChange(for: CGFloat.self) { $0.size.height } action: { controlsHeight = $0 } + .transition(.opacity) + } + } + .onHover { isHovering = $0 } + .animation(.easeInOut(duration: 0.15), value: showsControls) + } +} + +// MARK: - 操作部 + +enum MusicVideoPlayerControlsStyle { + /// 小さなプレビュー用。幅が狭くても収まるよう、段を分ける。 + case compact + /// 全画面用。1段に並べる。 + case full +} + +/// シークバーと、再生・スキップ・ミュート・全画面の操作。 +struct MusicVideoPlayerControls: View { + @ObservedObject var viewModel: MusicVideoViewModel + let style: MusicVideoPlayerControlsStyle + let isFullScreen: Bool + let onToggleFullScreen: () -> Void + + private var isFull: Bool { style == .full } + + var body: some View { + VStack(spacing: isFull ? 12 : 6) { + MusicVideoSeekBar( + duration: viewModel.playbackDuration, + time: viewModel.playbackTime, + cutStarts: viewModel.plan?.cuts.map(\.timelineStart) ?? [], + onScrub: { viewModel.scrub(to: $0) }, + onCommit: { viewModel.seek(to: $0) } + ) + if isFull { + fullRow + } else { + compactRows + } + } + .padding(.horizontal, isFull ? 28 : 12) + .padding(.top, isFull ? 44 : 30) + .padding(.bottom, isFull ? 24 : 10) + .background( + LinearGradient(colors: [.clear, .black.opacity(0.8)], startPoint: .top, endPoint: .bottom) + ) + .foregroundStyle(.white) + } + + // MARK: 並べ方 + + private var compactRows: some View { + VStack(spacing: 4) { + HStack(spacing: 4) { + timeLabel + Spacer(minLength: 4) + muteButton(size: 13) + fullScreenButton(size: 13) + } + transport(buttonSize: 15, playSize: 22, spacing: 8) + } + } + + private var fullRow: some View { + HStack(spacing: 18) { + timeLabel + .frame(minWidth: 120, alignment: .leading) + Spacer(minLength: 8) + transport(buttonSize: 22, playSize: 34, spacing: 22) + Spacer(minLength: 8) + cutLabel + .frame(minWidth: 120, alignment: .trailing) + muteButton(size: 18) + fullScreenButton(size: 18) + } + } + + private func transport(buttonSize: CGFloat, playSize: CGFloat, spacing: CGFloat) -> some View { + HStack(spacing: spacing) { + iconButton("backward.end.fill", label: "前のカット(,)", size: buttonSize, id: "musicvideo.player.previousCut") { + viewModel.skipToCut(-1) + } + iconButton("gobackward.10", label: "10秒戻る(J)", size: buttonSize, id: "musicvideo.player.back10") { + viewModel.skip(by: -10) + } + iconButton( + viewModel.isPlaying ? "pause.fill" : "play.fill", + label: viewModel.isPlaying ? "一時停止(スペース)" : "再生(スペース)", + size: playSize, + id: "musicvideo.player.playPause" + ) { + viewModel.togglePlayback() + } + iconButton("goforward.10", label: "10秒進む(L)", size: buttonSize, id: "musicvideo.player.forward10") { + viewModel.skip(by: 10) + } + iconButton("forward.end.fill", label: "次のカット(.)", size: buttonSize, id: "musicvideo.player.nextCut") { + viewModel.skipToCut(1) + } + } + } + + private func muteButton(size: CGFloat) -> some View { + iconButton( + viewModel.isMuted ? "speaker.slash.fill" : "speaker.wave.2.fill", + label: viewModel.isMuted ? "音を出す(M)" : "音を消す(M)", + size: size, + id: "musicvideo.player.mute" + ) { + viewModel.isMuted.toggle() + } + } + + private func fullScreenButton(size: CGFloat) -> some View { + iconButton( + isFullScreen ? "arrow.down.right.and.arrow.up.left" : "arrow.up.left.and.arrow.down.right", + label: isFullScreen ? "全画面をやめる(F・Esc・ダブルクリック)" : "全画面で見る(ダブルクリック)", + size: size, + id: "musicvideo.player.fullScreen", + action: onToggleFullScreen + ) + } + + private func iconButton( + _ symbol: String, + label: String, + size: CGFloat, + id: String, + action: @escaping () -> Void + ) -> some View { + Button(action: action) { + Image(systemName: symbol) + .font(.system(size: size)) + .frame(width: size + 10, height: size + 8) + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + .help(label) + .accessibilityLabel(label) + .accessibilityIdentifier(id) + } + + // MARK: 文字 + + private var timeLabel: some View { + Text("\(Self.clock(viewModel.playbackTime)) / \(Self.clock(viewModel.playbackDuration))") + .font(.appCaption.monospacedDigit()) + .lineLimit(1) + } + + private var cutLabel: some View { + Group { + if let number = viewModel.currentCutNumber, let total = viewModel.plan?.cuts.count { + Text("カット \(number)/\(total)") + } + } + .font(.appCaption.monospacedDigit()) + .lineLimit(1) + } + + static func clock(_ seconds: Double) -> String { + let total = Int(max(0, seconds)) + return String(format: "%d:%02d", total / 60, total % 60) + } +} + +// MARK: - シークバー + +/// 再生位置を示し、クリックやドラッグで動かせる細い棒。カットの切り替え位置に印を付ける。 +struct MusicVideoSeekBar: View { + let duration: Double + let time: Double + let cutStarts: [Double] + /// ドラッグしている間、続けて呼ばれる(軽く動かす)。 + let onScrub: (Double) -> Void + /// クリックまたはドラッグの終わりに呼ばれる(正確な位置へ合わせる)。 + let onCommit: (Double) -> Void + + @State private var dragTime: Double? + + var body: some View { + GeometryReader { proxy in + let width = max(proxy.size.width, 1) + let shown = dragTime ?? time + let fraction = duration > 0 ? min(max(shown / duration, 0), 1) : 0 + ZStack(alignment: .leading) { + Capsule() + .fill(Color.white.opacity(0.28)) + .frame(height: 4) + Capsule() + .fill(Color.white) + .frame(width: max(4, width * fraction), height: 4) + Canvas { context, size in + drawCutMarks(in: &context, size: size) + } + .allowsHitTesting(false) + Circle() + .fill(Color.white) + .frame(width: dragTime == nil ? 10 : 14, height: dragTime == nil ? 10 : 14) + .offset(x: width * fraction - (dragTime == nil ? 5 : 7)) + .shadow(color: .black.opacity(0.4), radius: 2) + } + .frame(maxHeight: .infinity) + .contentShape(Rectangle()) + .gesture( + DragGesture(minimumDistance: 0) + .onChanged { value in + let target = seconds(at: value.location.x, width: width) + dragTime = target + onScrub(target) + } + .onEnded { value in + let target = seconds(at: value.location.x, width: width) + dragTime = nil + onCommit(target) + } + ) + } + .frame(height: 20) + .accessibilityElement() + .accessibilityLabel("再生位置") + .accessibilityValue("\(MusicVideoPlayerControls.clock(time)) / \(MusicVideoPlayerControls.clock(duration))") + } + + private func seconds(at x: CGFloat, width: CGFloat) -> Double { + guard duration > 0 else { return 0 } + return min(max(Double(x / width), 0), 1) * duration + } + + /// カットの切り替え位置に、短い縦線を引く。間隔が詰まりすぎる所は間引く。 + private func drawCutMarks(in context: inout GraphicsContext, size: CGSize) { + guard duration > 0 else { return } + var lastX = -10.0 + for start in cutStarts where start > 0 { + let x = start / duration * size.width + guard x - lastX >= 3 else { continue } + lastX = x + let rect = CGRect(x: x - 0.5, y: size.height / 2 - 5, width: 1, height: 10) + context.fill(Path(rect), with: .color(.white.opacity(0.45))) + } + } +} + +// MARK: - 全画面 + +/// 全画面のウィンドウの中身。映像を画面いっぱいに出し、操作部は、しばらく動かさないと隠れる。 +struct MusicVideoFullScreenView: View { + @ObservedObject var viewModel: MusicVideoViewModel + let close: () -> Void + + @State private var controlsVisible = true + @State private var hideTask: Task? + @State private var controlsHeight: CGFloat = 0 + + var body: some View { + ZStack { + Color.black + MusicVideoPlayerSurface( + player: viewModel.player, + passThroughBottom: controlsVisible ? controlsHeight : 0, + onClick: { viewModel.togglePlayback() }, + onDoubleClick: { + viewModel.togglePlayback() + close() + } + ) + + VStack(spacing: 0) { + Spacer() + MusicVideoPlayerControls(viewModel: viewModel, style: .full, isFullScreen: true, onToggleFullScreen: close) + .onGeometryChange(for: CGFloat.self) { $0.size.height } action: { controlsHeight = $0 } + } + .opacity(controlsVisible ? 1 : 0) + .allowsHitTesting(controlsVisible) + .animation(.easeInOut(duration: 0.2), value: controlsVisible) + } + .ignoresSafeArea() + .onContinuousHover { phase in + if case .active = phase { revealControls() } + } + .onAppear(perform: revealControls) + .onChange(of: viewModel.isPlaying) { revealControls() } + // 映像が無くなった(作り直しなど)ときは、全画面を閉じる。 + .onChange(of: viewModel.plan == nil) { _, isGone in + if isGone { close() } + } + .background(shortcuts) + .accessibilityIdentifier("musicvideo.fullScreen") + } + + /// 操作部を出し、再生中なら少し待って隠す(一時停止中は出したままにする)。 + private func revealControls() { + controlsVisible = true + hideTask?.cancel() + guard viewModel.isPlaying else { return } + hideTask = Task { + try? await Task.sleep(for: .seconds(2.5)) + guard !Task.isCancelled, viewModel.isPlaying else { return } + controlsVisible = false + NSCursor.setHiddenUntilMouseMoves(true) + } + } + + /// キーボードの操作。全画面のウィンドウの中だけで効く(ほかの画面の入力とぶつからない)。 + private var shortcuts: some View { + ZStack { + shortcut(.space) { viewModel.togglePlayback() } + shortcut("k") { viewModel.togglePlayback() } + shortcut(.leftArrow) { viewModel.skip(by: -5) } + shortcut(.rightArrow) { viewModel.skip(by: 5) } + shortcut(",") { viewModel.skipToCut(-1) } + shortcut(".") { viewModel.skipToCut(1) } + shortcut("j") { viewModel.skip(by: -10) } + shortcut("l") { viewModel.skip(by: 10) } + shortcut("m") { viewModel.isMuted.toggle() } + shortcut("f") { close() } + } + .frame(width: 0, height: 0) + .opacity(0) + .accessibilityHidden(true) + } + + private func shortcut( + _ key: KeyEquivalent, + modifiers: EventModifiers = [], + action: @escaping () -> Void + ) -> some View { + Button("", action: { + action() + revealControls() + }) + .keyboardShortcut(key, modifiers: modifiers) + } +} diff --git a/ArkServer/Features/MusicVideo/Views/MusicVideoSourcePickerSheet.swift b/ArkServer/Features/MusicVideo/Views/MusicVideoSourcePickerSheet.swift index 5a612cb..45f6f78 100644 --- a/ArkServer/Features/MusicVideo/Views/MusicVideoSourcePickerSheet.swift +++ b/ArkServer/Features/MusicVideo/Views/MusicVideoSourcePickerSheet.swift @@ -28,15 +28,6 @@ struct MusicVideoSourcePickerSheet: View { var id: String { rawValue } } - private struct AlbumRow: Identifiable { - let id: UUID - let title: String - let parent: String - let count: Int - let totalDuration: Double - let latestImport: Date - } - @State private var tab: Tab = .albums @State private var searchText = "" @AppStorage("musicVideo.picker.albumOrder") private var albumOrder: AlbumOrder = .name @@ -45,7 +36,7 @@ struct MusicVideoSourcePickerSheet: View { @AppStorage("musicVideo.picker.minimumLength") private var minimumLength = 5.0 @State private var onlySelected = false @State private var favoritesOnly = false - @State private var albumRows: [AlbumRow] = [] + @State private var albumRows: [MusicVideoAlbumEntry] = [] /// 動画タブの一覧(動画だけ・ゴミ箱外)。ライブラリが変わったときだけ作り直す。 @State private var allVideos: [VideoItem] = [] @@ -142,15 +133,11 @@ struct MusicVideoSourcePickerSheet: View { // MARK: - アルバム - private var visibleAlbums: [AlbumRow] { + private var visibleAlbums: [MusicVideoAlbumEntry] { var rows = albumRows if hidesEmptyAlbums { rows = rows.filter { $0.count > 0 } } if onlySelected { rows = rows.filter { viewModel.selectedAlbumIDs.contains($0.id) } } - if !query.isEmpty { - rows = rows.filter { - $0.title.localizedCaseInsensitiveContains(query) || $0.parent.localizedCaseInsensitiveContains(query) - } - } + if !query.isEmpty { rows = rows.filter { $0.matches(query: query) } } switch albumOrder { case .name: rows.sort { ($0.parent + "/" + $0.title).localizedStandardCompare($1.parent + "/" + $1.title) == .orderedAscending } @@ -292,7 +279,7 @@ struct MusicVideoSourcePickerSheet: View { HStack(spacing: 12) { VStack(alignment: .leading, spacing: 2) { Text("使える動画 \(viewModel.candidateCount.formatted())本") - .font(.appBody.weight(.semibold)) + .font(.appBodyStrong) Text(summaryDetail) .font(.appCaption) .foregroundStyle(NeomorphicTheme.muted) @@ -312,7 +299,7 @@ struct MusicVideoSourcePickerSheet: View { if !viewModel.selectedVideoIDs.isEmpty { parts.append("動画 \(viewModel.selectedVideoIDs.count)本") } if viewModel.includeFavorites { parts.append("お気に入り") } let selection = parts.isEmpty ? "まだ何も選ばれていません" : parts.joined(separator: "・") - let limit = ClipPoolBuilder().maxVideos + let limit = viewModel.sourceLimit return viewModel.candidateCount > limit ? "\(selection)(解析は無作為に選ぶ\(limit)本まで)" : selection @@ -346,28 +333,6 @@ struct MusicVideoSourcePickerSheet: View { let videos = dataManager.videos allVideos = videos.filter { $0.mediaType == .video && !$0.isInTrash } - let byID = Dictionary(videos.map { ($0.id, $0) }, uniquingKeysWith: { first, _ in first }) - albumRows = dataManager.albums - .filter { $0.type != .photo } - .map { album in - var count = 0 - var total = 0.0 - var latest = Date.distantPast - for id in album.videoIDs { - guard let item = byID[id], item.mediaType == .video, !item.isInTrash else { continue } - count += 1 - total += item.duration - latest = max(latest, item.importDate) - } - let components = album.name.components(separatedBy: "/") - return AlbumRow( - id: album.id, - title: album.displayTitle, - parent: components.count > 1 ? components.dropLast().joined(separator: " / ") : "", - count: count, - totalDuration: total, - latestImport: latest - ) - } + albumRows = MusicVideoAlbumEntry.entries(albums: dataManager.albums, videos: videos) } } diff --git a/ArkServer/Features/MusicVideo/Views/MusicVideoTuningSections.swift b/ArkServer/Features/MusicVideo/Views/MusicVideoTuningSections.swift new file mode 100644 index 0000000..0292136 --- /dev/null +++ b/ArkServer/Features/MusicVideo/Views/MusicVideoTuningSections.swift @@ -0,0 +1,322 @@ +// ArkServer/Features/MusicVideo/Views/MusicVideoTuningSections.swift + +import SwiftUI + +/// 「カット割り」「見た目と音」「書き出し」の調整項目。 +/// +/// 映像ができているときは、項目を変えると、すぐにプレビューとタイムラインが変わる(乱数の種は変えないので、 +/// 変えた項目だけの違いが出る)。各項目の説明には、いまの曲での秒数や、いまのカット割りの結果を数値で添える。 +struct MusicVideoTuningSections: View { + @ObservedObject var viewModel: MusicVideoViewModel + + var body: some View { + VStack(alignment: .leading, spacing: 28) { + cutSection + lookSection + exportSection + } + } + + // MARK: - カット割り + + private var cutSection: some View { + SettingsSection( + title: "カット割り", + footer: viewModel.plan == nil + ? "映像を作ると、ここを変えるたびにプレビューが変わります." + : "変えるとすぐに映像へ反映されます.気に入らなければ「元に戻す」で戻せます." + ) { + SettingsGroup { + SettingsRow(title: "カットの細かさ", detail: cutStyleDetail) { + FlatSegmentedControl( + options: MusicVideoCutStyle.allCases, + title: \.displayName, + selection: $viewModel.cutStyle, + width: 210 + ) + } + SettingsRow(title: "最短のカット", detail: minimumDetail) { + Picker("最短のカット", selection: minimumBinding) { + ForEach(MusicVideoCutTuning.minimumChoices, id: \.self) { value in + Text(Self.seconds(value)).tag(value) + } + } + .labelsHidden() + .fixedSize() + } + SettingsRow(title: "最長のカット", detail: maximumDetail) { + Picker("最長のカット", selection: maximumBinding) { + Text("制限なし").tag(Double?.none) + ForEach(MusicVideoCutTuning.maximumChoices, id: \.self) { value in + Text(Self.seconds(value)).tag(Double?.some(value)) + } + } + .labelsHidden() + .fixedSize() + } + SettingsRow(title: "動きの合わせ方", detail: motionDetail) { + FlatSegmentedControl( + options: MotionMatching.allCases, + title: \.displayName, + selection: $viewModel.cutTuning.motionMatching, + width: 300 + ) + } + SettingsRow(title: "動画のばらけ具合", detail: varietyDetail) { + Picker("動画のばらけ具合", selection: $viewModel.cutTuning.variety) { + ForEach(VideoVariety.allCases, id: \.self) { Text($0.displayName).tag($0) } + } + .labelsHidden() + .fixedSize() + } + SettingsRow(title: "切り替えのタイミング", detail: viewModel.cutTuning.alignment.summary) { + Picker("切り替えのタイミング", selection: $viewModel.cutTuning.alignment) { + ForEach(CutAlignment.allCases, id: \.self) { Text($0.displayName).tag($0) } + } + .labelsHidden() + .fixedSize() + } + } + .disabled(viewModel.isWorking) + } + } + + private var minimumBinding: Binding { + Binding( + get: { viewModel.cutTuning.minimumCutDuration }, + set: { viewModel.cutTuning.setMinimum($0) } + ) + } + + private var maximumBinding: Binding { + Binding( + get: { viewModel.cutTuning.maximumCutDuration }, + set: { viewModel.cutTuning.setMaximum($0) } + ) + } + + /// この曲のテンポでの、盛り上がりの段階ごとのカットの長さ。最短・最長・細かさを変えると、数値も変わる。 + private var cutStyleDetail: String { + let base = "静かな所は長く,盛り上がる所は細かく切り替えます." + guard let tempo = viewModel.fullAnalysis?.tempo, tempo > 0 else { return base } + let interval = 60 / tempo + let planner = CutPlanner(style: viewModel.cutStyle, tuning: viewModel.cutTuning) + func seconds(_ intensity: MusicIntensity) -> String { + Self.seconds(Double(planner.effectiveBeats(for: intensity, beatInterval: interval)) * interval) + } + return base + "\nこの曲(\(Int(tempo.rounded())) BPM)では、静かな所は約\(seconds(.calm))、中は約\(seconds(.medium))、盛り上がる所は約\(seconds(.intense))ごとです." + } + + private var minimumDetail: String { + var text = "これより短いカットは作りません.速い曲で切り替えが忙しすぎるときに上げます." + if let stats = viewModel.planStats { text += "\nいまの最短: \(Self.seconds(stats.shortestCutDuration))" } + return text + } + + private var maximumDetail: String { + var text = "これより長いカットは作りません.静かな所で1カットが長すぎるときに下げます." + if let stats = viewModel.planStats { text += "\nいまの最長: \(Self.seconds(stats.longestCutDuration))" } + return text + } + + private var motionDetail: String { + var text = viewModel.cutTuning.motionMatching.summary + if let match = viewModel.planStats?.motionMatch { text += "\nいまの動きの一致度: \(MusicVideoChangeSummary.percent(match))" } + return text + } + + private var varietyDetail: String { + var text = viewModel.cutTuning.variety.summary + if let stats = viewModel.planStats { + text += "\nいま: 素材\(stats.poolVideoCount)本のうち\(stats.usedVideoCount)本を使用" + } + return text + } + + // MARK: - 見た目と音 + + private var lookSection: some View { + SettingsSection(title: "見た目と音") { + SettingsGroup { + SettingsRow(title: "画面サイズ", detail: renderDetail) { + Picker("画面サイズ", selection: $viewModel.renderPreset) { + ForEach(MusicVideoRenderPreset.allCases, id: \.self) { preset in + Text(preset.displayName).tag(preset) + } + } + .labelsHidden() + .fixedSize() + } + SettingsRow(title: "画面の合わせ方", detail: viewModel.lookTuning.fitMode.summary) { + FlatSegmentedControl( + options: MusicVideoFitMode.allCases, + title: \.displayName, + selection: $viewModel.lookTuning.fitMode, + width: 230 + ) + } + SettingsRow(title: "切り替え効果", detail: viewModel.lookTuning.transition.summary) { + FlatSegmentedControl( + options: MusicVideoTransition.allCases, + title: \.displayName, + selection: $viewModel.lookTuning.transition, + width: 300 + ) + } + SettingsRow(title: "最初と最後のフェード", detail: fadeDetail) { + Picker("最初と最後のフェード", selection: $viewModel.lookTuning.fadeSeconds) { + ForEach(MusicVideoLookTuning.fadeChoices, id: \.self) { value in + Text(value == 0 ? "なし" : Self.seconds(value)).tag(value) + } + } + .labelsHidden() + .fixedSize() + } + } + .disabled(viewModel.isWorking) + } + } + + private var renderDetail: String { + let size = viewModel.renderPreset.settings + return "完成映像の大きさです.いま \(size.width)×\(size.height)." + } + + private var fadeDetail: String { + let seconds = viewModel.lookTuning.fadeSeconds + if seconds == 0 { return "フェードしません.最初から最後まで、そのままの明るさと音量です." } + return "映像は黒から、音は無音から\(Self.seconds(seconds))かけて出て、最後も同じように消えます.この間、切り替え効果は付きません." + } + + // MARK: - 書き出し + + private var exportSection: some View { + SettingsSection(title: "書き出し") { + SettingsGroup { + SettingsRow(title: "書き出しの画質", detail: exportSizeText) { + Picker("書き出しの画質", selection: $viewModel.exportQuality) { + ForEach(MusicVideoExportQuality.allCases, id: \.self) { quality in + Text(quality.displayName).tag(quality) + } + } + .labelsHidden() + .fixedSize() + } + } + .disabled(viewModel.isWorking) + } + } + + /// 選んだ画質での、ファイルサイズの目安。映像にする長さが分かっていれば、全体の大きさも出す。 + private var exportSizeText: String { + let render = viewModel.renderPreset.settings + let perMinute = viewModel.exportQuality.estimatedMegabytesPerMinute(for: render) + var text = "1分あたり約\(Int(perMinute.rounded()))MB" + if let duration = viewModel.targetDuration { + text += "・この映像で約\(Int((perMinute * duration / 60).rounded()))MB" + } + return text + } + + static func seconds(_ value: Double) -> String { + MusicVideoChangeSummary.seconds(value) + } +} + +// MARK: - いまの結果 + +/// プレビューの下に出す、いまのカット割りの結果。調整項目を変えるたびに数値が変わる。 +struct MusicVideoResultSummary: View { + @ObservedObject var viewModel: MusicVideoViewModel + + var body: some View { + if let stats = viewModel.planStats { + VStack(alignment: .leading, spacing: 4) { + HStack(spacing: 8) { + Text(line(for: stats)) + .font(.appCaptionStrong) + .foregroundStyle(NeomorphicTheme.ink) + .lineLimit(2) + if viewModel.isApplyingEdit { ProgressView().controlSize(.small) } + } + if let note = viewModel.lastChangeNote { + Text(note) + .font(.appCaption) + .foregroundStyle(NeomorphicTheme.muted) + .fixedSize(horizontal: false, vertical: true) + } + } + .frame(maxWidth: .infinity, alignment: .leading) + .accessibilityElement(children: .combine) + } + } + + private func line(for stats: MusicVideoPlanStats) -> String { + var parts = [ + "\(stats.cutCount)カット", + "平均\(MusicVideoChangeSummary.seconds(stats.averageCutDuration))(\(MusicVideoChangeSummary.seconds(stats.shortestCutDuration))〜\(MusicVideoChangeSummary.seconds(stats.longestCutDuration)))", + "動画\(stats.usedVideoCount)/\(stats.poolVideoCount)本を使用" + ] + if let match = stats.motionMatch { parts.append("動きの一致\(MusicVideoChangeSummary.percent(match))") } + return parts.joined(separator: "・") + } +} + +// MARK: - 曲の範囲 + +/// 曲のうち、映像にする範囲の開始と終了を選ぶ。開始は曲の拍にそろう。 +struct MusicRangeControl: View { + @ObservedObject var viewModel: MusicVideoViewModel + + var body: some View { + if let duration = viewModel.fullAnalysis?.duration, duration > MusicRange.minimumLength { + let range = viewModel.musicRange + let start = range?.start ?? 0 + let end = range?.end ?? duration + SettingsRow(title: "使う範囲", detail: detail(start: start, end: end, duration: duration, isPartial: range != nil)) { + VStack(alignment: .trailing, spacing: 6) { + sliderRow(label: "開始", value: start, bounds: 0...(duration - MusicRange.minimumLength)) { + viewModel.setMusicRange(start: $0, end: max(end, $0 + MusicRange.minimumLength)) + } + sliderRow(label: "終了", value: end, bounds: MusicRange.minimumLength...duration) { + viewModel.setMusicRange(start: min(start, $0 - MusicRange.minimumLength), end: $0) + } + if range != nil { + Button("全体に戻す") { viewModel.setMusicRange(start: 0, end: duration) } + .buttonStyle(.quiet) + } + } + .disabled(viewModel.isWorking) + } + } + } + + private func sliderRow( + label: String, + value: Double, + bounds: ClosedRange, + onChange: @escaping (Double) -> Void + ) -> some View { + HStack(spacing: 8) { + Text(label) + .font(.appMicro) + .foregroundStyle(NeomorphicTheme.muted) + Slider(value: Binding(get: { value }, set: onChange), in: bounds) + .frame(width: 170) + Text(Self.clock(value)) + .font(.appCaption.monospacedDigit()) + .foregroundStyle(NeomorphicTheme.muted) + .frame(width: 40, alignment: .trailing) + } + } + + private func detail(start: Double, end: Double, duration: Double, isPartial: Bool) -> String { + guard isPartial else { return "曲の全体(\(Self.clock(duration)))を使います.サビだけの短い映像にしたいときは、範囲を狭めます." } + return "曲の\(Self.clock(start))から\(Self.clock(end))までの\(Int((end - start).rounded()))秒を映像にします.開始は拍にそろえます." + } + + static func clock(_ seconds: Double) -> String { + let total = Int(seconds.rounded()) + return String(format: "%d:%02d", total / 60, total % 60) + } +} diff --git a/ArkServer/Features/MusicVideo/Views/MusicVideoView.swift b/ArkServer/Features/MusicVideo/Views/MusicVideoView.swift index 1d99796..3d3cab6 100644 --- a/ArkServer/Features/MusicVideo/Views/MusicVideoView.swift +++ b/ArkServer/Features/MusicVideo/Views/MusicVideoView.swift @@ -16,42 +16,80 @@ struct MusicVideoView: View { @State private var isDropTargeted = false @State private var isShowingSourcePicker = false @State private var isShowingMusicPicker = false + @State private var isShowingExportAlbumPicker = false + /// プレビューを全画面で開く。 + @State private var fullScreen = MusicVideoFullScreenPresenter() + /// プレビューの高さが、窓の高さに占める割合。境目をドラッグして変える。次回も保つ。 + @AppStorage("musicVideo.previewHeightRatio") private var previewHeightRatio = 0.55 + @State private var dragStartRatio: Double? private static let topAnchor = "musicvideo.top" + /// プレビューを上に固定できる窓の高さ。これより低いときは、プレビューも一緒にスクロールする。 + private static let pinnedPreviewMinimumHeight: CGFloat = 640 + private static let previewHeightRatioRange: ClosedRange = 0.3...0.75 + /// 固定した領域のうち、プレビューの中身以外(余白・見出し・境目)の高さ。 + private static let pinnedPreviewChrome: CGFloat = 14 + 8 + 28 + 10 + /// 横長のプレビューで、動画の下に並べるタイムラインと結果の高さ。 + private static let stackedPreviewExtras: CGFloat = 150 + /// プレビューをスクロールの中に置くとき(窓が低いとき)の中身の高さ。 + private static let inlinePreviewContentHeight: CGFloat = 480 + var body: some View { - VStack(spacing: 0) { - ScrollViewReader { proxy in - ScrollView { - VStack(alignment: .leading, spacing: 28) { - // 見出しは列の左端にそろえる(LibraryPageHeader は左右に24の余白を持つ)。 - LibraryPageHeader( - title: "ミュージックビデオ", - subtitle: "曲を選ぶと,ライブラリの動画を曲の盛り上がりに合わせて自動で編集します" - ) - .padding(.horizontal, -24) - .id(Self.topAnchor) - - if viewModel.plan != nil { - previewSection - MusicVideoCutEditorView(viewModel: viewModel, dataManager: dataManager) - } - musicSection - sourceSection - finishSection + GeometryReader { geometry in + // 調整項目を変えたときの変化をその場で見られるよう、窓が十分に高ければ、プレビューを上に固定する。 + let pinsPreview = viewModel.plan != nil && geometry.size.height >= Self.pinnedPreviewMinimumHeight + let pinnedHeight = pinnedRegionHeight(windowHeight: geometry.size.height) + VStack(spacing: 0) { + if pinsPreview { + VStack(spacing: 0) { + previewSection(contentHeight: pinnedHeight - Self.pinnedPreviewChrome, showsCaption: false) + .frame(maxWidth: settingsColumnWidth) + .frame(maxWidth: .infinity) + .padding(.horizontal, 24) + .padding(.top, 14) + .padding(.bottom, 8) + .frame(height: pinnedHeight - 10, alignment: .top) + .clipped() + previewResizeHandle(windowHeight: geometry.size.height) } - .frame(maxWidth: musicVideoColumnWidth) - .frame(maxWidth: .infinity) - .padding(.horizontal, 24) - .padding(.bottom, 28) + .background(NeomorphicTheme.canvas) } - // 映像ができたら、一番上のプレビューが見えるようにする。 - .onChange(of: viewModel.plan != nil) { _, hasPlan in - if hasPlan { withAnimation { proxy.scrollTo(Self.topAnchor, anchor: .top) } } + + ScrollViewReader { proxy in + ScrollView { + VStack(alignment: .leading, spacing: 28) { + // 見出しは列の左端にそろえる(LibraryPageHeader は左右に24の余白を持つ)。 + LibraryPageHeader( + title: "ミュージックビデオ", + subtitle: "曲を選ぶと,ライブラリの動画を曲の盛り上がりに合わせて自動で編集します" + ) + .padding(.horizontal, -24) + .id(Self.topAnchor) + + if viewModel.plan != nil { + if !pinsPreview { + previewSection(contentHeight: Self.inlinePreviewContentHeight, showsCaption: true) + } + MusicVideoCutEditorView(viewModel: viewModel, dataManager: dataManager) + } + musicSection + sourceSection + MusicVideoTuningSections(viewModel: viewModel) + } + .frame(maxWidth: settingsColumnWidth) + .frame(maxWidth: .infinity) + .padding(.horizontal, 24) + .padding(.bottom, 28) + } + // 映像ができたら、一番上のプレビューが見えるようにする。 + .onChange(of: viewModel.plan != nil) { _, hasPlan in + if hasPlan { withAnimation { proxy.scrollTo(Self.topAnchor, anchor: .top) } } + } } - } - actionBar + actionBar + } } .background(CommandDeckBackground()) .navigationTitle("ミュージックビデオ") @@ -67,13 +105,18 @@ struct MusicVideoView: View { } .onDrop(of: [.fileURL], isTargeted: $isDropTargeted, perform: handleMusicDrop) .onAppear { viewModel.attach(dataManager: dataManager) } - .onDisappear { viewModel.pausePlayback() } + .onDisappear { viewModel.stopAllPlayback() } .sheet(isPresented: $isShowingSourcePicker) { MusicVideoSourcePickerSheet(viewModel: viewModel, dataManager: dataManager) } .sheet(isPresented: $isShowingMusicPicker) { MusicVideoMusicPickerSheet(viewModel: viewModel) } + .sheet(isPresented: $isShowingExportAlbumPicker) { + MusicVideoExportAlbumSheet(dataManager: dataManager, fileName: viewModel.suggestedFileName) { destination in + viewModel.exportToLibrary(dataManager: dataManager, destination: destination) + } + } .alert( "処理に失敗しました", isPresented: Binding( @@ -100,34 +143,107 @@ struct MusicVideoView: View { // MARK: - プレビュー - private var previewSection: some View { - MVSection(title: "プレビュー") { - VStack(spacing: 12) { - // 縦横比を保った枠(背景・角丸は枠そのものに付け、外側の frame で最大の高さだけ制限する)。 - Color.clear - .aspectRatio(previewAspectRatio, contentMode: .fit) - .overlay { VideoPlayer(player: viewModel.player) } - .background( - RoundedRectangle(cornerRadius: DS.cardCornerRadius, style: .continuous) - .fill(NeomorphicTheme.card) - ) - .clipShape(RoundedRectangle(cornerRadius: DS.cardCornerRadius, style: .continuous)) - .frame(maxWidth: .infinity, maxHeight: 340) - - if let analysis = viewModel.analysis { - VStack(alignment: .leading, spacing: 6) { - MusicTimelineView( - analysis: analysis, - plan: viewModel.plan, - playbackTime: viewModel.playbackTime, - selectedCutIndex: viewModel.selectedCutIndex, - onSeek: viewModel.seek(to:), - onSelect: viewModel.selectCut(at:) - ) - Text("濃い背景ほど盛り上がる部分です.上の短い線がカットの切り替え,下の短い線が拍です.") - .font(.appCaption) - .foregroundStyle(NeomorphicTheme.muted) + /// 固定するプレビュー領域の高さ。窓の高さに対する割合で決め、設定の欄が少なくとも300ptは残るようにする。 + private func pinnedRegionHeight(windowHeight: CGFloat) -> CGFloat { + let wanted = windowHeight * previewHeightRatio + return min(max(wanted, 260), max(260, windowHeight - 300)) + } + + /// プレビューと設定の境目。ドラッグでプレビューの大きさを変える。 + private func previewResizeHandle(windowHeight: CGFloat) -> some View { + ZStack { + Divider().overlay(NeomorphicTheme.separator) + Capsule() + .fill(NeomorphicTheme.muted.opacity(0.55)) + .frame(width: 36, height: 4) + } + .frame(height: 10) + .contentShape(Rectangle()) + .onHover { inside in + if inside { NSCursor.resizeUpDown.push() } else { NSCursor.pop() } + } + .gesture( + DragGesture(minimumDistance: 1, coordinateSpace: .global) + .onChanged { value in + let start = dragStartRatio ?? previewHeightRatio + dragStartRatio = start + let moved = start + Double(value.translation.height / max(windowHeight, 1)) + previewHeightRatio = min(max(moved, Self.previewHeightRatioRange.lowerBound), Self.previewHeightRatioRange.upperBound) + } + .onEnded { _ in dragStartRatio = nil } + ) + .help("ドラッグして、プレビューの大きさを変えます") + .accessibilityLabel("プレビューの大きさ") + } + + /// - Parameters: + /// - contentHeight: 見出しを除いた、プレビュー部分に使える高さ。 + /// - showsCaption: タイムラインの下に、見方の説明を出すか。 + private func previewSection(contentHeight: CGFloat, showsCaption: Bool) -> some View { + SettingsSection(title: "プレビュー") { + if previewAspectRatio < 1.2 { + // 縦長・正方形の画面: 動画を高く取り、タイムラインと結果は右に置く(横幅が余るので)。 + let width = min(max(160, contentHeight) * previewAspectRatio, 440) + HStack(alignment: .top, spacing: 20) { + Color.clear + .overlay { previewPlayer } + .background(previewPlayerBackground) + .clipShape(previewPlayerShape) + .frame(width: width, height: width / previewAspectRatio) + VStack(alignment: .leading, spacing: 12) { + timelineBlock(showsCaption: true) + MusicVideoResultSummary(viewModel: viewModel) } + .frame(maxWidth: .infinity, alignment: .topLeading) + } + } else { + // 横長の画面: 動画の下に、タイムラインと結果を並べる。 + VStack(spacing: 12) { + // 縦横比を保った枠(背景・角丸は枠そのものに付け、外側の frame で最大の高さだけ制限する)。 + Color.clear + .aspectRatio(previewAspectRatio, contentMode: .fit) + .overlay { previewPlayer } + .background(previewPlayerBackground) + .clipShape(previewPlayerShape) + .frame(maxWidth: .infinity, maxHeight: max(140, contentHeight - Self.stackedPreviewExtras)) + timelineBlock(showsCaption: showsCaption) + MusicVideoResultSummary(viewModel: viewModel) + } + } + } + } + + /// 映像と、再生の操作(再生・スキップ・シーク・ミュート・全画面)。 + private var previewPlayer: some View { + MusicVideoPlayerPane(viewModel: viewModel) { + fullScreen.present(viewModel: viewModel) + } + } + + private var previewPlayerShape: RoundedRectangle { + RoundedRectangle(cornerRadius: DS.cardCornerRadius, style: .continuous) + } + + private var previewPlayerBackground: some View { + previewPlayerShape.fill(NeomorphicTheme.card) + } + + @ViewBuilder + private func timelineBlock(showsCaption: Bool) -> some View { + if let analysis = viewModel.analysis { + VStack(alignment: .leading, spacing: 6) { + MusicTimelineView( + analysis: analysis, + plan: viewModel.plan, + playbackTime: viewModel.playbackTime, + selectedCutIndex: viewModel.selectedCutIndex, + onSeek: viewModel.seek(to:), + onSelect: viewModel.selectCut(at:) + ) + if showsCaption { + Text("濃い背景ほど盛り上がる部分です.上の短い線がカットの切り替え,下の短い線が拍です.") + .font(.appCaption) + .foregroundStyle(NeomorphicTheme.muted) } } } @@ -141,17 +257,20 @@ struct MusicVideoView: View { // MARK: - 曲 private var musicSection: some View { - MVSection(title: "曲") { - MVRowGroup { - MVRow(title: viewModel.musicTitle ?? "曲を選んでください", detail: musicDetail) { + SettingsSection(title: "曲") { + SettingsGroup { + SettingsRow(title: viewModel.musicTitle ?? "曲を選んでください", detail: musicDetail) { HStack(spacing: 8) { if viewModel.phase == .analyzingMusic { ProgressView().controlSize(.small) } + if let url = viewModel.musicURL { + MusicPreviewButton(preview: viewModel.preview, url: url) { viewModel.togglePreview(url) } + } Button("フォルダから…") { isShowingMusicPicker = true } - .buttonStyle(.mvSmall) + .buttonStyle(.quiet) .help("曲を置いてあるフォルダから探して選びます") .accessibilityIdentifier("musicvideo.musicFolder") Button("ファイル…") { chooseMusicFile() } - .buttonStyle(.mvSmall) + .buttonStyle(.quiet) .help("曲のファイルを1つ選びます") .accessibilityIdentifier("musicvideo.musicFile") if !viewModel.recentMusicURLs.isEmpty { recentMenu } @@ -159,19 +278,23 @@ struct MusicVideoView: View { .disabled(viewModel.isWorking) } if viewModel.musicURL == nil, let last = viewModel.lastMusicURL { - MVRow(title: "前回の曲", detail: last.deletingPathExtension().lastPathComponent) { - Button("開く") { viewModel.chooseMusic(last) } - .buttonStyle(.mvSmall) - .disabled(viewModel.isWorking) - .accessibilityIdentifier("musicvideo.openLastMusic") + SettingsRow(title: "前回の曲", detail: last.deletingPathExtension().lastPathComponent) { + HStack(spacing: 8) { + MusicPreviewButton(preview: viewModel.preview, url: last) { viewModel.togglePreview(last) } + Button("開く") { viewModel.chooseMusic(last) } + .buttonStyle(.quiet) + .disabled(viewModel.isWorking) + .accessibilityIdentifier("musicvideo.openLastMusic") + } } } - if let analysis = viewModel.analysis { - MVRow(title: "テンポと拍") { + if let analysis = viewModel.fullAnalysis { + SettingsRow(title: "テンポと拍") { Text("\(formatTime(analysis.duration))・\(Int(analysis.tempo.rounded())) BPM・拍 \(analysis.beats.count)個") .font(.appBody.monospacedDigit()) .foregroundStyle(NeomorphicTheme.muted) } + MusicRangeControl(viewModel: viewModel) } } } @@ -191,7 +314,7 @@ struct MusicVideoView: View { Text("最近") } .menuStyle(.button) - .buttonStyle(.mvSmall) + .buttonStyle(.quiet) .menuIndicator(.visible) .fixedSize() } @@ -230,32 +353,59 @@ struct MusicVideoView: View { } private var sourceSection: some View { - MVSection(title: "素材") { - MVRowGroup { - MVRow( + SettingsSection(title: "素材") { + SettingsGroup { + SettingsRow( title: viewModel.candidateCount == 0 ? "素材がまだ選ばれていません" : "使える動画 \(viewModel.candidateCount.formatted())本", detail: sourceDetail ) { HStack(spacing: 8) { if !(viewModel.selectedAlbumIDs.isEmpty && viewModel.selectedVideoIDs.isEmpty) { Button("解除") { viewModel.clearSourceSelection() } - .buttonStyle(.mvSmall) + .buttonStyle(.quiet) .help("アルバムと動画の選択をすべて外します") } Button("選ぶ…") { isShowingSourcePicker = true } - .buttonStyle(.mvSmall) + .buttonStyle(.quiet) .accessibilityIdentifier("musicvideo.chooseSource") } .disabled(viewModel.isWorking) } - MVRow(title: "お気に入りを含める", detail: "お気に入りにした動画も素材に加えます.") { - MVSwitch(title: "お気に入りを含める", isOn: $viewModel.includeFavorites) + SettingsRow(title: "お気に入りを含める", detail: "お気に入りにした動画も素材に加えます.") { + SettingsSwitch(title: "お気に入りを含める", isOn: $viewModel.includeFavorites) .disabled(viewModel.isWorking) } + SettingsRow(title: "解析に使う動画の本数", detail: sourceLimitDetail) { + Picker("解析に使う動画の本数", selection: $viewModel.sourceLimit) { + ForEach(MusicVideoSourceLimit.choices, id: \.self) { Text("\($0)本").tag($0) } + } + .labelsHidden() + .fixedSize() + .disabled(viewModel.isWorking) + .accessibilityIdentifier("musicvideo.sourceLimit") + } } } } + /// 選んだ動画が多いときの、解析する本数の説明。変えたあとは「作り直す」で反映する。 + private var sourceLimitDetail: String { + let candidates = viewModel.candidateCount + let limit = viewModel.sourceLimit + var text: String + if candidates == 0 { + text = "選んだ動画が多いときは、この本数を無作為に選んで解析します." + } else if candidates <= limit { + text = "選んだ\(candidates.formatted())本をすべて使います." + } else { + text = "選んだ\(candidates.formatted())本のうち、無作為に\(limit)本を使います.多いほど変化に富みますが、初回の解析に時間がかかります(解析済みの動画は次回から速くなります)." + } + if viewModel.sourceLimitNeedsRebuild { + text += "\n「作り直す」を押すと、この本数で作り直します." + } + return text + } + /// 選んだアルバム・動画の内訳(例: 「fontene・acid39 ほかアルバム2個・個別の動画 3本」)。 private var sourceDetail: String? { let albums = selectedAlbums @@ -265,61 +415,10 @@ struct MusicVideoView: View { parts.append(albums.count > 3 ? "\(names) ほかアルバム\(albums.count - 3)個" : names) } if !viewModel.selectedVideoIDs.isEmpty { parts.append("個別の動画 \(viewModel.selectedVideoIDs.count)本") } - var text = parts.joined(separator: "・") - let limit = ClipPoolBuilder().maxVideos - if viewModel.candidateCount > limit { - text += (text.isEmpty ? "" : "\n") + "解析は無作為に選んだ\(limit)本までです." - } + let text = parts.joined(separator: "・") return text.isEmpty ? "アルバムや動画を選んでください." : text } - // MARK: - 仕上がり - - private var finishSection: some View { - MVSection(title: "仕上がり") { - MVRowGroup { - MVRow(title: "カットの細かさ", detail: "静かな所は長く,盛り上がる所は細かく切り替えます.") { - FlatSegmentedControl( - options: MusicVideoCutStyle.allCases, - title: \.displayName, - selection: $viewModel.cutStyle, - width: 210 - ) - } - MVRow(title: "画面サイズ") { - Picker("画面サイズ", selection: $viewModel.renderPreset) { - ForEach(MusicVideoRenderPreset.allCases, id: \.self) { preset in - Text(preset.displayName).tag(preset) - } - } - .labelsHidden() - .fixedSize() - } - MVRow(title: "書き出しの画質", detail: exportSizeText) { - Picker("書き出しの画質", selection: $viewModel.exportQuality) { - ForEach(MusicVideoExportQuality.allCases, id: \.self) { quality in - Text(quality.displayName).tag(quality) - } - } - .labelsHidden() - .fixedSize() - } - } - .disabled(viewModel.isWorking) - } - } - - /// 選んだ画質での、ファイルサイズの目安。曲の長さが分かっていれば、全体の大きさも出す。 - private var exportSizeText: String { - let render = viewModel.renderPreset.settings - let perMinute = viewModel.exportQuality.estimatedMegabytesPerMinute(for: render) - var text = "1分あたり約\(Int(perMinute.rounded()))MB" - if let duration = viewModel.analysis?.duration { - text += "・この曲で約\(Int((perMinute * duration / 60).rounded()))MB" - } - return text - } - // MARK: - 下に固定する実行の帯 private var actionBar: some View { @@ -341,11 +440,11 @@ struct MusicVideoView: View { .controlSize(.large) .disabled(!viewModel.canExport) .accessibilityIdentifier("musicvideo.saveFile") - Button("「HMV」に追加") { viewModel.exportToLibrary(dataManager: dataManager) } + Button("ライブラリに追加…") { isShowingExportAlbumPicker = true } .buttonStyle(.bordered) .controlSize(.large) .disabled(!viewModel.canExport) - .help("書き出して「HMV」アルバムに追加します") + .help("追加するアルバムを選んで,書き出してライブラリに追加します") .accessibilityIdentifier("musicvideo.exportLibrary") } Button(viewModel.plan == nil ? "映像を作る" : "作り直す") { @@ -358,7 +457,7 @@ struct MusicVideoView: View { .accessibilityIdentifier("musicvideo.generate") } } - .frame(maxWidth: musicVideoColumnWidth) + .frame(maxWidth: settingsColumnWidth) .frame(maxWidth: .infinity) .padding(.horizontal, 24) .padding(.vertical, 14) From d3ccfa5bec6c38fd2fbfeb7ae452148929d1b998 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8E=9F=E3=80=80=E9=A2=AF=E7=99=BB?= Date: Wed, 4 Nov 2026 13:23:34 +0900 Subject: [PATCH 9/9] =?UTF-8?q?test(musicvideo):=20=E3=82=AB=E3=83=83?= =?UTF-8?q?=E3=83=88=E5=89=B2=E3=82=8A=E8=AA=BF=E6=95=B4=E3=83=BB=E6=98=A0?= =?UTF-8?q?=E5=83=8F=E5=8A=B9=E6=9E=9C=E5=90=88=E6=88=90=E3=83=BB=E6=9B=B2?= =?UTF-8?q?=E7=AF=84=E5=9B=B2=E3=83=BBViewModel=E6=93=8D=E4=BD=9C=E3=81=AE?= =?UTF-8?q?=E5=8D=98=E4=BD=93=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 --- ArkServerTests/MusicVideoTests.swift | 27 +- ArkServerTests/MusicVideoTuningTests.swift | 1107 ++++++++++++++++++++ 2 files changed, 1122 insertions(+), 12 deletions(-) create mode 100644 ArkServerTests/MusicVideoTuningTests.swift diff --git a/ArkServerTests/MusicVideoTests.swift b/ArkServerTests/MusicVideoTests.swift index 40e12d1..591f515 100644 --- a/ArkServerTests/MusicVideoTests.swift +++ b/ArkServerTests/MusicVideoTests.swift @@ -7,10 +7,10 @@ import Testing // MARK: - 合成音声 -private let testSampleRate = 22_050.0 +let testSampleRate = 22_050.0 /// 指定した時刻にクリック音(減衰する1.5kHzの短い音)を置いた音声を作る。 -private func clickTrack(duration: Double, clicks: [(time: Double, amplitude: Float)]) -> [Float] { +func clickTrack(duration: Double, clicks: [(time: Double, amplitude: Float)]) -> [Float] { var samples = [Float](repeating: 0, count: Int(duration * testSampleRate)) let burstLength = Int(0.03 * testSampleRate) for click in clicks { @@ -24,7 +24,7 @@ private func clickTrack(duration: Double, clicks: [(time: Double, amplitude: Flo } /// 一定間隔(`interval` 秒)のクリックの時刻。 -private func evenClicks(from first: Double, interval: Double, until end: Double) -> [Double] { +func evenClicks(from first: Double, interval: Double, until end: Double) -> [Double] { Array(stride(from: first, to: end, by: interval)) } @@ -35,11 +35,13 @@ private func nearestDistance(to time: Double, in times: [Double]) -> Double { // MARK: - 合成動画 /// 単色のフレームだけからなる小さな動画を書き出す。`brightness` でフレームごとの明るさを決める。 -private func makeTestVideo( +func makeTestVideo( at url: URL, duration: Double, size: (width: Int, height: Int) = (160, 90), framesPerSecond: Int32 = 30, + /// 向きの情報(スマートフォンで縦に撮った動画のように、画素は横長のまま回転だけを持たせる)。 + transform: CGAffineTransform = .identity, brightness: (Int) -> UInt8 ) async throws { let writer = try AVAssetWriter(outputURL: url, fileType: .mp4) @@ -51,6 +53,7 @@ private func makeTestVideo( AVVideoHeightKey: size.height ] ) + input.transform = transform let adaptor = AVAssetWriterInputPixelBufferAdaptor( assetWriterInput: input, sourcePixelBufferAttributes: [ @@ -83,7 +86,7 @@ private func makeTestVideo( #expect(writer.status == .completed) } -private func temporaryDirectory(_ name: String) throws -> URL { +func temporaryDirectory(_ name: String) throws -> URL { let url = FileManager.default.temporaryDirectory.appendingPathComponent("\(name)-\(UUID().uuidString)") try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true) return url @@ -558,7 +561,7 @@ private final class LockedCounter: @unchecked Sendable { // MARK: - 合成と書き出し /// 画像を `columns`×`rows` に区切り、各区画の平均の明るさ(0〜255)を返す。 -private func lumaGrid(_ image: CGImage, columns: Int = 4, rows: Int = 4) -> [Double] { +func lumaGrid(_ image: CGImage, columns: Int = 4, rows: Int = 4) -> [Double] { let width = 64, height = 64 var pixels = [UInt8](repeating: 0, count: width * height) pixels.withUnsafeMutableBytes { buffer in @@ -585,7 +588,7 @@ private func lumaGrid(_ image: CGImage, columns: Int = 4, rows: Int = 4) -> [Dou return result } -private func writeSineWAV(to url: URL, duration: Double) throws { +func writeSineWAV(to url: URL, duration: Double) throws { let sampleRate = 44_100.0 let format = try #require(AVAudioFormat(standardFormatWithSampleRate: sampleRate, channels: 1)) let frames = AVAudioFrameCount(duration * sampleRate) @@ -600,7 +603,7 @@ private func writeSineWAV(to url: URL, duration: Double) throws { } /// 段階の名前つきで実行し、失敗したときはどの段階かを記録してから投げ直す。 -private func step(_ label: String, _ body: () async throws -> T) async throws -> T { +func step(_ label: String, _ body: () async throws -> T) async throws -> T { do { return try await body() } catch { @@ -656,7 +659,7 @@ struct MusicVideoComposerTests { #expect(composed.composition.tracks(withMediaType: .audio).count == 1) #expect(composed.videoComposition.renderSize == render.size) - let outputURL = directory.appendingPathComponent("out/hmv.mp4") + let outputURL = directory.appendingPathComponent("out/result.mp4") let progress = LockedCounter() try await step("export") { try await composer.export(composed, to: outputURL) { fraction in @@ -715,7 +718,7 @@ struct MusicVideoComposerTests { // MARK: - 曲の解析から書き出しまで通した確認 -private func writeMonoWAV(samples: [Float], sampleRate: Double, to url: URL) throws { +func writeMonoWAV(samples: [Float], sampleRate: Double, to url: URL) throws { let format = try #require(AVAudioFormat(standardFormatWithSampleRate: sampleRate, channels: 1)) let buffer = try #require(AVAudioPCMBuffer(pcmFormat: format, frameCapacity: AVAudioFrameCount(samples.count))) buffer.frameLength = AVAudioFrameCount(samples.count) @@ -788,7 +791,7 @@ struct MusicVideoPipelineTests { audioURL: musicURL, render: render ) - let outputURL = directory.appendingPathComponent("hmv.mp4") + let outputURL = directory.appendingPathComponent("result.mp4") try await composer.export(composed, to: outputURL) let output = AVURLAsset(url: outputURL) @@ -1264,7 +1267,7 @@ struct MusicVideoExportQualityTests { func outputFileNamesAreSafeAndStamped() { let date = Date(timeIntervalSince1970: 1_700_000_000) let name = MusicVideoViewModel.outputFileName(musicTitle: "a/b:c*d?e", date: date) - #expect(name.hasPrefix("HMV_a_b_c_d_e_")) + #expect(name.hasPrefix("MusicVideo_a_b_c_d_e_")) #expect(name.hasSuffix(".mp4")) #expect(!name.dropFirst(4).contains("/")) } diff --git a/ArkServerTests/MusicVideoTuningTests.swift b/ArkServerTests/MusicVideoTuningTests.swift new file mode 100644 index 0000000..cb3fd52 --- /dev/null +++ b/ArkServerTests/MusicVideoTuningTests.swift @@ -0,0 +1,1107 @@ +// ArkServerTests/MusicVideoTuningTests.swift + +import AVFoundation +import Foundation +import Testing +@testable import ArkServer + +// MARK: - 共通の部品 + +/// 0.5秒ごとの拍。`intensityAt` が、秒ごとの盛り上がりの段階を決める。 +private func makeAnalysis( + duration: Double = 60, + beatInterval: Double = 0.5, + intensityAt: (Int) -> MusicIntensity = { second in + switch second { + case ..<20: return .calm + case ..<40: return .intense + default: return .medium + } + } +) -> MusicAnalysis { + let beats = Array(stride(from: beatInterval, to: duration - 0.1, by: beatInterval)) + var energy: [Double] = [] + var intensity: [MusicIntensity] = [] + for second in 0.. SourceMotionProfile { + SourceMotionProfile( + videoID: id, + duration: duration, + hop: 0.5, + values: [Double](repeating: motion, count: Int(duration / 0.5)) + ) +} + +private func plannedCut(_ video: UUID, from sourceStart: Double, at start: Double, length: Double) -> PlannedCut { + PlannedCut(videoID: video, sourceStart: sourceStart, duration: length, timelineStart: start, intensity: .medium) +} + +// MARK: - カット割りの調整項目 + +@Suite(.serialized) +struct CutTuningPlannerTests { + private func plan( + _ analysis: MusicAnalysis, + pool: [SourceMotionProfile], + style: MusicVideoCutStyle = .standard, + tuning: MusicVideoCutTuning = MusicVideoCutTuning(), + seed: UInt64 = 1 + ) throws -> CutPlan { + try CutPlanner(style: style, tuning: tuning).plan(analysis: analysis, pool: pool, seed: seed) + } + + @Test + func effectiveBeatsFollowStyleMinimumAndMaximum() { + // 標準: 静か=4拍。0.5秒間隔なら2.0秒。 + var planner = CutPlanner(style: .standard, tuning: MusicVideoCutTuning()) + #expect(planner.effectiveBeats(for: .calm, beatInterval: 0.5) == 4) + #expect(planner.effectiveBeats(for: .intense, beatInterval: 0.5) == 1) + + // 最長 1.5秒 → 3拍まで。 + planner.maximumCutDuration = 1.5 + #expect(planner.effectiveBeats(for: .calm, beatInterval: 0.5) == 3) + #expect(planner.effectiveBeats(for: .intense, beatInterval: 0.5) == 1) + + // 最短 3秒 → 1拍(0.5秒)は倍々にして 8拍(4秒)。最長は外す。 + planner.maximumCutDuration = nil + planner.minimumCutDuration = 3 + #expect(planner.effectiveBeats(for: .intense, beatInterval: 0.5) == 8) + } + + @Test + func maximumCutDurationShortensLongCuts() throws { + let analysis = makeAnalysis() + let pool = [motionProfile(motion: 0.5), motionProfile(motion: 0.5), motionProfile(motion: 0.5)] + + // 控えめだと静かな所は8拍(4秒)。最長を決めなければ 1.5 秒を超えるカットがある。 + let unlimited = try plan(analysis, pool: pool, style: .relaxed) + #expect(unlimited.cuts.contains { $0.duration > 1.5 + 1e-9 }) + + var tuning = MusicVideoCutTuning() + tuning.setMaximum(1.5) + let limited = try plan(analysis, pool: pool, style: .relaxed, tuning: tuning) + #expect(limited.cuts.allSatisfy { $0.duration <= 1.5 + 1e-9 }) + #expect(limited.cuts.count > unlimited.cuts.count) + // 短くしても、曲の全体を隙間なく覆う。 + #expect(limited.cuts.first?.timelineStart == 0) + #expect(abs((limited.cuts.last?.timelineEnd ?? 0) - analysis.duration) < 1e-9) + } + + @Test + func minimumCutDurationLengthensFastCuts() throws { + // 0.25秒間隔(テンポ240)。標準の「盛り上がり」は1拍=0.25秒で、最短(0.3秒)に足りないので倍になる。 + let analysis = makeAnalysis(beatInterval: 0.25) + let pool = [motionProfile(motion: 0.5), motionProfile(motion: 0.5), motionProfile(motion: 0.5)] + + var tuning = MusicVideoCutTuning() + tuning.setMinimum(1.0) + let result = try plan(analysis, pool: pool, tuning: tuning) + + // 最初(導入部)と最後(曲の終わり)を除き、1秒に満たないカットは無い。小節に揃える途中でも守られる。 + let inner = result.cuts.dropFirst().dropLast() + #expect(!inner.isEmpty) + #expect(inner.allSatisfy { $0.duration >= 1.0 - 1e-9 }) + + let defaultPlan = try plan(analysis, pool: pool) + #expect(result.cuts.count < defaultPlan.cuts.count) + } + + @Test + func minimumAndMaximumStayConsistent() { + var tuning = MusicVideoCutTuning() + tuning.setMaximum(2.0) + tuning.setMinimum(3.0) + #expect(tuning.maximumCutDuration == 3.0) // 最短が最長を超えるなら、最長も延びる + + tuning.setMaximum(1.0) + #expect(tuning.minimumCutDuration == 1.0) // 最長が最短を下回るなら、最短も縮む + + tuning.setMaximum(nil) + #expect(tuning.maximumCutDuration == nil) + #expect(tuning.minimumCutDuration == 1.0) + } + + @Test + func freeAlignmentCutsExactlyTheChosenNumberOfBeats() throws { + let analysis = makeAnalysis() + let pool = [motionProfile(motion: 0.5), motionProfile(motion: 0.5), motionProfile(motion: 0.5)] + + var tuning = MusicVideoCutTuning() + tuning.alignment = .free + let free = try plan(analysis, pool: pool, tuning: tuning) + let aligned = try plan(analysis, pool: pool) + + // 拍の数どおり: 標準は 静か=2.0秒・中=1.0秒・盛り上がり=0.5秒のどれかだけ(最初と最後を除く)。 + for cut in free.cuts.dropFirst().dropLast() { + #expect([2.0, 1.0, 0.5].contains { abs($0 - cut.duration) < 1e-9 }) + } + // 40秒で「盛り上がり」から「中」(2拍=1.0秒)に変わる。拍の数どおりなら、その 40.0 秒からぴったり1.0秒。 + func cut(at time: Double, in plan: CutPlan) -> PlannedCut? { + plan.cuts.first { abs($0.timelineStart - time) < 1e-9 } + } + #expect(cut(at: 40.0, in: free)?.duration == 1.0) + // 区切りにそろえると、2拍のカットは区切り(拍の偶数番目)から始めるので、40.0 秒は半端な0.5秒になり、 + // 1.0秒のカットはその次(40.5 秒)から始まる。 + #expect(cut(at: 40.0, in: aligned)?.duration == 0.5) + #expect(cut(at: 40.5, in: aligned)?.duration == 1.0) + #expect(free != aligned) + } + + @Test + func motionMatchingStrengthChangesHowCloselyMotionFollowsTheSong() throws { + // 動きの少ない動画と、多い動画を同数。曲の真ん中は「盛り上がり」(狙いは動きが大きい)。 + let calmVideos = (0..<5).map { _ in motionProfile(motion: 0.1) } + let busyVideos = (0..<5).map { _ in motionProfile(motion: 0.9) } + let pool = calmVideos + busyVideos + let analysis = makeAnalysis(intensityAt: { _ in .intense }) + + func averageMatch(_ matching: MotionMatching) throws -> Double { + var total = 0.0 + for seed in 1...5 as ClosedRange { + var tuning = MusicVideoCutTuning() + tuning.motionMatching = matching + let result = try plan(analysis, pool: pool, tuning: tuning, seed: seed) + total += try #require(MusicVideoPlanStats(plan: result, pool: pool, analysis: analysis).motionMatch) + } + return total / 5 + } + + let strong = try averageMatch(.strong) + let standard = try averageMatch(.standard) + let off = try averageMatch(.off) + #expect(strong > 0.95) + #expect(strong >= standard - 1e-9) + // 合わせないと、動きの少ない動画も混ざるので一致度が下がる。 + #expect(off < strong - 0.2) + } + + @Test + func varietyChangesHowOftenTheSameVideosAreReused() throws { + // 動きの大きさが少しずつ違う12本。動きを強く合わせる設定で、使い回しの差が出る。 + let pool = (0..<12).map { motionProfile(motion: Double($0) / 11) } + let analysis = makeAnalysis(duration: 120) + + func usage(_ variety: VideoVariety) throws -> (distinct: Int, topShare: Double) { + var distinctTotal = 0 + var topShareTotal = 0.0 + for seed in 1...6 as ClosedRange { + var tuning = MusicVideoCutTuning() + tuning.variety = variety + tuning.motionMatching = .strong + let result = try plan(analysis, pool: pool, tuning: tuning, seed: seed) + var counts: [UUID: Int] = [:] + for cut in result.cuts { counts[cut.videoID, default: 0] += 1 } + distinctTotal += counts.count + topShareTotal += Double(counts.values.max() ?? 0) / Double(result.cuts.count) + } + return (distinctTotal, topShareTotal / 6) + } + + let wide = try usage(.wide) + let standard = try usage(.standard) + let repeating = try usage(.repeating) + #expect(wide.distinct >= standard.distinct) + #expect(standard.distinct >= repeating.distinct) + #expect(wide.distinct > repeating.distinct) + // 使い回しを許すと、よく使う動画に偏る。 + #expect(repeating.topShare > wide.topShare) + } + + @Test + func replacingACutHonoursTheSameTuning() throws { + let analysis = makeAnalysis() + let pool = (0..<6).map { motionProfile(motion: Double($0) / 5) } + var tuning = MusicVideoCutTuning() + tuning.variety = .wide + let planner = CutPlanner(style: .standard, tuning: tuning) + let original = try planner.plan(analysis: analysis, pool: pool, seed: 3) + + let replaced = try planner.replaceCut(at: 4, in: original, analysis: analysis, pool: pool, seed: 9) + // 差し替えても、カットの枠(位置と長さ)は変わらない。 + #expect(replaced.cuts.count == original.cuts.count) + #expect(replaced.cuts[4].timelineStart == original.cuts[4].timelineStart) + #expect(replaced.cuts[4].duration == original.cuts[4].duration) + } +} + +// MARK: - 曲の範囲 + +struct MusicRangeTests { + @Test + func trimmingShiftsBeatsAndSlicesTheEnergy() { + let analysis = makeAnalysis(duration: 60) // 拍は 0.5, 1.0, … / 0〜20秒は静か、20〜40秒は盛り上がり + let range = MusicRange(start: 18, end: 42) + let trimmed = analysis.trimmed(to: range) + + #expect(trimmed.duration == 24) + #expect(trimmed.tempo == analysis.tempo) + // 拍は範囲の先頭が 0 秒になるようにずれ、範囲の外の拍は消える。 + #expect(trimmed.beats.first == 0) // 元の 18.0 秒の拍 + #expect(trimmed.beats.allSatisfy { $0 >= 0 && $0 < 24 }) + #expect(trimmed.beats.count == 48) + // 盛り上がりの段階も、範囲に合わせてずれる(18〜20秒は静か、20〜40秒は盛り上がり、40秒以降は中)。 + #expect(trimmed.intensity(at: 1) == .calm) + #expect(trimmed.intensity(at: 3) == .intense) + #expect(trimmed.intensity(at: 23) == .medium) + #expect(trimmed.energy.count == 24) + } + + @Test + func clampedRangesStayInsideTheSongAndKeepAMinimumLength() { + // 全体と同じなら範囲なし。 + #expect(MusicRange.clamped(start: 0, end: 60, songDuration: 60) == nil) + #expect(MusicRange.clamped(start: -5, end: 80, songDuration: 60) == nil) + + let inside = MusicRange.clamped(start: 10, end: 30, songDuration: 60) + #expect(inside == MusicRange(start: 10, end: 30)) + + // 短すぎるときは、最短の長さまで広げる。 + let tiny = MusicRange.clamped(start: 10, end: 11, songDuration: 60) + #expect(tiny == MusicRange(start: 10, end: 15)) + + // 曲の終わりを越える開始は、最短の長さが残る位置まで戻す。 + let late = MusicRange.clamped(start: 59, end: 60, songDuration: 60) + #expect(late == MusicRange(start: 55, end: 60)) + } + + @Test + func nearestBeatSnapsAStartTimeToTheBeatGrid() { + let analysis = makeAnalysis(duration: 30) + #expect(analysis.nearestBeat(to: 10.2) == 10.0) + #expect(analysis.nearestBeat(to: 10.3) == 10.5) + } +} + +// MARK: - 結果の数値 + +struct MusicVideoPlanStatsTests { + @Test + func statsDescribeTheCutsAndTheVideosUsed() { + let first = UUID(), second = UUID(), unused = UUID() + let plan = CutPlan( + cuts: [ + plannedCut(first, from: 0, at: 0, length: 1), + plannedCut(second, from: 0, at: 1, length: 2), + plannedCut(first, from: 5, at: 3, length: 3) + ], + duration: 6 + ) + let pool = [ + motionProfile(first, motion: 0.5), + motionProfile(second, motion: 0.5), + motionProfile(unused, motion: 0.5) + ] + let stats = MusicVideoPlanStats(plan: plan, pool: pool, analysis: nil) + + #expect(stats.cutCount == 3) + #expect(abs(stats.averageCutDuration - 2.0) < 1e-9) + #expect(stats.shortestCutDuration == 1) + #expect(stats.longestCutDuration == 3) + #expect(stats.usedVideoCount == 2) + #expect(stats.poolVideoCount == 3) + #expect(stats.motionMatch == nil) // 曲の解析が無ければ調べられない + } + + @Test + func changeSummaryNamesOnlyWhatChanged() { + func stats(cuts: Int, average: Double, used: Int, match: Double?) -> MusicVideoPlanStats { + let id = UUID() + var result = MusicVideoPlanStats( + plan: CutPlan(cuts: [plannedCut(id, from: 0, at: 0, length: 1)], duration: 1), + pool: [], + analysis: nil + ) + result.cutCount = cuts + result.averageCutDuration = average + result.usedVideoCount = used + result.motionMatch = match + return result + } + + let summary = MusicVideoChangeSummary( + title: "最長のカット", + before: stats(cuts: 64, average: 1.4, used: 9, match: 0.80), + after: stats(cuts: 48, average: 1.9, used: 9, match: 0.78) + ) + #expect(summary.text == "「最長のカット」を変えました:カット 64 → 48・平均 1.4秒 → 1.9秒・動きの一致 80% → 78%") + + let same = MusicVideoChangeSummary( + title: "画面の合わせ方", + before: stats(cuts: 10, average: 2, used: 5, match: 0.5), + after: stats(cuts: 10, average: 2, used: 5, match: 0.5) + ) + #expect(same.text.contains("大きな違いはありません")) + } +} + +// MARK: - 保存 + +struct MusicVideoTuningPreferencesTests { + @Test + func oldSavedPreferencesStillLoadWithDefaultTuning() throws { + let legacy = #"{"cutStyle":"energetic","renderPreset":"landscapeHD","exportQuality":"standard"}"# + let decoded = try JSONDecoder().decode(MusicVideoPreferences.self, from: Data(legacy.utf8)) + #expect(decoded.cutStyle == .energetic) + #expect(decoded.cutTuning == MusicVideoCutTuning()) + #expect(decoded.lookTuning == MusicVideoLookTuning()) + } + + @Test + func tuningSurvivesASaveAndLoad() throws { + var preferences = MusicVideoPreferences() + preferences.cutTuning.setMaximum(3.0) + preferences.cutTuning.motionMatching = .strong + preferences.cutTuning.variety = .wide + preferences.cutTuning.alignment = .free + preferences.lookTuning.fitMode = .fit + preferences.lookTuning.transition = .crossfade + preferences.lookTuning.fadeSeconds = 1 + + let data = try JSONEncoder().encode(preferences) + let decoded = try JSONDecoder().decode(MusicVideoPreferences.self, from: data) + #expect(decoded == preferences) + } +} + +// MARK: - 合成: 画面の合わせ方・切り替え効果・フェード・曲の範囲 + +/// 合成した映像の、`seconds` 秒の位置のフレームの明るさ(4x4の区画ごと)。 +private func lumaCells(of composed: MusicVideoComposition, at seconds: Double) async throws -> [Double] { + let generator = AVAssetImageGenerator(asset: composed.composition) + generator.videoComposition = composed.videoComposition + generator.requestedTimeToleranceBefore = .zero + generator.requestedTimeToleranceAfter = .zero + let (image, _) = try await generator.image(at: CMTime(seconds: seconds, preferredTimescale: 600)) + return lumaGrid(image) +} + +private func average(_ values: [Double]) -> Double { + values.isEmpty ? 0 : values.reduce(0, +) / Double(values.count) +} + +/// 合成した音の、`start` 秒から `length` 秒の大きさ(RMS)。フェードの指定(audioMix)も反映する。 +private func audioRMS(of composed: MusicVideoComposition, from start: Double, length: Double) throws -> Double { + let reader = try AVAssetReader(asset: composed.composition) + let tracks = composed.composition.tracks(withMediaType: .audio) + let output = AVAssetReaderAudioMixOutput( + audioTracks: tracks, + audioSettings: [ + AVFormatIDKey: kAudioFormatLinearPCM, + AVLinearPCMBitDepthKey: 32, + AVLinearPCMIsFloatKey: true, + AVLinearPCMIsBigEndianKey: false, + AVLinearPCMIsNonInterleaved: false, + AVSampleRateKey: 44_100.0, + 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 sum = 0.0 + var count = 0 + while let buffer = output.copyNextSampleBuffer() { + guard let block = CMSampleBufferGetDataBuffer(buffer) else { continue } + let total = CMBlockBufferGetDataLength(block) + var data = [UInt8](repeating: 0, count: total) + CMBlockBufferCopyDataBytes(block, atOffset: 0, dataLength: total, destination: &data) + data.withUnsafeBytes { raw in + for value in raw.bindMemory(to: Float.self) { + sum += Double(value * value) + count += 1 + } + } + } + return count == 0 ? 0 : (sum / Double(count)).squareRoot() +} + +@Suite(.serialized) +struct MusicVideoLookCompositionTests { + private let render = MusicVideoRenderSettings(width: 320, height: 180, framesPerSecond: 30) + + private struct Fixture { + let directory: URL + let dark: UUID, bright: UUID, portrait: UUID + let urls: [UUID: URL] + let music: URL + } + + /// 暗い(30)・明るい(230)・縦長(中間の200)の素材と、6秒の音楽。 + private func makeFixture() async throws -> Fixture { + let directory = try temporaryDirectory("look") + let darkURL = directory.appendingPathComponent("dark.mp4") + let brightURL = directory.appendingPathComponent("bright.mp4") + let portraitURL = directory.appendingPathComponent("portrait.mp4") + let musicURL = directory.appendingPathComponent("music.wav") + try await step("dark video") { try await makeTestVideo(at: darkURL, duration: 8) { _ in 30 } } + try await step("bright video") { try await makeTestVideo(at: brightURL, duration: 8) { _ in 230 } } + try await step("portrait video") { try await makeTestVideo(at: portraitURL, duration: 8, size: (90, 160)) { _ in 200 } } + try await step("music") { try writeSineWAV(to: musicURL, duration: 8) } + let dark = UUID(), bright = UUID(), portrait = UUID() + return Fixture( + directory: directory, + dark: dark, bright: bright, portrait: portrait, + urls: [dark: darkURL, bright: brightURL, portrait: portraitURL], + music: musicURL + ) + } + + private func compose( + _ plan: CutPlan, + fixture: Fixture, + look: MusicVideoLookTuning, + audioStart: Double = 0 + ) async throws -> MusicVideoComposition { + try await step("compose") { + try await MusicVideoComposer().makeComposition( + plan: plan, sourceURLs: fixture.urls, audioURL: fixture.music, render: render, look: look, audioStart: audioStart + ) + } + } + + /// 暗い → 明るい → 暗い、各1.5秒。 + private func darkBrightDarkPlan(_ fixture: Fixture) -> CutPlan { + CutPlan( + cuts: [ + plannedCut(fixture.dark, from: 0, at: 0, length: 1.5), + plannedCut(fixture.bright, from: 1, at: 1.5, length: 1.5), + plannedCut(fixture.dark, from: 3, at: 3, length: 1.5) + ], + duration: 4.5 + ) + } + + /// 指示の時間が、0 秒から合成の終わりまで、隙間も重なりもなく続いている。 + private func expectContiguousInstructions(_ composed: MusicVideoComposition) { + let instructions = composed.videoComposition.instructions + #expect(!instructions.isEmpty) + #expect(instructions.first?.timeRange.start == .zero) + for (current, next) in zip(instructions, instructions.dropFirst()) { + #expect(current.timeRange.end == next.timeRange.start) + } + #expect(instructions.last?.timeRange.end == composed.composition.duration) + } + + @Test + func defaultLookKeepsOneTrackAndOneInstruction() async throws { + let fixture = try await makeFixture() + defer { try? FileManager.default.removeItem(at: fixture.directory) } + + let composed = try await compose(darkBrightDarkPlan(fixture), fixture: fixture, look: MusicVideoLookTuning()) + #expect(composed.composition.tracks(withMediaType: .video).count == 1) + #expect(composed.videoComposition.instructions.count == 1) + #expect(composed.audioMix == nil) + expectContiguousInstructions(composed) + } + + @Test + func fitModeShowsTheWholeSourceWithBlackBars() async throws { + let fixture = try await makeFixture() + defer { try? FileManager.default.removeItem(at: fixture.directory) } + let plan = CutPlan(cuts: [plannedCut(fixture.portrait, from: 1, at: 0, length: 2)], duration: 2) + + var look = MusicVideoLookTuning() + look.fitMode = .fill + let fill = try await lumaCells(of: compose(plan, fixture: fixture, look: look), at: 1) + // 画面いっぱい: 四隅まで素材で埋まる(縦長の素材を拡大するので、黒帯は出ない)。 + #expect(fill.allSatisfy { $0 > 150 }) + + look.fitMode = .fit + let fit = try await lumaCells(of: compose(plan, fixture: fixture, look: look), at: 1) + // 全体を見せる: 縦長の素材は左右に黒帯が出て、中央だけが明るい。 + for row in 0..<4 { + #expect(fit[row * 4 + 0] < 40, "左端は黒帯") + #expect(fit[row * 4 + 3] < 40, "右端は黒帯") + #expect(fit[row * 4 + 1] > 90 && fit[row * 4 + 2] > 90, "中央は素材") + } + } + + @Test + func crossfadeBlendsAcrossTheBeatUsingTwoTracks() async throws { + let fixture = try await makeFixture() + defer { try? FileManager.default.removeItem(at: fixture.directory) } + + var look = MusicVideoLookTuning() + look.transition = .crossfade + let composed = try await compose(darkBrightDarkPlan(fixture), fixture: fixture, look: look) + + #expect(composed.composition.tracks(withMediaType: .video).count == 2) + expectContiguousInstructions(composed) + #expect(abs(composed.duration - 4.5) < 0.02) + + // 拍(1.5秒)の前は暗く、後は明るい。拍の位置は、2つの映像がほぼ半分ずつ混ざる(暗30と明230の中間)。 + let before = average(try await lumaCells(of: composed, at: 1.0)) + let atBeat = average(try await lumaCells(of: composed, at: 1.5)) + let after = average(try await lumaCells(of: composed, at: 2.0)) + #expect(before < 60) + #expect(after > 190) + #expect(atBeat > 100 && atBeat < 160) + // 切り替えの途中は、明るさがなめらかに変わる(切り替えの頭より後ろのほうが明るい)。 + let early = average(try await lumaCells(of: composed, at: 1.4)) + let late = average(try await lumaCells(of: composed, at: 1.6)) + #expect(early < atBeat && atBeat < late) + } + + @Test + func flashLightsTheStartOfEachCutThenSettles() async throws { + let fixture = try await makeFixture() + defer { try? FileManager.default.removeItem(at: fixture.directory) } + // 暗い素材だけ。普通の切り替えなら、どこも暗いまま。 + let plan = CutPlan( + cuts: [ + plannedCut(fixture.dark, from: 0, at: 0, length: 1.5), + plannedCut(fixture.dark, from: 3, at: 1.5, length: 1.5) + ], + duration: 3 + ) + var look = MusicVideoLookTuning() + look.transition = .flash + let composed = try await compose(plan, fixture: fixture, look: look) + + #expect(composed.composition.tracks(withMediaType: .video).count == 1) + expectContiguousInstructions(composed) + + let beforeBeat = average(try await lumaCells(of: composed, at: 1.0)) + let justAfterBeat = average(try await lumaCells(of: composed, at: 1.52)) + let settled = average(try await lumaCells(of: composed, at: 1.8)) + #expect(beforeBeat < 60) + #expect(justAfterBeat > 170, "拍の直後は、白く光っている") + #expect(settled < 60, "光ったあとは、素材の明るさに戻る") + + // 最初のカットの頭は光らない(曲の始まりで光らせない)。 + let start = average(try await lumaCells(of: composed, at: 0.02)) + #expect(start < 60) + } + + @Test + func fadeDarkensTheEdgesOfTheVideoAndTheMusic() async throws { + let fixture = try await makeFixture() + defer { try? FileManager.default.removeItem(at: fixture.directory) } + let plan = CutPlan(cuts: [plannedCut(fixture.bright, from: 0, at: 0, length: 5)], duration: 5) + + var look = MusicVideoLookTuning() + look.fadeSeconds = 1 + let composed = try await compose(plan, fixture: fixture, look: look) + expectContiguousInstructions(composed) + + // 映像: 最初と最後は暗く、真ん中は素材の明るさ。 + let first = average(try await lumaCells(of: composed, at: 0.05)) + let middle = average(try await lumaCells(of: composed, at: 2.5)) + let last = average(try await lumaCells(of: composed, at: 4.95)) + #expect(first < 40) + #expect(middle > 190) + #expect(last < 40) + + // 音: 最初と最後の 0.1 秒は、真ん中よりずっと小さい。 + #expect(composed.audioMix != nil) + let audioFirst = try audioRMS(of: composed, from: 0, length: 0.1) + let audioMiddle = try audioRMS(of: composed, from: 2, length: 0.5) + let audioLast = try audioRMS(of: composed, from: 4.9, length: 0.1) + #expect(audioMiddle > 0.1) + #expect(audioFirst < audioMiddle * 0.25) + #expect(audioLast < audioMiddle * 0.25) + } + + @Test + func fadeAndTransitionsDoNotConflictOnShortCuts() async throws { + let fixture = try await makeFixture() + defer { try? FileManager.default.removeItem(at: fixture.directory) } + // 0.5秒ごとに替わるカットで、フェード(2秒)と切り替え効果が重なる。 + let cuts = (0..<8).map { index in + plannedCut(index % 2 == 0 ? fixture.dark : fixture.bright, from: Double(index) * 0.2, at: Double(index) * 0.5, length: 0.5) + } + let plan = CutPlan(cuts: cuts, duration: 4) + + for transition in MusicVideoTransition.allCases { + var look = MusicVideoLookTuning() + look.transition = transition + look.fadeSeconds = 2 + let composed = try await compose(plan, fixture: fixture, look: look) + expectContiguousInstructions(composed) + #expect(abs(composed.duration - 4) < 0.02) + // フェードの頂点(2秒)では、素材の明るさがそのまま出る(暗か明のどちらか)。 + let top = average(try await lumaCells(of: composed, at: 2.1)) + #expect(top < 60 || top > 170) + // 最初のフレームは、どの切り替え効果でも暗い。 + let start = average(try await lumaCells(of: composed, at: 0.03)) + #expect(start < 40) + } + } + + /// 画素は横長のまま、90度の回転情報だけを持つ素材(スマートフォンで縦に撮った動画と同じ作り)。 + /// 表示すると縦長(90x160)になる。 + private func makeRotatedPortraitVideo(at url: URL, brightness: UInt8) async throws { + // 画素 160x90 を、時計回りに90度回して表示する(回転後は 90x160 の縦長)。 + let rotate = CGAffineTransform(a: 0, b: 1, c: -1, d: 0, tx: 90, ty: 0) + try await makeTestVideo(at: url, duration: 8, size: (160, 90), transform: rotate) { _ in brightness } + } + + @Test + func firstSourceOrientationDoesNotDecideTheFrameOfLaterCuts() async throws { + let fixture = try await makeFixture() + defer { try? FileManager.default.removeItem(at: fixture.directory) } + let rotatedURL = fixture.directory.appendingPathComponent("rotated.mp4") + try await step("rotated video") { try await makeRotatedPortraitVideo(at: rotatedURL, brightness: 200) } + let rotated = UUID() + let urls = fixture.urls.merging([rotated: rotatedURL]) { current, _ in current } + let fixtureWithRotated = Fixture( + directory: fixture.directory, dark: fixture.dark, bright: fixture.bright, portrait: fixture.portrait, + urls: urls, music: fixture.music + ) + + // 最初が縦向きの素材で、そのあとに横向きの素材が続く。画面は横長(320x180)。 + let plan = CutPlan( + cuts: [ + plannedCut(rotated, from: 1, at: 0, length: 1.5), + plannedCut(fixture.dark, from: 0, at: 1.5, length: 1.5), + plannedCut(rotated, from: 3, at: 3, length: 1.5), + plannedCut(fixture.bright, from: 0, at: 4.5, length: 1.5) + ], + duration: 6 + ) + + for transition in [MusicVideoTransition.cut, .crossfade, .flash] { + var look = MusicVideoLookTuning() + look.transition = transition + look.fitMode = .fill + let composed = try await compose(plan, fixture: fixtureWithRotated, look: look) + #expect(composed.videoComposition.renderSize == render.size, "\(transition)") + + // 画面いっぱいの設定なら、どのカットも四隅まで素材で埋まる(最初の素材の向きに引きずられない)。 + let first = try await lumaCells(of: composed, at: 0.75) + let second = try await lumaCells(of: composed, at: 2.25) + let third = try await lumaCells(of: composed, at: 3.75) + let fourth = try await lumaCells(of: composed, at: 5.25) + #expect(first.allSatisfy { $0 > 150 && $0 < 240 }, "\(transition) 縦向き(1つ目)") + #expect(second.allSatisfy { $0 < 80 }, "\(transition) 横向き(2つ目)") + #expect(third.allSatisfy { $0 > 150 && $0 < 240 }, "\(transition) 縦向き(3つ目)") + #expect(fourth.allSatisfy { $0 > 190 }, "\(transition) 横向き(4つ目)") + } + + // 全体を見せる設定なら、縦向きの素材だけ左右に黒帯が出て、横向きの素材は帯なし。 + var fit = MusicVideoLookTuning() + fit.fitMode = .fit + let composed = try await compose(plan, fixture: fixtureWithRotated, look: fit) + let portraitCells = try await lumaCells(of: composed, at: 0.75) + let landscapeCells = try await lumaCells(of: composed, at: 2.25) + for row in 0..<4 { + #expect(portraitCells[row * 4] < 40 && portraitCells[row * 4 + 3] < 40, "縦向きは左右が黒帯") + } + #expect(landscapeCells.allSatisfy { $0 > 10 && $0 < 80 }, "横向きは帯なし(暗い素材そのまま)") + } + + @Test + func musicStartOffsetPlaysTheChosenPartOfTheSong() async throws { + let fixture = try await makeFixture() + defer { try? FileManager.default.removeItem(at: fixture.directory) } + // 前半の 3 秒は無音、その後はずっと音がある曲。 + let sampleRate = 44_100.0 + let samples: [Float] = (0.. 0.1) + #expect(abs(fromThree.duration - 4) < 0.05) + } + + @Test + func crossfadeWithFadeExportsAPlayableMP4() async throws { + let fixture = try await makeFixture() + defer { try? FileManager.default.removeItem(at: fixture.directory) } + + var look = MusicVideoLookTuning() + look.transition = .crossfade + look.fitMode = .fit + look.fadeSeconds = 0.5 + let composed = try await compose(darkBrightDarkPlan(fixture), fixture: fixture, look: look) + + let output = fixture.directory.appendingPathComponent("out/result.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) + #expect(abs(try await asset.load(.duration).seconds - 4.5) < 0.2) + } +} + +// MARK: - ビューモデル: 項目を変えたときの反映 + +private struct WaitTimeout: Error, CustomStringConvertible { + let label: String + var description: String { "待っていた状態にならないまま時間切れ: \(label)" } +} + +@Suite(.serialized) +@MainActor +struct MusicVideoTuningViewModelTests { + private struct Harness { + let directory: URL + let suite: String + let defaults: UserDefaults + let library: LibraryViewModel + let viewModel: MusicVideoViewModel + + func cleanUp() { + defaults.removePersistentDomain(forName: suite) + try? FileManager.default.removeItem(at: directory) + } + } + + /// 曲(120BPM・16秒)を解析し終えた状態の画面と、`videoCount` 本の素材動画を持つライブラリを作る。 + /// 設定の保存先も、ライブラリの置き場も、テスト専用の場所にする(実際のものには触らない)。 + private func makeHarness(videoCount: Int) async throws -> Harness { + let directory = try temporaryDirectory("tuning-vm") + let suite = "musicvideo-vm-tests-\(UUID().uuidString)" + let defaults = try #require(UserDefaults(suiteName: suite)) + + let musicURL = directory.appendingPathComponent("music.wav") + let clicks = evenClicks(from: 0.25, interval: 0.5, until: 16) + try writeMonoWAV( + samples: clickTrack(duration: 16, clicks: clicks.map { ($0, 0.8) }), + sampleRate: testSampleRate, + to: musicURL + ) + + var items: [VideoItem] = [] + for index in 0.. Bool + ) async throws { + let deadline = Date().addingTimeInterval(timeout) + while !condition() { + if Date() > deadline { throw WaitTimeout(label: label) } + try await Task.sleep(for: .milliseconds(40)) + } + } + + /// 映像を作り終えるまで待つ。 + private func generate(_ harness: Harness) async throws { + harness.viewModel.generate(dataManager: harness.library) + try await waitUntil("映像の作成") { harness.viewModel.phase == .ready && harness.viewModel.plan != nil } + } + + @Test + func tuningRebuildsTheCutsWithTheSameSeedAndCanBeUndone() async throws { + let harness = try await makeHarness(videoCount: 4) + defer { harness.cleanUp() } + let viewModel = harness.viewModel + try await generate(harness) + let original = try #require(viewModel.plan) + #expect(viewModel.undoDepth == 0) + #expect(viewModel.planStats?.cutCount == original.cuts.count) + + // 最長を1.0秒にすると、すぐにカット割りが作り直される。 + viewModel.cutTuning.setMaximum(1.0) + try await waitUntil("最長1.0秒の反映") { viewModel.plan != original && !viewModel.isApplyingEdit } + let limited = try #require(viewModel.plan) + #expect(limited.cuts.allSatisfy { $0.duration <= 1.0 + 1e-9 }) + #expect(limited.cuts.count > original.cuts.count) + #expect(viewModel.lastChangeNote?.contains("最長のカット長") == true) + #expect(viewModel.lastChangeNote?.contains("カット \(original.cuts.count) → \(limited.cuts.count)") == true) + #expect(viewModel.planStats?.cutCount == limited.cuts.count) + #expect(viewModel.undoDepth == 1) + + // 乱数の種は変えないので、制限を外せば、まったく同じカット割りに戻る(項目の効果だけが出ている)。 + viewModel.cutTuning.setMaximum(nil) + try await waitUntil("制限を外した反映") { viewModel.plan == original && !viewModel.isApplyingEdit } + #expect(viewModel.undoDepth == 2) + + // 取り消すと、カット割りと一緒に、項目も元に戻る。 + viewModel.undo() + try await waitUntil("取り消し1回目") { viewModel.plan == limited && !viewModel.isApplyingEdit } + #expect(viewModel.cutTuning.maximumCutDuration == 1.0) + viewModel.undo() + try await waitUntil("取り消し2回目") { viewModel.plan == original && !viewModel.isApplyingEdit } + #expect(viewModel.cutTuning.maximumCutDuration == nil) + #expect(viewModel.undoDepth == 0) + #expect(viewModel.redoDepth == 2) + + // 取り消しで項目を戻したことは、新しい変更として反映し直されない。 + try await Task.sleep(for: .milliseconds(600)) + #expect(viewModel.plan == original) + #expect(viewModel.undoDepth == 0) + } + + @Test + func rapidChangesAreAppliedOnceAndUndoneTogether() async throws { + let harness = try await makeHarness(videoCount: 4) + defer { harness.cleanUp() } + let viewModel = harness.viewModel + try await generate(harness) + let original = try #require(viewModel.plan) + + // つまみを動かすような連続した変更は、まとめて1回だけ反映する。 + viewModel.cutTuning.setMaximum(6.0) + viewModel.cutTuning.setMaximum(3.0) + viewModel.cutTuning.setMaximum(1.5) + try await waitUntil("連続した変更の反映") { viewModel.plan != original && !viewModel.isApplyingEdit } + try await Task.sleep(for: .milliseconds(500)) + #expect(viewModel.undoDepth == 1) + #expect(viewModel.plan?.cuts.allSatisfy { $0.duration <= 1.5 + 1e-9 } == true) + + viewModel.undo() + try await waitUntil("まとめて取り消し") { viewModel.plan == original && !viewModel.isApplyingEdit } + #expect(viewModel.cutTuning.maximumCutDuration == nil) + } + + @Test + func changingTheScreenSizeRecomposesTheExistingVideo() async throws { + let harness = try await makeHarness(videoCount: 3) + defer { harness.cleanUp() } + let viewModel = harness.viewModel + try await generate(harness) + let original = try #require(viewModel.plan) + #expect(viewModel.player.currentItem?.videoComposition?.renderSize == CGSize(width: 1920, height: 1080)) + + // 画面サイズを変えると、作り直さなくても、映像そのものの大きさが変わる。カット割りはそのまま。 + viewModel.renderPreset = .portraitHD + try await waitUntil("画面サイズの反映") { + viewModel.player.currentItem?.videoComposition?.renderSize == CGSize(width: 720, height: 1280) + && !viewModel.isApplyingEdit + } + #expect(viewModel.plan == original) + #expect(viewModel.undoDepth == 0) + #expect(viewModel.lastChangeNote?.contains("画面サイズ") == true) + + // 切り替え効果を変えると、合成だけがやり直される(クロスフェードは映像トラックを2本使う)。 + viewModel.lookTuning.transition = .crossfade + try await waitUntil("切り替え効果の反映") { + (viewModel.player.currentItem?.asset as? AVComposition)?.tracks(withMediaType: .video).count == 2 + && !viewModel.isApplyingEdit + } + #expect(viewModel.plan == original) + } + + @Test + func musicRangeTrimsThePlanAndIsUndoable() async throws { + let harness = try await makeHarness(videoCount: 4) + defer { harness.cleanUp() } + let viewModel = harness.viewModel + try await generate(harness) + let original = try #require(viewModel.plan) + let fullDuration = try #require(viewModel.fullAnalysis?.duration) + #expect(viewModel.targetDuration == fullDuration) + + viewModel.setMusicRange(start: 4, end: 12) + try await waitUntil("曲の範囲の反映") { viewModel.plan != original && !viewModel.isApplyingEdit } + let range = try #require(viewModel.musicRange) + let trimmed = try #require(viewModel.plan) + // 開始は拍にそろう(拍は0.25秒+0.5秒ごと)。映像の長さは、範囲の長さと一致する。 + #expect(abs(range.start - 4) <= 0.26) + #expect(abs(range.length - 8) <= 0.5) + #expect(abs(trimmed.duration - range.length) < 1e-9) + #expect(abs((viewModel.analysis?.duration ?? 0) - range.length) < 1e-9) + #expect(viewModel.targetDuration == range.length) + #expect(abs((viewModel.player.currentItem?.asset.duration.seconds ?? 0) - range.length) < 0.1) + + viewModel.undo() + try await waitUntil("範囲の取り消し") { viewModel.plan == original && !viewModel.isApplyingEdit } + #expect(viewModel.musicRange == nil) + #expect(viewModel.analysis?.duration == fullDuration) + #expect(viewModel.targetDuration == fullDuration) + } + + @Test + func sourceLimitDecidesHowManyVideosAreAnalysed() async throws { + let harness = try await makeHarness(videoCount: 12) + defer { harness.cleanUp() } + let viewModel = harness.viewModel + + viewModel.sourceLimit = 10 + try await generate(harness) + #expect(viewModel.poolVideos.count == 10) + #expect(!viewModel.sourceLimitNeedsRebuild) + + // 本数を増やしても、「作り直す」まではいまの映像のまま。反映が必要なことは分かる。 + let before = viewModel.plan + viewModel.sourceLimit = 20 + #expect(viewModel.sourceLimitNeedsRebuild) + try await Task.sleep(for: .milliseconds(500)) + #expect(viewModel.plan == before) + #expect(viewModel.poolVideos.count == 10) + + try await generate(harness) + #expect(viewModel.poolVideos.count == 12) + #expect(!viewModel.sourceLimitNeedsRebuild) + } + + @Test + func skipMovesThePlaybackPositionAndStaysInsideTheVideo() async throws { + let harness = try await makeHarness(videoCount: 4) + defer { harness.cleanUp() } + let viewModel = harness.viewModel + try await generate(harness) + let plan = try #require(viewModel.plan) + #expect(viewModel.playbackDuration == plan.duration) + #expect(!viewModel.isPlaying) + + viewModel.skip(by: 10) + try await waitUntil("10秒進む") { abs(viewModel.playbackTime - 10) < 0.2 } + viewModel.skip(by: -4) + try await waitUntil("4秒戻る") { abs(viewModel.playbackTime - 6) < 0.2 } + + // 映像の範囲の外へは出ない。 + viewModel.skip(by: -100) + try await waitUntil("先頭で止まる") { viewModel.playbackTime < 0.1 } + viewModel.skip(by: 1000) + try await waitUntil("終わりで止まる") { viewModel.playbackTime > plan.duration - 0.3 } + #expect(viewModel.playbackTime <= plan.duration) + } + + @Test + func skipToCutJumpsBetweenCutStarts() async throws { + let harness = try await makeHarness(videoCount: 4) + defer { harness.cleanUp() } + let viewModel = harness.viewModel + try await generate(harness) + let plan = try #require(viewModel.plan) + #expect(plan.cuts.count >= 5) + func expectTime(_ expected: Double, _ label: String) async throws { + try await waitUntil(label) { abs(viewModel.playbackTime - expected) < 0.06 } + } + + // 次のカットの頭へ、順に進む。 + viewModel.skipToCut(1) + try await expectTime(plan.cuts[1].timelineStart, "1つ目の次のカット") + viewModel.skipToCut(1) + try await expectTime(plan.cuts[2].timelineStart, "2つ目の次のカット") + + // カットの途中で戻ると、まずそのカットの頭へ。頭にいるときに戻ると、前のカットの頭へ。 + let long = try #require(plan.cuts.indices.dropFirst(2).first { plan.cuts[$0].duration >= 1.6 && $0 >= 3 }) + viewModel.seek(to: plan.cuts[long].timelineStart + 1.3) + try await expectTime(plan.cuts[long].timelineStart + 1.3, "長いカットの途中") + viewModel.skipToCut(-1) + try await expectTime(plan.cuts[long].timelineStart, "そのカットの頭") + viewModel.skipToCut(-1) + try await expectTime(plan.cuts[long - 1].timelineStart, "前のカットの頭") + + // 最後のカットでは、それより先へは進まない。 + let last = plan.cuts.count - 1 + viewModel.seek(to: plan.cuts[last].timelineStart) + try await expectTime(plan.cuts[last].timelineStart, "最後のカット") + viewModel.skipToCut(1) + try await Task.sleep(for: .milliseconds(300)) + #expect(abs(viewModel.playbackTime - plan.cuts[last].timelineStart) < 0.06) + // 先頭のカットでは、それより前へは戻らない。 + viewModel.seek(to: 0) + try await expectTime(0, "先頭") + viewModel.skipToCut(-1) + try await Task.sleep(for: .milliseconds(300)) + #expect(viewModel.playbackTime < 0.06) + } + + @Test + func playPauseAndMuteWork_andReplayFromTheStartAfterTheEnd() async throws { + let harness = try await makeHarness(videoCount: 3) + defer { harness.cleanUp() } + let viewModel = harness.viewModel + try await generate(harness) + let plan = try #require(viewModel.plan) + + viewModel.togglePlayback() + try await waitUntil("再生開始") { viewModel.isPlaying } + viewModel.togglePlayback() + try await waitUntil("一時停止") { !viewModel.isPlaying } + + // 終わりまで進めてから再生すると、先頭から再生し直す。 + viewModel.seek(to: plan.duration - 0.02) + try await waitUntil("終わりへ移動") { viewModel.playbackTime > plan.duration - 0.2 } + viewModel.togglePlayback() + try await waitUntil("先頭から再生") { viewModel.isPlaying && viewModel.playbackTime < 2 } + viewModel.togglePlayback() + try await waitUntil("再び一時停止") { !viewModel.isPlaying } + + viewModel.isMuted = true + #expect(viewModel.player.isMuted) + viewModel.isMuted = false + #expect(!viewModel.player.isMuted) + } + + @Test + func fullScreenDoesNotOpenWithoutAVideo() { + let viewModel = MusicVideoViewModel(preferencesStore: MusicVideoPreferencesStore(defaults: UserDefaults(suiteName: "musicvideo-fs-\(UUID().uuidString)")!)) + let presenter = MusicVideoFullScreenPresenter() + presenter.present(viewModel: viewModel) + #expect(!presenter.isPresented) + } + + @Test + func tuningIsSavedAndRestoredInTheNextSession() async throws { + let harness = try await makeHarness(videoCount: 2) + defer { harness.cleanUp() } + + harness.viewModel.cutTuning.motionMatching = .strong + harness.viewModel.cutTuning.variety = .wide + harness.viewModel.lookTuning.fitMode = .fit + harness.viewModel.lookTuning.fadeSeconds = 1 + harness.viewModel.sourceLimit = 80 + + let next = MusicVideoViewModel(preferencesStore: MusicVideoPreferencesStore(defaults: harness.defaults)) + next.attach(dataManager: harness.library) + #expect(next.cutTuning.motionMatching == .strong) + #expect(next.cutTuning.variety == .wide) + #expect(next.lookTuning.fitMode == .fit) + #expect(next.lookTuning.fadeSeconds == 1) + #expect(next.sourceLimit == 80) + // 復元しただけでは、何も反映待ちにならない(映像がまだ無いので、何も作り直されない)。 + #expect(next.plan == nil) + } +}