diff --git a/ArkServer/App/Models/NavigationSelection.swift b/ArkServer/App/Models/NavigationSelection.swift index 0314016..a198cf5 100644 --- a/ArkServer/App/Models/NavigationSelection.swift +++ b/ArkServer/App/Models/NavigationSelection.swift @@ -10,6 +10,8 @@ enum NavigationSelection: Hashable { case history case trash case sceneExtraction + /// 曲に合わせてライブラリの動画を自動で編集する画面。 + case musicVideo /// 動画・画像のアルバムを表紙つきで一覧するページ。 case albums case album(UUID) diff --git a/ArkServer/App/ViewModels/AppViewModel.swift b/ArkServer/App/ViewModels/AppViewModel.swift index c31e6c1..eb8ecca 100644 --- a/ArkServer/App/ViewModels/AppViewModel.swift +++ b/ArkServer/App/ViewModels/AppViewModel.swift @@ -30,6 +30,8 @@ final class AppViewModel: ObservableObject { let playbackSettings = PlaybackSettings() /// シーン抽出画面の再生位置,解析結果,GTラベルを画面切替後も保持します. let sceneExtraction = SceneExtractionViewModel() + /// ミュージックビデオ作成の曲・素材・プレビューを画面切替後も保持します. + let musicVideo = MusicVideoViewModel() private var cancellables = Set() private var sceneExtractionReturnSelection: NavigationSelection = .home diff --git a/ArkServer/App/Views/ContentView.swift b/ArkServer/App/Views/ContentView.swift index dc642c9..6891aae 100644 --- a/ArkServer/App/Views/ContentView.swift +++ b/ArkServer/App/Views/ContentView.swift @@ -318,6 +318,11 @@ struct ContentView: View { viewModel: viewModel.sceneExtraction, onClose: viewModel.closeSceneExtraction ) + case .musicVideo: + MusicVideoView( + viewModel: viewModel.musicVideo, + dataManager: dataManager + ) case .albums: AlbumOverviewView( dataManager: dataManager, diff --git a/ArkServer/Features/Library/ViewModels/LibraryViewModel.swift b/ArkServer/Features/Library/ViewModels/LibraryViewModel.swift index e9bd034..3b8c3cc 100644 --- a/ArkServer/Features/Library/ViewModels/LibraryViewModel.swift +++ b/ArkServer/Features/Library/ViewModels/LibraryViewModel.swift @@ -352,12 +352,7 @@ class LibraryViewModel: ObservableObject { isSecondaryInstance = !Self.acquireInstanceLock(at: appRootURL.appendingPathComponent(".instance.lock")) if isSecondaryInstance { DispatchQueue.main.async { - let alert = NSAlert() - alert.messageText = "Ark Server は既に起動しています" - alert.informativeText = "別のインスタンス(例: Xcodeからの実行と通常起動)が同じライブラリを開いています.データの二重書き込みによる消失を防ぐため,このインスタンスは終了します." - alert.alertStyle = .warning - alert.runModal() - NSApplication.shared.terminate(nil) + Self.presentDuplicateInstanceAlertAndQuit() } return } @@ -376,6 +371,32 @@ class LibraryViewModel: ObservableObject { } } + /// 二重起動側のインスタンスで警告を出し、確実に終了する。 + /// + /// このインスタンスはライブラリを読み込まず何も保存しないので、強制終了しても失われるものはない。 + /// 「OK」が押せない・終了が効かない場合でも、プロセスが残り続けないようにする。 + private static func presentDuplicateInstanceAlertAndQuit() { + // 主スレッドが詰まっていても動くよう、別のキューから強制終了を予約しておく。 + DispatchQueue.global(qos: .userInitiated).asyncAfter(deadline: .now() + duplicateInstanceAutoQuitSeconds) { + exit(0) + } + // Xcode などから起動すると、アプリが前面に出ずアラートが他のウィンドウの後ろに残ることがある。 + NSApp.activate(ignoringOtherApps: true) + + let alert = NSAlert() + alert.messageText = "Ark Server は既に起動しています" + alert.informativeText = "別のインスタンス(例: Xcodeからの実行と通常起動)が同じライブラリを開いています.データの二重書き込みによる消失を防ぐため,このインスタンスは終了します.(\(Int(duplicateInstanceAutoQuitSeconds))秒たつと自動で終了します)" + alert.alertStyle = .warning + alert.runModal() + + NSApplication.shared.terminate(nil) + // terminate が取り消された・止まった場合の保険。 + DispatchQueue.global(qos: .userInitiated).asyncAfter(deadline: .now() + 2) { exit(0) } + } + + /// 二重起動の警告を出してから、操作がなくても自動で終了するまでの秒数。 + private static let duplicateInstanceAutoQuitSeconds: Double = 30 + private func prepareStorageDirectories(_ directories: [URL]) -> Bool { for directory in directories { do { diff --git a/ArkServer/Features/MusicVideo/Models/MusicVideoModels.swift b/ArkServer/Features/MusicVideo/Models/MusicVideoModels.swift new file mode 100644 index 0000000..623a0ed --- /dev/null +++ b/ArkServer/Features/MusicVideo/Models/MusicVideoModels.swift @@ -0,0 +1,281 @@ +// ArkServer/Features/MusicVideo/Models/MusicVideoModels.swift + +import Foundation + +/// 曲の盛り上がりの段階。カットの長さと、選ぶ素材の動きの大きさを決める。 +nonisolated enum MusicIntensity: Int, Codable, Comparable, CaseIterable, Sendable { + case calm = 0 + case medium + case intense + + static func < (lhs: MusicIntensity, rhs: MusicIntensity) -> Bool { + lhs.rawValue < rhs.rawValue + } + + var displayName: String { + switch self { + case .calm: return "静か" + case .medium: return "中" + case .intense: return "盛り上がり" + } + } + + /// この段階で選びたい素材の動きの大きさ(0〜1)。 + var targetMotion: Double { + switch self { + case .calm: return 0.15 + case .medium: return 0.5 + case .intense: return 0.85 + } + } +} + +/// カット割りの細かさ。盛り上がりの段階ごとに「何拍で切り替えるか」を決める。 +nonisolated enum MusicVideoCutStyle: String, Codable, CaseIterable, Sendable { + case relaxed + case standard + case energetic + + var displayName: String { + switch self { + case .relaxed: return "控えめ" + case .standard: return "標準" + case .energetic: return "激しい" + } + } + + func beatsPerCut(for intensity: MusicIntensity) -> Int { + switch (self, intensity) { + case (.relaxed, .calm): return 8 + case (.relaxed, .medium): return 4 + case (.relaxed, .intense): return 2 + case (.standard, .calm): return 4 + case (.standard, .medium): return 2 + case (.standard, .intense): return 1 + case (.energetic, .calm): return 2 + case (.energetic, .medium): return 1 + case (.energetic, .intense): return 1 + } + } +} + +/// 完成映像の画面サイズの選択肢。 +nonisolated enum MusicVideoRenderPreset: String, Codable, CaseIterable, Hashable, Sendable { + case landscapeFullHD + case landscapeHD + case portraitFullHD + case portraitHD + + var displayName: String { + switch self { + case .landscapeFullHD: return "横 1080p" + case .landscapeHD: return "横 720p" + case .portraitFullHD: return "縦 1080p" + case .portraitHD: return "縦 720p" + } + } + + var settings: MusicVideoRenderSettings { + switch self { + case .landscapeFullHD: return .landscapeFullHD + case .landscapeHD: return .landscapeHD + case .portraitFullHD: return .portraitFullHD + case .portraitHD: return .portraitHD + } + } +} + +/// 書き出しの画質。画面サイズは変えず、映像のビットレート(1秒あたりのデータ量)で決める。 +nonisolated enum MusicVideoExportQuality: String, Codable, CaseIterable, Hashable, Sendable { + case high + case standard + case compact + + static let audioBitRate = 192_000 + static let audioSampleRate = 44_100.0 + + var displayName: String { + switch self { + case .high: return "高画質" + case .standard: return "標準" + case .compact: return "小さめ" + } + } + + /// 1画素・1フレームあたりのビット数。H.264 で、カットが細かく動きの多い映像でも崩れにくい目安。 + private var bitsPerPixel: Double { + switch self { + case .high: return 0.16 + case .standard: return 0.08 + case .compact: return 0.04 + } + } + + /// 画面サイズ・フレームレートに応じた映像のビットレート(bps)。 + func videoBitRate(for render: MusicVideoRenderSettings) -> Int { + let raw = Double(render.width * render.height * render.framesPerSecond) * bitsPerPixel + return max(300_000, Int(raw)) + } + + /// 1分あたりのファイルサイズの目安(MB)。音声を含む。 + func estimatedMegabytesPerMinute(for render: MusicVideoRenderSettings) -> Double { + Double(videoBitRate(for: render) + Self.audioBitRate) * 60 / 8 / 1_000_000 + } +} + +/// 曲の解析結果。拍の位置と、時間ごとの盛り上がりを持つ。 +nonisolated struct MusicAnalysis: Codable, Equatable, Sendable { + /// 曲全体の長さ(秒)。 + var duration: Double + /// 推定したテンポ(BPM)。 + var tempo: Double + /// 拍の時刻(秒、昇順)。 + var beats: [Double] + /// 盛り上がりの連続値(0〜1)。`energyHop` 秒ごと。 + var energy: [Double] + /// 盛り上がりの段階。`energy` と同じ間隔。 + var intensity: [MusicIntensity] + /// `energy` / `intensity` の標本間隔(秒)。 + var energyHop: Double + + func energy(at time: Double) -> Double { + guard !energy.isEmpty, energyHop > 0 else { return 0.5 } + let index = min(max(0, Int(time / energyHop)), energy.count - 1) + return energy[index] + } + + func intensity(at time: Double) -> MusicIntensity { + guard !intensity.isEmpty, energyHop > 0 else { return .medium } + let index = min(max(0, Int(time / energyHop)), intensity.count - 1) + return intensity[index] + } +} + +/// 素材動画の「ある区間」について、時間ごとの映像の動きの大きさ(0〜1)。 +/// 長い動画は全体を調べず、離れた複数の区間(窓)だけを調べるので、1本の動画が複数の窓になりうる。 +nonisolated struct SourceMotionProfile: Codable, Equatable, Sendable { + let videoID: UUID + /// この区間の動画内での開始位置(秒)。`values` の先頭がこの位置に当たる。 + let offset: Double + /// この区間の長さ(秒)。カットはこの範囲の中から選ぶ。 + let duration: Double + /// `values` の標本間隔(秒)。 + let hop: Double + /// 動きの大きさ(0〜1)。 + let values: [Double] + /// 区間の平均を O(1) で求めるための累積和。保存はせず、読み込み時に作り直す。 + private let prefixSums: [Double] + + init(videoID: UUID, offset: Double = 0, duration: Double, hop: Double, values: [Double]) { + self.videoID = videoID + self.offset = offset + self.duration = duration + self.hop = hop + self.values = values + self.prefixSums = Self.makePrefixSums(values) + } + + private enum CodingKeys: String, CodingKey { + case videoID, offset, duration, hop, values + } + + init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + let videoID = try container.decode(UUID.self, forKey: .videoID) + let offset = try container.decodeIfPresent(Double.self, forKey: .offset) ?? 0 + let duration = try container.decode(Double.self, forKey: .duration) + let hop = try container.decode(Double.self, forKey: .hop) + let values = try container.decode([Double].self, forKey: .values) + self.init(videoID: videoID, offset: offset, duration: duration, hop: hop, values: values) + } + + private static func makePrefixSums(_ values: [Double]) -> [Double] { + var sums = [Double](repeating: 0, count: values.count + 1) + for (index, value) in values.enumerated() { + sums[index + 1] = sums[index] + value + } + return sums + } + + /// この区間の中の `start`(区間の先頭からの秒数)から `length` 秒の、動きの平均。標本が無いときは中間値を返す。 + func meanMotion(start: Double, length: Double) -> Double { + guard !values.isEmpty, hop > 0 else { return 0.5 } + let first = min(max(0, Int(start / hop)), values.count - 1) + let end = min(values.count, max(first + 1, Int(((start + length) / hop).rounded(.up)))) + return (prefixSums[end] - prefixSums[first]) / Double(end - first) + } +} + +/// 1カット分の計画。素材のどこを、タイムラインのどこに置くか。 +nonisolated struct PlannedCut: Identifiable, Equatable, Sendable { + let id = UUID() + let videoID: UUID + /// 素材動画の中の開始位置(秒)。 + let sourceStart: Double + let duration: Double + /// 完成映像の中での開始位置(秒)。 + let timelineStart: Double + let intensity: MusicIntensity + + var timelineEnd: Double { timelineStart + duration } + + static func == (lhs: PlannedCut, rhs: PlannedCut) -> Bool { + lhs.videoID == rhs.videoID + && lhs.sourceStart == rhs.sourceStart + && lhs.duration == rhs.duration + && lhs.timelineStart == rhs.timelineStart + && lhs.intensity == rhs.intensity + } +} + +/// 映像全体のカット割り。曲の長さに一致する。 +nonisolated struct CutPlan: Equatable, Sendable { + var cuts: [PlannedCut] + var duration: Double + + /// `time` 秒の位置にあるカットの番号。範囲外なら最初/最後のカットに寄せる。カットが無ければ nil。 + func cutIndex(at time: Double) -> Int? { + guard !cuts.isEmpty else { return nil } + var low = 0 + var high = cuts.count - 1 + while low < high { + let middle = (low + high + 1) / 2 + if cuts[middle].timelineStart <= time { low = middle } else { high = middle - 1 } + } + return low + } +} + +nonisolated enum CutPlannerError: LocalizedError, Equatable { + case noBeats + case emptyPool + case noClipLongEnough + + var errorDescription: String? { + switch self { + case .noBeats: + return "曲から拍を検出できませんでした." + case .emptyPool: + return "使える素材動画がありません." + case .noClipLongEnough: + return "素材動画が短すぎて,曲のカット長を満たせません.長めの動画を選んでください." + } + } +} + +/// 同じ種から同じ乱数列を作る擬似乱数(SplitMix64)。カット割りを再現可能にするために使う。 +nonisolated struct SeededGenerator: RandomNumberGenerator, Sendable { + private var state: UInt64 + + init(seed: UInt64) { + state = seed + } + + mutating func next() -> UInt64 { + state &+= 0x9E37_79B9_7F4A_7C15 + var z = state + z = (z ^ (z >> 30)) &* 0xBF58_476D_1CE4_E5B9 + z = (z ^ (z >> 27)) &* 0x94D0_49BB_1331_11EB + return z ^ (z >> 31) + } +} diff --git a/ArkServer/Features/MusicVideo/Models/MusicVideoPreferences.swift b/ArkServer/Features/MusicVideo/Models/MusicVideoPreferences.swift new file mode 100644 index 0000000..3ec15d7 --- /dev/null +++ b/ArkServer/Features/MusicVideo/Models/MusicVideoPreferences.swift @@ -0,0 +1,75 @@ +// ArkServer/Features/MusicVideo/Models/MusicVideoPreferences.swift + +import Foundation + +/// ミュージックビデオ画面の設定。次に開いたときに同じ状態から始められるよう保存する。 +nonisolated struct MusicVideoPreferences: Codable, Equatable, Sendable { + var cutStyle: MusicVideoCutStyle = .standard + var renderPreset: MusicVideoRenderPreset = .landscapeFullHD + var exportQuality: MusicVideoExportQuality = .high + var selectedAlbumIDs: [UUID] = [] + var selectedVideoIDs: [UUID] = [] + var includeFavorites = false + /// 曲を探すフォルダ。 + var musicFolderPath: String? + /// 最近使った曲(新しい順)。 + var recentMusicPaths: [String] = [] + + static let recentMusicLimit = 8 + + /// 最近使った曲の先頭に加える。同じ曲は1つにまとめ、上限を超えた古いものを捨てる。 + mutating func recordRecentMusic(_ path: String) { + recentMusicPaths.removeAll { $0 == path } + recentMusicPaths.insert(path, at: 0) + if recentMusicPaths.count > Self.recentMusicLimit { + recentMusicPaths.removeLast(recentMusicPaths.count - Self.recentMusicLimit) + } + } + + /// ライブラリからなくなったアルバム・動画の選択を取り除く。 + func pruned(validAlbumIDs: Set, validVideoIDs: Set) -> MusicVideoPreferences { + var result = self + result.selectedAlbumIDs = selectedAlbumIDs.filter { validAlbumIDs.contains($0) } + result.selectedVideoIDs = selectedVideoIDs.filter { validVideoIDs.contains($0) } + return result + } + + // 後から項目を足しても、古い保存データを読めるようにする(無い項目は既定値)。 + private enum CodingKeys: String, CodingKey { + case cutStyle, renderPreset, exportQuality, selectedAlbumIDs, selectedVideoIDs, includeFavorites + case musicFolderPath, recentMusicPaths + } + + init() {} + + init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + 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 + 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 + musicFolderPath = try container.decodeIfPresent(String.self, forKey: .musicFolderPath) + recentMusicPaths = try container.decodeIfPresent([String].self, forKey: .recentMusicPaths) ?? [] + } +} + +/// `MusicVideoPreferences` を UserDefaults に読み書きする。壊れた保存データは既定値に戻す。 +nonisolated struct MusicVideoPreferencesStore: @unchecked Sendable { + var defaults: UserDefaults = .standard + var key = "musicVideo.preferences" + + func load() -> MusicVideoPreferences { + guard let data = defaults.data(forKey: key), + let decoded = try? JSONDecoder().decode(MusicVideoPreferences.self, from: data) else { + return MusicVideoPreferences() + } + return decoded + } + + func save(_ preferences: MusicVideoPreferences) { + guard let data = try? JSONEncoder().encode(preferences) else { return } + defaults.set(data, forKey: key) + } +} diff --git a/ArkServer/Features/MusicVideo/Models/MusicVideoSourceSelection.swift b/ArkServer/Features/MusicVideo/Models/MusicVideoSourceSelection.swift new file mode 100644 index 0000000..95a5fdb --- /dev/null +++ b/ArkServer/Features/MusicVideo/Models/MusicVideoSourceSelection.swift @@ -0,0 +1,34 @@ +// ArkServer/Features/MusicVideo/Models/MusicVideoSourceSelection.swift + +import Foundation + +/// 素材として選ばれた動画を、ライブラリの内容から決める純粋ロジック。 +/// 選び方は1つの集合に統合する: 選んだアルバムの動画 ∪ 個別に選んだ動画 ∪ お気に入り。 +/// +/// 実ファイルの存在確認はしない(ここは画面の件数表示でも使うため、ファイルアクセスを伴わない)。 +/// ファイルの確認は、映像を作る直前にだけ行う。 +nonisolated enum MusicVideoSourceSelection { + /// 素材として使える最短の長さ(秒)。これより短い動画は1カットも取れない。 + static let defaultMinimumDuration = 1.0 + + static func candidateIDs( + videos: [VideoItem], + albums: [Album], + selectedAlbumIDs: Set, + selectedVideoIDs: Set, + includeFavorites: Bool, + minimumDuration: Double = defaultMinimumDuration + ) -> [UUID] { + guard !selectedAlbumIDs.isEmpty || !selectedVideoIDs.isEmpty || includeFavorites else { return [] } + + var chosen = selectedVideoIDs + for album in albums where selectedAlbumIDs.contains(album.id) { + chosen.formUnion(album.videoIDs) + } + return videos.compactMap { item in + guard item.mediaType == .video, !item.isInTrash, item.duration >= minimumDuration else { return nil } + guard chosen.contains(item.id) || (includeFavorites && item.isFavorite) else { return nil } + return item.id + } + } +} diff --git a/ArkServer/Features/MusicVideo/Services/BeatAnalyzer.swift b/ArkServer/Features/MusicVideo/Services/BeatAnalyzer.swift new file mode 100644 index 0000000..fa5b1ec --- /dev/null +++ b/ArkServer/Features/MusicVideo/Services/BeatAnalyzer.swift @@ -0,0 +1,465 @@ +// ArkServer/Features/MusicVideo/Services/BeatAnalyzer.swift + +import Accelerate +import AVFoundation +import Foundation + +nonisolated enum BeatAnalyzerError: LocalizedError { + case noAudioTrack + case cannotCreateReader + case cannotAddOutput + case readerFailed(String) + case tooShort + + var errorDescription: String? { + switch self { + case .noAudioTrack: + return "音声トラックが見つかりませんでした." + case .cannotCreateReader: + return "音声解析用のAVAssetReaderを作成できませんでした." + case .cannotAddOutput: + return "音声PCM出力をAVAssetReaderへ追加できませんでした." + case .readerFailed(let reason): + return "音声の読み取りに失敗しました.\(reason)" + case .tooShort: + return "音声が短すぎて解析できません." + } + } +} + +/// 曲から拍の位置と盛り上がりを求める。 +/// +/// 手順: スペクトルフラックスで音の立ち上がり(onset)を求め → 自己相関でテンポを推定し → +/// 動的計画法(Ellis 2007)で拍を並べる。盛り上がりは音量と onset の密度を平滑化して3段階に分ける。 +nonisolated struct BeatAnalyzer: Sendable { + /// ファイルを読むときに変換する標本化周波数。拍の解析には十分で、処理が軽くなる。 + static let analysisSampleRate = 22_050.0 + + private let frameSize = 1024 + private let hopSize = 256 + private let minimumTempo = 60.0 + private let maximumTempo = 200.0 + private let preferredTempo = 120.0 + /// 盛り上がりを求める間隔(秒)。 + private let energyHop = 0.1 + + // MARK: - ファイルからの解析 + + func analyze(url: URL) async throws -> MusicAnalysis { + let samples = try await readMonoSamples(url: url) + try Task.checkCancellation() + guard samples.count >= frameSize * 8 else { throw BeatAnalyzerError.tooShort } + return analyze(samples: samples, sampleRate: Self.analysisSampleRate) + } + + private func readMonoSamples(url: URL) async throws -> [Float] { + let asset = AVURLAsset(url: url) + guard let track = try await asset.loadTracks(withMediaType: .audio).first else { + throw BeatAnalyzerError.noAudioTrack + } + let reader: AVAssetReader + do { + reader = try AVAssetReader(asset: asset) + } catch { + throw BeatAnalyzerError.cannotCreateReader + } + let outputSettings: [String: Any] = [ + AVFormatIDKey: kAudioFormatLinearPCM, + AVLinearPCMIsFloatKey: true, + AVLinearPCMBitDepthKey: 32, + AVLinearPCMIsBigEndianKey: false, + AVLinearPCMIsNonInterleaved: false, + AVNumberOfChannelsKey: 1, + AVSampleRateKey: Self.analysisSampleRate + ] + let output = AVAssetReaderTrackOutput(track: track, outputSettings: outputSettings) + output.alwaysCopiesSampleData = false + guard reader.canAdd(output) else { throw BeatAnalyzerError.cannotAddOutput } + reader.add(output) + guard reader.startReading() else { + throw BeatAnalyzerError.readerFailed(reader.error?.localizedDescription ?? "開始できませんでした.") + } + + var samples: [Float] = [] + while let sampleBuffer = output.copyNextSampleBuffer() { + try Task.checkCancellation() + guard let dataBuffer = CMSampleBufferGetDataBuffer(sampleBuffer) else { continue } + let byteCount = CMBlockBufferGetDataLength(dataBuffer) + guard byteCount > 0, byteCount.isMultiple(of: MemoryLayout.size) else { continue } + var chunk = [Float](repeating: 0, count: byteCount / MemoryLayout.size) + let status = chunk.withUnsafeMutableBytes { destination in + CMBlockBufferCopyDataBytes( + dataBuffer, + atOffset: 0, + dataLength: byteCount, + destination: destination.baseAddress! + ) + } + guard status == kCMBlockBufferNoErr else { + throw BeatAnalyzerError.readerFailed("PCMバッファをコピーできませんでした.") + } + samples.append(contentsOf: chunk) + } + if reader.status == .failed { + throw BeatAnalyzerError.readerFailed(reader.error?.localizedDescription ?? "原因不明です.") + } + return samples + } + + // MARK: - 解析本体(ファイル非依存。単体テストはここを直接呼ぶ) + + func analyze(samples: [Float], sampleRate: Double) -> MusicAnalysis { + let duration = Double(samples.count) / sampleRate + let features = extractFrameFeatures(samples: samples, sampleRate: sampleRate) + let framesPerSecond = sampleRate / Double(hopSize) + + let onset = makeOnsetEnvelope(flux: features.flux, framesPerSecond: framesPerSecond) + let period = estimateBeatPeriod(onset: onset, framesPerSecond: framesPerSecond) + var beatFrames = trackBeats(onset: onset, period: period) + + // フラックスが最大になるのは、音の立ち上がりが窓の後ろ寄り(約3/4)に入ったとき。 + // フレームの先頭からその位置までを足して、実際の音のタイミングに合わせる。 + let onsetOffset = 0.75 * Double(frameSize) / sampleRate + var beats = beatFrames.map { Double($0) / framesPerSecond + onsetOffset } + beats = beats.filter { $0 >= 0 && $0 < duration } + + var tempo = 60 * framesPerSecond / period + if beats.count >= 4 { + let intervals = zip(beats.dropFirst(), beats).map { $0 - $1 }.sorted() + let median = intervals[intervals.count / 2] + if median > 0 { tempo = 60 / median } + } + // 拍がほとんど取れなかったときは、推定したテンポで等間隔に並べる。 + if beats.count < 2 { + let interval = 60 / max(1, tempo) + beats = Array(stride(from: interval, to: max(interval, duration - 0.05), by: interval)) + beatFrames = [] + } + + let (energy, intensity) = makeEnergyAndIntensity( + loudness: features.loudness, + onset: onset, + framesPerSecond: framesPerSecond + ) + return MusicAnalysis( + duration: duration, + tempo: tempo, + beats: beats, + energy: energy, + intensity: intensity, + energyHop: energyHop + ) + } + + // MARK: - フレームごとの特徴 + + private struct FrameFeatures { + var flux: [Double] + var loudness: [Double] + } + + /// フレームごとのスペクトルフラックス(音の立ち上がり)と音量(dB)を求める。 + private func extractFrameFeatures(samples: [Float], sampleRate: Double) -> FrameFeatures { + guard samples.count >= frameSize else { return FrameFeatures(flux: [], loudness: []) } + let frameCount = (samples.count - frameSize) / hopSize + 1 + let halfLength = frameSize / 2 + let log2Length = vDSP_Length(log2(Double(frameSize))) + guard let fftSetup = vDSP_create_fftsetup(log2Length, FFTRadix(kFFTRadix2)) else { + return FrameFeatures( + flux: [Double](repeating: 0, count: frameCount), + loudness: [Double](repeating: -60, count: frameCount) + ) + } + defer { vDSP_destroy_fftsetup(fftSetup) } + + var hann = [Float](repeating: 0, count: frameSize) + vDSP_hann_window(&hann, vDSP_Length(frameSize), Int32(vDSP_HANN_NORM)) + + var windowed = [Float](repeating: 0, count: frameSize) + var real = [Float](repeating: 0, count: halfLength) + var imaginary = [Float](repeating: 0, count: halfLength) + var power = [Float](repeating: 0, count: halfLength) + var previous = [Float](repeating: 0, count: halfLength) + var current = [Float](repeating: 0, count: halfLength) + var flux = [Double](repeating: 0, count: frameCount) + var loudness = [Double](repeating: -60, count: frameCount) + let magnitudeScale = 1000 / Float(frameSize) + + samples.withUnsafeBufferPointer { sampleBuffer in + for frame in 0.. 0 { frameFlux += rise } + } + flux[frame] = frame == 0 ? 0 : Double(frameFlux) + swap(&previous, ¤t) + } + } + return FrameFeatures(flux: flux, loudness: loudness) + } + + // MARK: - onset の整形 + + /// フラックスから局所平均を引いて正の部分だけを残し、標準偏差で規格化する。 + private func makeOnsetEnvelope(flux: [Double], framesPerSecond: Double) -> [Double] { + guard !flux.isEmpty else { return [] } + let radius = max(1, Int(framesPerSecond * 0.5)) + let mean = movingAverage(flux, radius: radius) + var onset = zip(flux, mean).map { max(0, $0 - $1) } + let count = Double(onset.count) + let average = onset.reduce(0, +) / count + let variance = onset.reduce(0) { $0 + ($1 - average) * ($1 - average) } / count + let deviation = variance.squareRoot() + if deviation > 1e-9 { + onset = onset.map { $0 / deviation } + } + return onset + } + + // MARK: - テンポ(拍の間隔)の推定 + + /// onset の自己相関から、拍の間隔(フレーム数)を求める。 + private func estimateBeatPeriod(onset: [Double], framesPerSecond: Double) -> Double { + let fallback = framesPerSecond * 60 / preferredTempo + let minLag = max(2, Int((framesPerSecond * 60 / maximumTempo).rounded(.down))) + let maxLag = Int((framesPerSecond * 60 / minimumTempo).rounded(.up)) + // 2倍・4倍の周期にも山が出るので、それも足して基本周期を強調する。 + let longestLag = maxLag * 4 + guard onset.count > longestLag * 2 else { return fallback } + + let signal = onset.map { Float($0) } + var correlation = [Double](repeating: 0, count: longestLag + 2) + signal.withUnsafeBufferPointer { buffer in + for lag in minLag...longestLag { + var dot: Float = 0 + let length = vDSP_Length(buffer.count - lag) + vDSP_dotpr(buffer.baseAddress!, 1, buffer.baseAddress! + lag, 1, &dot, length) + correlation[lag] = Double(dot) / Double(length) + } + } + guard correlation.contains(where: { $0 > 0 }) else { return fallback } + + var bestLag = minLag + var bestScore = -Double.infinity + var scores = [Double](repeating: 0, count: maxLag + 2) + for lag in minLag...maxLag { + var score = correlation[lag] + if lag * 2 <= longestLag { score += 0.5 * correlation[lag * 2] } + if lag * 4 <= longestLag { score += 0.25 * correlation[lag * 4] } + // 120BPM付近を好む事前分布(オクターブ違いの取り違えを減らす)。 + let tempo = framesPerSecond * 60 / Double(lag) + let octaves = log2(tempo / preferredTempo) + score *= exp(-0.5 * octaves * octaves) + scores[lag] = score + if score > bestScore { + bestScore = score + bestLag = lag + } + } + + // 放物線補間で、フレーム間隔より細かい周期を求める。 + var refined = Double(bestLag) + if bestLag > minLag, bestLag < maxLag { + let left = scores[bestLag - 1] + let center = scores[bestLag] + let right = scores[bestLag + 1] + let denominator = left - 2 * center + right + if abs(denominator) > 1e-12 { + refined += 0.5 * (left - right) / denominator + } + } + return refined + } + + // MARK: - 拍の追跡(Ellis 2007 の動的計画法) + + /// 拍のフレーム番号を昇順で返す。 + private func trackBeats(onset: [Double], period: Double) -> [Int] { + let count = onset.count + guard count > 0, period >= 2 else { return [] } + let minGap = max(1, Int((period / 2).rounded())) + let maxGap = max(minGap + 1, Int((period * 2).rounded())) + let tightness = 100.0 + + var penalty = [Double](repeating: 0, count: maxGap + 1) + for gap in minGap...maxGap { + let ratio = log(Double(gap) / period) + penalty[gap] = tightness * ratio * ratio + } + + var cumulative = onset + var backlink = [Int](repeating: -1, count: count) + for frame in 0..= lowest else { continue } + var bestScore = -Double.infinity + var bestPrevious = -1 + for previous in lowest...highest { + let score = cumulative[previous] - penalty[frame - previous] + if score > bestScore { + bestScore = score + bestPrevious = previous + } + } + if bestPrevious >= 0, bestScore > 0 { + cumulative[frame] = onset[frame] + bestScore + backlink[frame] = bestPrevious + } + } + + let tailStart = max(0, count - maxGap) + var last = tailStart + for frame in tailStart.. cumulative[last] { + last = frame + } + var beats: [Int] = [] + var frame = last + while frame >= 0 { + beats.append(frame) + frame = backlink[frame] + } + return beats.reversed() + } + + // MARK: - 盛り上がり + + private func makeEnergyAndIntensity( + loudness: [Double], + onset: [Double], + framesPerSecond: Double + ) -> (energy: [Double], intensity: [MusicIntensity]) { + let blockFrames = max(1, Int((framesPerSecond * energyHop).rounded())) + let blockCount = max(1, min(loudness.count, onset.count) / blockFrames) + var loudBlocks = [Double](repeating: 0, count: blockCount) + var onsetBlocks = [Double](repeating: 0, count: blockCount) + for block in 0.. [Double] { + guard values.count > 1 else { return values.map { _ in 0.5 } } + let sorted = values.sorted() + let low = sorted[Int(Double(sorted.count - 1) * 0.1)] + let high = sorted[Int(Double(sorted.count - 1) * 0.9)] + guard high - low > 1e-9 else { return values.map { _ in 0.5 } } + return values.map { min(1, max(0, ($0 - low) / (high - low))) } + } + + /// ヒステリシス付きで3段階に分け、短すぎる区間は前後に吸収する。 + private func classify(_ energy: [Double]) -> [MusicIntensity] { + guard let first = energy.first else { return [] } + let calmBoundary = 0.35 + let intenseBoundary = 0.65 + let margin = 0.05 + + var level: MusicIntensity = first < calmBoundary ? .calm : (first > intenseBoundary ? .intense : .medium) + var levels: [MusicIntensity] = [] + levels.reserveCapacity(energy.count) + for value in energy { + switch level { + case .calm: + if value > calmBoundary + margin { + level = value > intenseBoundary + margin ? .intense : .medium + } + case .medium: + if value < calmBoundary - margin { + level = .calm + } else if value > intenseBoundary + margin { + level = .intense + } + case .intense: + if value < intenseBoundary - margin { + level = value < calmBoundary - margin ? .calm : .medium + } + } + levels.append(level) + } + return mergeShortRuns(levels, minimumRun: max(1, Int(2.0 / energyHop))) + } + + private func mergeShortRuns(_ levels: [MusicIntensity], minimumRun: Int) -> [MusicIntensity] { + guard !levels.isEmpty else { return levels } + var result = levels + // 短い区間を消すと別の短い区間ができることがあるので、数回繰り返す。 + for _ in 0..<3 { + var runs: [(level: MusicIntensity, range: Range)] = [] + var start = 0 + for index in 1...result.count where index == result.count || result[index] != result[start] { + runs.append((result[start], start.. 1 { + let neighbor = runIndex > 0 ? runs[runIndex - 1].level : runs[runIndex + 1].level + for index in run.range { result[index] = neighbor } + changed = true + } + if !changed { break } + } + return result + } + + // MARK: - 補助 + + /// 前後 `radius` 要素の単純移動平均(端は範囲を狭めて計算)。 + private func movingAverage(_ values: [Double], radius: Int) -> [Double] { + guard !values.isEmpty else { return [] } + var prefix = [Double](repeating: 0, count: values.count + 1) + for (index, value) in values.enumerated() { + prefix[index + 1] = prefix[index] + value + } + return values.indices.map { index in + let lower = max(0, index - radius) + let upper = min(values.count, index + radius + 1) + return (prefix[upper] - prefix[lower]) / Double(upper - lower) + } + } +} diff --git a/ArkServer/Features/MusicVideo/Services/ClipPoolBuilder.swift b/ArkServer/Features/MusicVideo/Services/ClipPoolBuilder.swift new file mode 100644 index 0000000..720fdd1 --- /dev/null +++ b/ArkServer/Features/MusicVideo/Services/ClipPoolBuilder.swift @@ -0,0 +1,263 @@ +// ArkServer/Features/MusicVideo/Services/ClipPoolBuilder.swift + +import Foundation + +/// 解析対象の素材動画1本。 +nonisolated struct ClipPoolSource: Sendable { + let videoID: UUID + let url: URL + /// ライブラリに記録されている動画の長さ(秒)。 + let duration: Double +} + +nonisolated enum ClipPoolError: LocalizedError { + case noUsableVideos + + var errorDescription: String? { + switch self { + case .noUsableVideos: + return "素材動画を解析できませんでした.動画ファイルが存在するか確認してください." + } + } +} + +/// 解析前の(正規化していない)動きの時系列。キャッシュにはこの形で保存する。 +nonisolated struct RawMotionWindow: Codable, Equatable, Sendable { + let offset: Double + let duration: Double + let hop: Double + let values: [Double] +} + +/// 素材動画から、カット割りで使う「動きの時系列」を作る。 +/// +/// 長い動画は全体を解析すると時間がかかるので、動画の中の離れた複数の区間(窓)だけを調べる。 +/// 解析結果は動画ごとにディスクへキャッシュし、同じ動画は再解析しない。 +nonisolated struct ClipPoolBuilder: Sendable { + /// 1つの窓の長さ(秒)。 + var windowDuration = 15.0 + /// 1本の動画から調べる窓の最大数。 + var maxWindowsPerVideo = 6 + /// 動きを調べるときの1秒あたりの標本数。 + var analysisFramesPerSecond = 4.0 + /// 同時に解析する動画の数。 + var maxConcurrentAnalyses = 3 + /// 解析する動画の最大本数。これを超えたらシードで無作為に選ぶ。 + var maxVideos = 40 + /// キャッシュの保存先。nil ならキャッシュしない。 + var cacheDirectory: URL? + + private static let cacheVersion = 1 + + func build( + sources: [ClipPoolSource], + seed: UInt64, + progress: @escaping @Sendable (_ completed: Int, _ total: Int) async -> Void = { _, _ in } + ) async throws -> [SourceMotionProfile] { + let selected = select(sources, seed: seed) + guard !selected.isEmpty else { throw ClipPoolError.noUsableVideos } + + var analyzed: [(source: ClipPoolSource, windows: [RawMotionWindow])] = [] + var completed = 0 + await progress(0, selected.count) + + try await withThrowingTaskGroup(of: (Int, [RawMotionWindow]?).self) { group in + var nextIndex = 0 + func addNext() { + guard nextIndex < selected.count else { return } + let index = nextIndex + let source = selected[index] + nextIndex += 1 + group.addTask { + (index, try? await self.motionWindows(for: source)) + } + } + for _ in 0.. [ClipPoolSource] { + guard sources.count > maxVideos else { return sources } + var generator = SeededGenerator(seed: seed) + return Array(sources.shuffled(using: &generator).prefix(maxVideos)) + } + + // MARK: - 窓の配置 + + /// 動画の長さから、解析する窓の (開始位置, 長さ) を決める。 + /// 冒頭と末尾の5%は(タイトルやエンドロールが多いので)避け、残りに均等に並べる。 + func windowRanges(forDuration duration: Double) -> [(offset: Double, length: Double)] { + guard duration > 0 else { return [] } + if duration <= windowDuration { return [(0, duration)] } + + let margin = duration * 0.05 + let usable = max(windowDuration, duration - 2 * margin) + let count = max(1, min(maxWindowsPerVideo, Int(usable / windowDuration))) + if count == 1 { + return [(max(0, (duration - windowDuration) / 2), windowDuration)] + } + let span = usable - windowDuration + return (0.. [RawMotionWindow] { + let attributes = try? FileManager.default.attributesOfItem(atPath: source.url.path) + let fileSize = (attributes?[.size] as? NSNumber)?.int64Value ?? -1 + let modificationTime = (attributes?[.modificationDate] as? Date)?.timeIntervalSince1970 ?? 0 + + if let cached = loadCache(for: source.videoID), + cached.version == Self.cacheVersion, + cached.fileSize == fileSize, + abs(cached.modificationTime - modificationTime) < 0.001, + cached.windowDuration == windowDuration, + cached.maxWindowsPerVideo == maxWindowsPerVideo, + cached.framesPerSecond == analysisFramesPerSecond, + abs(cached.duration - source.duration) < 0.001 { + return cached.windows + } + + let analyzer = VisualAnalyzer() + var settings = AnalysisSettings() + settings.analysisFramesPerSecond = analysisFramesPerSecond + let hop = 1 / analysisFramesPerSecond + + var windows: [RawMotionWindow] = [] + for range in windowRanges(forDuration: source.duration) { + try Task.checkCancellation() + let points = try await analyzer.analyze( + url: source.url, + settings: settings, + timeRange: range.offset...(range.offset + range.length) + ) + let values = Self.resample(points: points, offset: range.offset, length: range.length, hop: hop) + if !values.isEmpty { + windows.append(RawMotionWindow(offset: range.offset, duration: range.length, hop: hop, values: values)) + } + } + + if !windows.isEmpty { + saveCache( + CacheFile( + version: Self.cacheVersion, + fileSize: fileSize, + modificationTime: modificationTime, + windowDuration: windowDuration, + maxWindowsPerVideo: maxWindowsPerVideo, + framesPerSecond: analysisFramesPerSecond, + duration: source.duration, + windows: windows + ), + for: source.videoID + ) + } + return windows + } + + /// 解析点を、窓の先頭から `hop` 秒ごとの等間隔の列に直す。 + /// 先頭の点は直前のフレームが無く差が0になるので使わない。欠けた所は直前の値で埋める。 + static func resample(points: [VisualFeaturePoint], offset: Double, length: Double, hop: Double) -> [Double] { + let usable = Array(points.dropFirst()) + guard !usable.isEmpty, hop > 0 else { return [] } + let bucketCount = max(1, Int((length / hop).rounded(.up))) + var sums = [Double](repeating: 0, count: bucketCount) + var counts = [Int](repeating: 0, count: bucketCount) + for point in usable { + let index = min(bucketCount - 1, max(0, Int((point.time - offset) / hop))) + sums[index] += point.frameDiff + counts[index] += 1 + } + var values = [Double](repeating: 0, count: bucketCount) + var last = usable[0].frameDiff + for index in 0.. 0 { last = sums[index] / Double(counts[index]) } + values[index] = last + } + return values + } + + private func cacheURL(for videoID: UUID) -> URL? { + cacheDirectory?.appendingPathComponent("\(videoID.uuidString).json") + } + + private func loadCache(for videoID: UUID) -> CacheFile? { + guard let url = cacheURL(for: videoID), let data = try? Data(contentsOf: url) else { return nil } + return try? JSONDecoder().decode(CacheFile.self, from: data) + } + + private func saveCache(_ cache: CacheFile, for videoID: UUID) { + guard let directory = cacheDirectory, let url = cacheURL(for: videoID) else { return } + try? FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + if let data = try? JSONEncoder().encode(cache) { + try? data.write(to: url, options: .atomic) + } + } + + // MARK: - 正規化 + + /// 全素材をまとめて、下位5%を0・上位5%を1として規格化する。 + /// 動画ごとに規格化すると、静かな動画にも「激しい部分」ができてしまうので、素材全体で揃える。 + static func normalizedProfiles( + from analyzed: [(source: ClipPoolSource, windows: [RawMotionWindow])] + ) -> [SourceMotionProfile] { + let allValues = analyzed.flatMap { $0.windows.flatMap(\.values) }.sorted() + guard !allValues.isEmpty else { return [] } + let low = allValues[Int(Double(allValues.count - 1) * 0.05)] + let high = allValues[Int(Double(allValues.count - 1) * 0.95)] + let range = high - low + + var profiles: [SourceMotionProfile] = [] + for (source, windows) in analyzed { + for window in windows { + let values: [Double] = window.values.map { value in + guard range > 1e-9 else { return 0.5 } + return min(1, max(0, (value - low) / range)) + } + profiles.append( + SourceMotionProfile( + videoID: source.videoID, + offset: window.offset, + duration: window.duration, + hop: window.hop, + values: values + ) + ) + } + } + return profiles + } +} diff --git a/ArkServer/Features/MusicVideo/Services/CutPlanner.swift b/ArkServer/Features/MusicVideo/Services/CutPlanner.swift new file mode 100644 index 0000000..de5ed9a --- /dev/null +++ b/ArkServer/Features/MusicVideo/Services/CutPlanner.swift @@ -0,0 +1,280 @@ +// ArkServer/Features/MusicVideo/Services/CutPlanner.swift + +import Foundation + +/// 曲の拍と盛り上がりから、カット割りと素材の区間を決める純粋ロジック。 +/// 同じ入力と同じシードなら、必ず同じ結果になる。 +nonisolated struct CutPlanner: Sendable { + var style: MusicVideoCutStyle = .standard + /// これより短いカットは作らない(拍が速すぎる曲では切り替えの間隔を倍にする)。 + var minimumCutDuration = 0.3 + /// 1カットごとに試す素材候補の数。多いほど動きの一致度が上がる。 + var candidateAttemptsPerCut = 40 + + func plan( + analysis: MusicAnalysis, + pool: [SourceMotionProfile], + seed: UInt64 + ) throws -> CutPlan { + guard !analysis.beats.isEmpty else { throw CutPlannerError.noBeats } + guard !pool.isEmpty else { throw CutPlannerError.emptyPool } + + var generator = SeededGenerator(seed: seed) + let grid = makeGrid(analysis: analysis) + var cuts: [PlannedCut] = [] + var usage: [UUID: Int] = [:] + var usedRanges: [UUID: [Range]] = [:] + + var index = 0 + while index < grid.count - 1 { + let start = grid[index] + let intensity = analysis.intensity(at: start) + var step = nextStep(from: index, intensity: intensity, grid: grid) + var end = grid[min(grid.count - 1, index + step)] + + // 素材が足りないときは、拍の位置を保ったままカットを短くする。 + while step > 1 && !pool.contains(where: { $0.duration >= end - start }) { + step -= 1 + end = grid[min(grid.count - 1, index + step)] + } + + // 曲の終わりに短い余りが出るなら、今のカットを曲の終わりまで延ばして吸収する。 + let remainingAfter = analysis.duration - end + if remainingAfter > 0, remainingAfter < minimumCutDuration, + pool.contains(where: { $0.duration >= analysis.duration - start }) { + 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 + guard let choice = pickClip( + length: length, + target: target, + pool: pool, + avoidVideoIDs: cuts.last.map { [$0.videoID] } ?? [], + usage: usage, + usedRanges: usedRanges, + forbidden: nil, + generator: &generator + ) else { + throw CutPlannerError.noClipLongEnough + } + + cuts.append(PlannedCut( + videoID: choice.videoID, + sourceStart: choice.start, + duration: length, + timelineStart: start, + intensity: intensity + )) + usage[choice.videoID, default: 0] += 1 + usedRanges[choice.videoID, default: []].append(choice.start..<(choice.start + length)) + + if end >= analysis.duration { break } + index += step + } + + return CutPlan(cuts: cuts, duration: analysis.duration) + } + + // MARK: - 格子(カットの境界になりうる時刻) + + /// 先頭に 0 秒、末尾に曲の終わりを加えた拍の一覧。 + private func makeGrid(analysis: MusicAnalysis) -> [Double] { + var grid = analysis.beats.filter { $0 > 0.05 && $0 < analysis.duration - 0.05 } + grid.insert(0, at: 0) + grid.append(analysis.duration) + return grid + } + + /// 現在位置から次のカット境界までの拍数。 + /// 長いカット(2拍以上)は小節の頭に揃え、拍が速すぎる曲では最短時間を満たすまで倍にする。 + private func nextStep(from index: Int, intensity: MusicIntensity, grid: [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 + } + let remainingSteps = max(1, grid.count - 1 - index) + + // 格子の先頭(0秒)は拍ではない。最初のカットは1拍目までの導入部にするか、 + // 導入部が短すぎるなら最初の小節の終わりまで続ける。 + if index == 0 { + let introGap = grid[1] - grid[0] + return min(introGap >= minimumCutDuration ? 1 : beats + 1, remainingSteps) + } + + // 以降は、小節(beats 拍)の頭に境界を揃える。拍の番号は格子の番号 - 1。 + var step = beats + if beats >= 2 { + 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) + } + + private func averageInterval(grid: [Double], around index: Int) -> Double { + guard grid.count > 2 else { return 0.5 } + let upper = min(grid.count - 1, max(2, index + 4)) + let lower = max(1, upper - 4) + guard upper > lower else { return 0.5 } + return (grid[upper] - grid[lower]) / Double(upper - lower) + } + + // MARK: - 素材の選択 + + private struct ClipChoice { + let videoID: UUID + let start: Double + } + + private func pickClip( + length: Double, + target: Double, + pool: [SourceMotionProfile], + avoidVideoIDs: Set, + usage: [UUID: Int], + usedRanges: [UUID: [Range]], + forbidden: (videoID: UUID, range: Range)?, + generator: inout SeededGenerator + ) -> ClipChoice? { + let feasible = pool.filter { $0.duration >= length } + guard !feasible.isEmpty else { return nil } + // 1本の動画が複数の窓を持つので、「避ける動画以外がある」かどうかは動画IDで数える。 + let hasAlternative = feasible.contains { !avoidVideoIDs.contains($0.videoID) } + + func search(honoringForbidden: Bool, generator: inout SeededGenerator) -> ClipChoice? { + var best: (choice: ClipChoice, score: Double)? + for _ in 0.. 0 ? Double.random(in: 0...latestStart, using: &generator) : 0 + // 標本の間隔に揃えて、同じ位置が重なりやすくなるのを抑えつつ計算を安定させる。 + if profile.hop > 0 { start = (start / profile.hop).rounded(.down) * profile.hop } + start = min(start, max(0, latestStart)) + + let motion = profile.meanMotion(start: start, length: length) + // 以降の比較・記録は、動画全体の中での位置(窓の先頭からの位置 + 窓の開始位置)で行う。 + start += profile.offset + let range = start..<(start + length) + if honoringForbidden, let forbidden, + forbidden.videoID == profile.videoID, forbidden.range.overlaps(range) { + 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 } + score += 0.05 * Double.random(in: 0...1, using: &generator) + + if best == nil || score > best!.score { + best = (ClipChoice(videoID: profile.videoID, start: start), score) + } + } + return best?.choice + } + + // 禁止された区間を避けられる候補が見つからないときだけ、禁止なしでもう一度探す。 + return search(honoringForbidden: true, generator: &generator) + ?? search(honoringForbidden: false, generator: &generator) + } + + // MARK: - カット単位の差し替え + + /// `index` 番目のカットだけを、別の素材区間に選び直す。 + /// カットの枠(開始・長さ・盛り上がりの段階)は変えない。前後のカットと同じ動画は、他に選べる動画があるかぎり避け、 + /// 元の区間とは重ならない位置を選ぶ。 + /// - Parameters: + /// - excludedVideoIDs: 候補から外す動画。 + /// - forcedVideoID: 指定すると、その動画の区間だけから選ぶ。 + func replaceCut( + at index: Int, + in plan: CutPlan, + analysis: MusicAnalysis, + pool: [SourceMotionProfile], + seed: UInt64, + excluding excludedVideoIDs: Set = [], + forcing forcedVideoID: UUID? = nil + ) throws -> CutPlan { + guard plan.cuts.indices.contains(index) else { return plan } + let candidates = pool.filter { profile in + !excludedVideoIDs.contains(profile.videoID) && (forcedVideoID == nil || profile.videoID == forcedVideoID) + } + guard !candidates.isEmpty else { throw CutPlannerError.emptyPool } + + let original = plan.cuts[index] + var usage: [UUID: Int] = [:] + var usedRanges: [UUID: [Range]] = [:] + for (otherIndex, other) in plan.cuts.enumerated() where otherIndex != index { + usage[other.videoID, default: 0] += 1 + usedRanges[other.videoID, default: []].append(other.sourceStart..<(other.sourceStart + other.duration)) + } + var avoid = Set() + if forcedVideoID == nil { + if index > 0 { avoid.insert(plan.cuts[index - 1].videoID) } + 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 + + // カットの番号ごとに乱数を変える(同じ種でも、別のカットは別の選び方になる)。 + var generator = SeededGenerator(seed: seed &+ UInt64(index) &* 0x9E37_79B9_7F4A_7C15) + guard let choice = pickClip( + length: original.duration, + target: target, + pool: candidates, + avoidVideoIDs: avoid, + usage: usage, + usedRanges: usedRanges, + forbidden: (original.videoID, original.sourceStart..<(original.sourceStart + original.duration)), + generator: &generator + ) else { + throw CutPlannerError.noClipLongEnough + } + + var cuts = plan.cuts + cuts[index] = PlannedCut( + videoID: choice.videoID, + sourceStart: choice.start, + duration: original.duration, + timelineStart: original.timelineStart, + intensity: original.intensity + ) + return CutPlan(cuts: cuts, duration: plan.duration) + } + + /// `videoID` の動画を使っているカットを、すべて別の動画に選び直す。 + func replaceAllCuts( + usingVideo videoID: UUID, + in plan: CutPlan, + analysis: MusicAnalysis, + pool: [SourceMotionProfile], + seed: UInt64, + excluding excludedVideoIDs: Set = [] + ) throws -> CutPlan { + var result = plan + for index in plan.cuts.indices where plan.cuts[index].videoID == videoID { + result = try replaceCut( + at: index, + in: result, + analysis: analysis, + pool: pool, + seed: seed, + excluding: excludedVideoIDs.union([videoID]) + ) + } + return result + } +} diff --git a/ArkServer/Features/MusicVideo/Services/MusicVideoComposer.swift b/ArkServer/Features/MusicVideo/Services/MusicVideoComposer.swift new file mode 100644 index 0000000..ecf5247 --- /dev/null +++ b/ArkServer/Features/MusicVideo/Services/MusicVideoComposer.swift @@ -0,0 +1,484 @@ +// ArkServer/Features/MusicVideo/Services/MusicVideoComposer.swift + +import AVFoundation +import CoreGraphics +import Foundation + +/// 完成映像の画面サイズとフレームレート。 +nonisolated struct MusicVideoRenderSettings: Equatable, Sendable { + var width: Int + var height: Int + var framesPerSecond: Int + + static let landscapeFullHD = MusicVideoRenderSettings(width: 1920, height: 1080, framesPerSecond: 30) + static let landscapeHD = MusicVideoRenderSettings(width: 1280, height: 720, framesPerSecond: 30) + static let portraitFullHD = MusicVideoRenderSettings(width: 1080, height: 1920, framesPerSecond: 30) + static let portraitHD = MusicVideoRenderSettings(width: 720, height: 1280, framesPerSecond: 30) + + var size: CGSize { CGSize(width: width, height: height) } +} + +nonisolated enum MusicVideoComposerError: LocalizedError { + case emptyPlan + case missingSource(UUID) + case noVideoTrack(String) + case noAudioTrack + case cannotCreateTrack + case cannotCreateExporter + case exportFailed(String) + case invalidOutput(String) + + var errorDescription: String? { + switch self { + case .emptyPlan: + return "カット割りが空です." + case .missingSource: + return "素材動画のファイルが見つかりません." + case .noVideoTrack(let name): + return "素材動画に映像トラックがありません.(\(name))" + case .noAudioTrack: + return "音楽ファイルに音声トラックがありません." + case .cannotCreateTrack: + return "合成用のトラックを作成できませんでした." + case .cannotCreateExporter: + return "書き出しを開始できませんでした." + case .exportFailed(let reason): + return "書き出しに失敗しました.\(reason)" + case .invalidOutput(let reason): + return "書き出した動画が正しくありません.\(reason)" + } + } +} + +/// プレビュー再生と書き出しの両方に使う、合成済みの映像。 +nonisolated struct MusicVideoComposition: @unchecked Sendable { + let composition: AVMutableComposition + let videoComposition: AVMutableVideoComposition + /// 完成映像の長さ(秒)。 + let duration: Double + /// 画面サイズとフレームレート。書き出しのビットレートの計算にも使う。 + let render: MusicVideoRenderSettings + + func makePlayerItem() -> AVPlayerItem { + let item = AVPlayerItem(asset: composition) + item.videoComposition = videoComposition + return item + } +} + +/// `CutPlan` から1本の映像を組み立て、mp3 などの音楽を付けて書き出す。 +/// +/// 1拍ごとのカットだと数百カットになるので、映像トラックは1本を使い回し、 +/// 画面いっぱいに拡大する変換だけをカットの切り替え時刻ごとに差し替える。 +nonisolated struct MusicVideoComposer: Sendable { + /// 時刻を丸める分解能。30/24/25fps のどれの1フレームも割り切れる値。 + private static let timescale: CMTimeScale = 600 + + // MARK: - 合成 + + func makeComposition( + plan: CutPlan, + sourceURLs: [UUID: URL], + audioURL: URL, + render: MusicVideoRenderSettings + ) async throws -> MusicVideoComposition { + guard !plan.cuts.isEmpty else { throw MusicVideoComposerError.emptyPlan } + + let composition = AVMutableComposition() + guard let videoTrack = composition.addMutableTrack( + withMediaType: .video, + preferredTrackID: kCMPersistentTrackID_Invalid + ) else { + throw MusicVideoComposerError.cannotCreateTrack + } + + var sources: [UUID: SourceTrack] = [:] + let layerInstruction = AVMutableVideoCompositionLayerInstruction(assetTrack: videoTrack) + + for cut in plan.cuts { + 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 start = Self.time(cut.timelineStart) + let end = Self.time(cut.timelineEnd) + let length = CMTimeSubtract(end, start) + guard length > .zero else { continue } + + var sourceStart = Self.time(cut.sourceStart) + let sourceEnd = CMTimeAdd(sourceStart, length) + // 素材の終わりを少しでも越えるなら、範囲に収まるまで手前にずらす。 + if sourceEnd > source.timeRange.end { + sourceStart = max(source.timeRange.start, CMTimeSubtract(source.timeRange.end, length)) + } + try videoTrack.insertTimeRange( + CMTimeRange(start: sourceStart, duration: length), + of: source.track, + at: start + ) + layerInstruction.setTransform( + Self.fillTransform(for: source, renderSize: render.size), + at: start + ) + } + + let totalDuration = Self.time(plan.duration) + try await addAudio(from: audioURL, to: composition, duration: totalDuration) + + let instruction = AVMutableVideoCompositionInstruction() + instruction.timeRange = CMTimeRange(start: .zero, duration: composition.duration) + instruction.backgroundColor = CGColor(gray: 0, alpha: 1) + instruction.layerInstructions = [layerInstruction] + + 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 + + return MusicVideoComposition( + composition: composition, + videoComposition: videoComposition, + duration: composition.duration.seconds, + render: render + ) + } + + private struct SourceTrack { + /// トラックは元のアセットが解放されると使えなくなる(挿入時に -12780 で失敗する)ので、アセットも持ち続ける。 + let asset: AVURLAsset + let track: AVAssetTrack + let timeRange: CMTimeRange + let naturalSize: CGSize + let preferredTransform: CGAffineTransform + } + + private func loadSource(url: URL) async throws -> SourceTrack { + let asset = AVURLAsset(url: url) + guard let track = try await asset.loadTracks(withMediaType: .video).first else { + throw MusicVideoComposerError.noVideoTrack(url.lastPathComponent) + } + let (timeRange, naturalSize, transform) = try await track.load(.timeRange, .naturalSize, .preferredTransform) + return SourceTrack( + asset: asset, + track: track, + timeRange: timeRange, + naturalSize: naturalSize, + preferredTransform: transform + ) + } + + private func addAudio( + from url: URL, + to composition: AVMutableComposition, + duration: CMTime + ) async throws { + let asset = AVURLAsset(url: url) + guard let sourceTrack = try await asset.loadTracks(withMediaType: .audio).first else { + throw MusicVideoComposerError.noAudioTrack + } + guard let audioTrack = composition.addMutableTrack( + withMediaType: .audio, + preferredTrackID: kCMPersistentTrackID_Invalid + ) else { + throw MusicVideoComposerError.cannotCreateTrack + } + let available = try await sourceTrack.load(.timeRange) + let length = min(duration, available.duration) + try audioTrack.insertTimeRange( + CMTimeRange(start: available.start, duration: length), + of: sourceTrack, + at: .zero + ) + } + + /// 素材を画面いっぱいに(はみ出す部分は切り落として)敷き詰める変換。向き(回転)も反映する。 + private static func fillTransform(for source: SourceTrack, renderSize: CGSize) -> 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 scaledSize = CGSize(width: displaySize.width * scale, height: displaySize.height * scale) + let translation = CGAffineTransform( + translationX: (renderSize.width - scaledSize.width) / 2, + y: (renderSize.height - scaledSize.height) / 2 + ) + return source.preferredTransform + .concatenating(CGAffineTransform(scaleX: scale, y: scale)) + .concatenating(translation) + } + + private static func time(_ seconds: Double) -> CMTime { + CMTime(seconds: seconds, preferredTimescale: timescale) + } + + // MARK: - 書き出し + + /// 合成した映像を mp4(H.264 + AAC)に書き出す。`progress` には 0〜1 が渡される。 + /// 画面サイズは保ったまま、`quality` に応じた映像のビットレートで書き出す。 + func export( + _ composed: MusicVideoComposition, + to outputURL: URL, + quality: MusicVideoExportQuality = .high, + progress: @escaping @Sendable (Double) async -> Void = { _ in } + ) async throws { + try? FileManager.default.removeItem(at: outputURL) + try FileManager.default.createDirectory( + at: outputURL.deletingLastPathComponent(), + withIntermediateDirectories: true + ) + + let job = try ExportJob(composed: composed, outputURL: outputURL, quality: quality) + do { + try await withTaskCancellationHandler { + try await job.run(progress: progress) + } onCancel: { + job.cancel() + } + } catch is CancellationError { + try? FileManager.default.removeItem(at: outputURL) + throw CancellationError() + } catch { + try? FileManager.default.removeItem(at: outputURL) + if let known = error as? MusicVideoComposerError { throw known } + throw MusicVideoComposerError.exportFailed(error.localizedDescription) + } + await progress(1) + + try await validateOutput(at: outputURL, expectedDuration: composed.duration) + } + + /// 読み出し(合成済みの映像と音声)と書き込み(H.264 + AAC)をつなぎ、順に流し込む。 + private final class ExportJob: @unchecked Sendable { + private let reader: AVAssetReader + private let writer: AVAssetWriter + private let videoOutput: AVAssetReaderVideoCompositionOutput + private let videoInput: AVAssetWriterInput + private let audioOutput: AVAssetReaderAudioMixOutput? + private let audioInput: AVAssetWriterInput? + private let duration: Double + /// 読み出しの開始(startReading)中に中止(cancelReading)を呼ぶと AVFoundation の内部で落ちるので、 + /// 開始中の取り消しは、開始が終わってから実行する。 + private enum Phase { case idle, starting, running } + private let lock = NSLock() + private var isCancelled = false + private var phase: Phase = .idle + + init(composed: MusicVideoComposition, outputURL: URL, quality: MusicVideoExportQuality) throws { + let render = composed.render + duration = composed.duration + reader = try AVAssetReader(asset: composed.composition) + + videoOutput = AVAssetReaderVideoCompositionOutput( + videoTracks: composed.composition.tracks(withMediaType: .video), + videoSettings: [ + kCVPixelBufferPixelFormatTypeKey as String: kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange + ] + ) + videoOutput.videoComposition = composed.videoComposition + videoOutput.alwaysCopiesSampleData = false + guard reader.canAdd(videoOutput) else { throw MusicVideoComposerError.cannotCreateExporter } + reader.add(videoOutput) + + let audioTracks = composed.composition.tracks(withMediaType: .audio) + if audioTracks.isEmpty { + audioOutput = nil + } else { + let output = AVAssetReaderAudioMixOutput( + audioTracks: audioTracks, + audioSettings: [ + AVFormatIDKey: kAudioFormatLinearPCM, + AVLinearPCMBitDepthKey: 32, + AVLinearPCMIsFloatKey: true, + AVLinearPCMIsBigEndianKey: false, + AVLinearPCMIsNonInterleaved: false, + AVSampleRateKey: MusicVideoExportQuality.audioSampleRate, + AVNumberOfChannelsKey: 2 + ] + ) + output.alwaysCopiesSampleData = false + guard reader.canAdd(output) else { throw MusicVideoComposerError.cannotCreateExporter } + reader.add(output) + audioOutput = output + } + + writer = try AVAssetWriter(outputURL: outputURL, fileType: .mp4) + videoInput = AVAssetWriterInput( + mediaType: .video, + outputSettings: [ + AVVideoCodecKey: AVVideoCodecType.h264, + AVVideoWidthKey: render.width, + AVVideoHeightKey: render.height, + AVVideoColorPropertiesKey: [ + AVVideoColorPrimariesKey: AVVideoColorPrimaries_ITU_R_709_2, + AVVideoTransferFunctionKey: AVVideoTransferFunction_ITU_R_709_2, + AVVideoYCbCrMatrixKey: AVVideoYCbCrMatrix_ITU_R_709_2 + ], + AVVideoCompressionPropertiesKey: [ + AVVideoAverageBitRateKey: quality.videoBitRate(for: render), + AVVideoProfileLevelKey: AVVideoProfileLevelH264HighAutoLevel, + AVVideoMaxKeyFrameIntervalKey: render.framesPerSecond * 2, + AVVideoExpectedSourceFrameRateKey: render.framesPerSecond + ] + ] + ) + videoInput.expectsMediaDataInRealTime = false + guard writer.canAdd(videoInput) else { throw MusicVideoComposerError.cannotCreateExporter } + writer.add(videoInput) + + if audioOutput != nil { + let input = AVAssetWriterInput( + mediaType: .audio, + outputSettings: [ + AVFormatIDKey: kAudioFormatMPEG4AAC, + AVSampleRateKey: MusicVideoExportQuality.audioSampleRate, + AVNumberOfChannelsKey: 2, + AVEncoderBitRateKey: MusicVideoExportQuality.audioBitRate + ] + ) + input.expectsMediaDataInRealTime = false + guard writer.canAdd(input) else { throw MusicVideoComposerError.cannotCreateExporter } + writer.add(input) + audioInput = input + } else { + audioInput = nil + } + } + + func cancel() { + lock.lock() + isCancelled = true + let shouldCancelNow = phase == .running + lock.unlock() + // 読み出しを止めると、流し込みの側は終わりまで読んだものとして自然に閉じる。 + // まだ始まっていない/開始中なら、run() が開始後に止める。 + if shouldCancelNow { reader.cancelReading() } + } + + private var wasCancelled: Bool { + lock.lock(); defer { lock.unlock() } + return isCancelled + } + + func run(progress: @escaping @Sendable (Double) async -> Void) async throws { + lock.lock() + if isCancelled { lock.unlock(); throw CancellationError() } + phase = .starting + lock.unlock() + + let started = reader.startReading() + + lock.lock() + phase = .running + let cancelledWhileStarting = isCancelled + lock.unlock() + if cancelledWhileStarting { + reader.cancelReading() + throw CancellationError() + } + guard started else { + throw MusicVideoComposerError.exportFailed(reader.error?.localizedDescription ?? "読み出しを開始できませんでした.") + } + guard writer.startWriting() else { + reader.cancelReading() + throw MusicVideoComposerError.exportFailed(writer.error?.localizedDescription ?? "書き込みを開始できませんでした.") + } + writer.startSession(atSourceTime: .zero) + + async let videoDone: Void = pump(videoInput, from: videoOutput, progress: progress) + async let audioDone: Void = { + if let audioInput, let audioOutput { await pump(audioInput, from: audioOutput, progress: nil) } + }() + _ = await (videoDone, audioDone) + + if wasCancelled { + writer.cancelWriting() + throw CancellationError() + } + if reader.status == .failed { + writer.cancelWriting() + throw MusicVideoComposerError.exportFailed(reader.error?.localizedDescription ?? "読み出しに失敗しました.") + } + await writer.finishWriting() + guard writer.status == .completed else { + throw MusicVideoComposerError.exportFailed(writer.error?.localizedDescription ?? "書き込みに失敗しました.") + } + } + + /// 読み出し側から取り出したサンプルを、書き込み側が受け取れるたびに渡す。 + private func pump( + _ input: AVAssetWriterInput, + from output: AVAssetReaderOutput, + progress: (@Sendable (Double) async -> Void)? + ) async { + let queue = DispatchQueue(label: "musicvideo.export.\(input.mediaType.rawValue)") + let total = max(duration, 0.001) + // 書き出し側は、閉じた後も「受け取れます」と呼び出し直してくることがある。 + // そのとき、解放済みの読み出し側に触らないよう、(1)終わったら何もしない (2)呼び出しが続く間は reader を保持する。 + let reader = self.reader + await withCheckedContinuation { (continuation: CheckedContinuation) in + var lastReported = -1.0 + var isFinished = false + input.requestMediaDataWhenReady(on: queue) { + withExtendedLifetime(reader) { + guard !isFinished else { return } + while input.isReadyForMoreMediaData { + guard let buffer = output.copyNextSampleBuffer() else { + isFinished = true + input.markAsFinished() + continuation.resume() + return + } + if !input.append(buffer) { + isFinished = true + input.markAsFinished() + continuation.resume() + return + } + if let progress { + let fraction = min(1, max(0, CMSampleBufferGetPresentationTimeStamp(buffer).seconds / total)) + if fraction - lastReported >= 0.01 { + lastReported = fraction + Task { await progress(fraction) } + } + } + } + } + } + } + } + } + + /// 書き出したファイルに映像と音声があり、長さが想定と大きくずれていないことを確かめる。 + private func validateOutput(at url: URL, expectedDuration: Double) async throws { + let asset = AVURLAsset(url: url) + let duration = try await asset.load(.duration).seconds + let hasVideo = try await !asset.loadTracks(withMediaType: .video).isEmpty + let hasAudio = try await !asset.loadTracks(withMediaType: .audio).isEmpty + guard hasVideo else { + try? FileManager.default.removeItem(at: url) + throw MusicVideoComposerError.invalidOutput("映像がありません.") + } + guard hasAudio else { + try? FileManager.default.removeItem(at: url) + throw MusicVideoComposerError.invalidOutput("音声がありません.") + } + guard abs(duration - expectedDuration) < 1.0 else { + try? FileManager.default.removeItem(at: url) + throw MusicVideoComposerError.invalidOutput("長さが想定(\(Int(expectedDuration))秒)と合いません.") + } + } +} diff --git a/ArkServer/Features/MusicVideo/ViewModels/MusicVideoViewModel.swift b/ArkServer/Features/MusicVideo/ViewModels/MusicVideoViewModel.swift new file mode 100644 index 0000000..0468e48 --- /dev/null +++ b/ArkServer/Features/MusicVideo/ViewModels/MusicVideoViewModel.swift @@ -0,0 +1,626 @@ +// ArkServer/Features/MusicVideo/ViewModels/MusicVideoViewModel.swift + +import AVFoundation +import Combine +import Foundation + +/// 作成の進み具合。 +enum MusicVideoPhase: Equatable { + case idle + case analyzingMusic + case analyzingSources(completed: Int, total: Int) + case composing + case ready + case exporting(progress: Double) +} + +/// 「指定の動画に差し替え」のメニューに出す動画。 +struct MusicVideoPoolVideo: Identifiable, Equatable { + let id: UUID + let name: String +} + +/// 音楽に合わせた映像(HMV)の作成を進める。 +/// 曲の解析・素材の解析・カット割り・編集・プレビュー・書き出しの状態をここが持ち、画面を切り替えても保たれる。 +@MainActor +final class MusicVideoViewModel: ObservableObject { + // MARK: 入力(変更すると設定として保存する) + @Published private(set) var musicURL: URL? + @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() } } + @Published var exportQuality: MusicVideoExportQuality = .high { didSet { savePreferences() } } + @Published private(set) var musicFolderURL: URL? + @Published private(set) var recentMusicURLs: [URL] = [] + /// 選んだ素材のうち、条件(動画・ゴミ箱外・長さ)を満たす動画の本数。ファイルの存在は確認していない。 + @Published private(set) var candidateCount = 0 + + // MARK: 結果 + @Published private(set) var analysis: MusicAnalysis? + @Published private(set) var plan: CutPlan? + @Published private(set) var phase: MusicVideoPhase = .idle + @Published private(set) var playbackTime: Double = 0 + @Published var errorMessage: String? + @Published var resultMessage: String? + /// 実際に使った動画の本数。 + @Published private(set) var usedVideoCount = 0 + /// 選ばれていたが、実ファイルが見つからなかった動画の本数。 + @Published private(set) var missingFileCount = 0 + /// 素材の解析の残り時間の目安(秒)。 + @Published private(set) var estimatedRemaining: TimeInterval? + + // MARK: 編集 + @Published private(set) var selectedCutIndex: Int? + @Published private(set) var isApplyingEdit = false + @Published private(set) var excludedVideoIDs: Set = [] + @Published private(set) var poolVideos: [MusicVideoPoolVideo] = [] + @Published private(set) var undoDepth = 0 + @Published private(set) var redoDepth = 0 + + let player = AVPlayer() + + private weak var dataManager: LibraryViewModel? + private var libraryObservation: AnyCancellable? + private let preferencesStore = MusicVideoPreferencesStore() + private var preferences = MusicVideoPreferences() + private var isRestoringPreferences = false + + private var pool: [SourceMotionProfile] = [] + /// `pool` を作ったときの素材の組み合わせ。変わっていなければ作り直しで再解析しない。 + private var poolSourceIDs: Set = [] + private var sourceURLs: [UUID: URL] = [:] + private var sourceItems: [UUID: VideoItem] = [:] + 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 workTask: Task? + private var editTask: Task? + private var timeObserver: Any? + + private static let undoLimit = 50 + + // MARK: - 状態の判定 + + var isWorking: Bool { + switch phase { + case .idle, .ready: return false + default: return true + } + } + + var musicTitle: String? { + musicURL?.deletingPathExtension().lastPathComponent + } + + /// 「映像を作る」を押せない理由。押せるときは nil。 + var generateBlocker: String? { + if musicURL == nil { return "曲を選んでください" } + if analysis == nil { return "曲を解析しています…" } + if candidateCount == 0 { return "素材の動画を選んでください" } + return nil + } + + var canGenerate: Bool { generateBlocker == nil && !isWorking } + var canExport: Bool { composed != nil && plan != nil && !isWorking && !isApplyingEdit } + var canEdit: Bool { plan != nil && !isWorking && !isApplyingEdit } + var canUndo: Bool { canEdit && undoDepth > 0 } + var canRedo: Bool { canEdit && redoDepth > 0 } + + var selectedCut: PlannedCut? { + guard let plan, let index = selectedCutIndex, plan.cuts.indices.contains(index) else { return nil } + return plan.cuts[index] + } + + /// 前回使った曲(今開いている曲とは別のもの)。 + var lastMusicURL: URL? { + recentMusicURLs.first { $0 != musicURL } + } + + init() { + 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 + } + } + } + + deinit { + if let timeObserver { player.removeTimeObserver(timeObserver) } + } + + // MARK: - ライブラリとの接続・設定の復元 + + /// 画面が最初に開いたときに呼ぶ。保存した設定を復元し、ライブラリの変化を見て素材の件数を更新する。 + func attach(dataManager: LibraryViewModel) { + guard self.dataManager !== dataManager else { return } + self.dataManager = dataManager + restorePreferences(dataManager: dataManager) + libraryObservation = dataManager.$videos + .combineLatest(dataManager.$albums) + .debounce(for: .milliseconds(400), scheduler: DispatchQueue.main) + .sink { [weak self] _, _ in + MainActor.assumeIsolated { self?.recountCandidates() } + } + } + + private func restorePreferences(dataManager: LibraryViewModel) { + var stored = preferencesStore.load() + // ライブラリがまだ読み込まれていないときは、選択を捨てずにそのまま使う。 + if !dataManager.videos.isEmpty { + stored = stored.pruned( + validAlbumIDs: Set(dataManager.albums.map(\.id)), + validVideoIDs: Set(dataManager.videos.map(\.id)) + ) + } + preferences = stored + isRestoringPreferences = true + cutStyle = stored.cutStyle + renderPreset = stored.renderPreset + exportQuality = stored.exportQuality + selectedAlbumIDs = Set(stored.selectedAlbumIDs) + selectedVideoIDs = Set(stored.selectedVideoIDs) + includeFavorites = stored.includeFavorites + isRestoringPreferences = false + musicFolderURL = stored.musicFolderPath.map { URL(fileURLWithPath: $0, isDirectory: true) } + refreshRecentMusic() + recountCandidates() + } + + private func savePreferences() { + guard !isRestoringPreferences else { return } + preferences.cutStyle = cutStyle + preferences.renderPreset = renderPreset + preferences.exportQuality = exportQuality + preferences.selectedAlbumIDs = Array(selectedAlbumIDs) + preferences.selectedVideoIDs = Array(selectedVideoIDs) + preferences.includeFavorites = includeFavorites + preferencesStore.save(preferences) + } + + private func selectionDidChange() { + guard !isRestoringPreferences else { return } + recountCandidates() + savePreferences() + } + + private func recountCandidates() { + guard let dataManager else { candidateCount = 0; return } + candidateCount = MusicVideoSourceSelection.candidateIDs( + videos: dataManager.videos, + albums: dataManager.albums, + selectedAlbumIDs: selectedAlbumIDs, + selectedVideoIDs: selectedVideoIDs, + includeFavorites: includeFavorites + ).count + } + + private func refreshRecentMusic() { + recentMusicURLs = preferences.recentMusicPaths + .map { URL(fileURLWithPath: $0) } + .filter { FileManager.default.fileExists(atPath: $0.path) } + } + + func clearSourceSelection() { + isRestoringPreferences = true + selectedAlbumIDs = [] + selectedVideoIDs = [] + includeFavorites = false + isRestoringPreferences = false + selectionDidChange() + } + + func setMusicFolder(_ url: URL) { + musicFolderURL = url + preferences.musicFolderPath = url.path + preferencesStore.save(preferences) + } + + // MARK: - 音楽 + + func chooseMusic(_ url: URL) { + cancelWork() + clearResult() + musicURL = url + analysis = nil + preferences.recordRecentMusic(url.path) + preferencesStore.save(preferences) + refreshRecentMusic() + phase = .analyzingMusic + workTask = Task { [weak self] in + do { + let result = try await BeatAnalyzer().analyze(url: url) + guard let self, !Task.isCancelled else { return } + self.analysis = result + self.phase = .idle + } catch is CancellationError { + self?.phase = .idle + } catch { + guard let self else { return } + self.musicURL = nil + self.phase = .idle + self.errorMessage = error.localizedDescription + } + } + } + + // MARK: - 作成 + + /// 選んだ素材から映像を作る。素材の組み合わせが前回と同じなら、解析済みの動きを使い回す。 + func generate(dataManager: LibraryViewModel, newSeed: Bool = true) { + guard let musicURL, let analysis, !isWorking else { return } + let resolved = resolveSources(dataManager: dataManager) + let sources = resolved.sources + guard !sources.isEmpty else { + errorMessage = "使える素材動画がありません.選んだ動画のファイルが見つからないか,除外した動画だけが残っています." + return + } + missingFileCount = resolved.missing + if newSeed { seed = UInt64.random(in: 0...UInt64.max) } + clearResult() + + let seed = self.seed + let style = cutStyle + let render = renderPreset.settings + let sourceIDs = Set(sources.map(\.videoID)) + let reusablePool = (sourceIDs == poolSourceIDs && !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)) + : .composing + estimatedRemaining = nil + let startedAt = Date() + + workTask = Task { [weak self] in + do { + let motion: [SourceMotionProfile] + if let reusablePool { + motion = reusablePool + } else { + var builder = ClipPoolBuilder() + builder.cacheDirectory = cacheDirectory + motion = try await builder.build(sources: sources, seed: seed) { completed, total in + await MainActor.run { + self?.phase = .analyzingSources(completed: completed, total: total) + self?.updateEstimate(completed: completed, total: total, since: startedAt) + } + } + } + try Task.checkCancellation() + + self?.phase = .composing + self?.estimatedRemaining = nil + var planner = CutPlanner() + planner.style = style + 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 + ) + try Task.checkCancellation() + + guard let self else { return } + self.pool = motion + self.poolSourceIDs = sourceIDs + self.sourceURLs = urls + self.sourceItems = items + self.undoStack = [] + self.redoStack = [] + self.syncHistoryDepth() + self.editCounter = 0 + self.usedVideoCount = Set(cutPlan.cuts.map(\.videoID)).count + self.poolVideos = Self.makePoolVideos(pool: motion, items: items) + self.plan = cutPlan + self.composed = result + self.selectedCutIndex = nil + self.player.replaceCurrentItem(with: result.makePlayerItem()) + await self.player.seek(to: .zero) + self.phase = .ready + } catch is CancellationError { + self?.phase = .idle + self?.estimatedRemaining = nil + } catch { + self?.phase = .idle + self?.estimatedRemaining = nil + self?.errorMessage = error.localizedDescription + } + } + } + + /// 同じ素材で、別のカット割りを作る。 + func regenerate(dataManager: LibraryViewModel) { + generate(dataManager: dataManager, newSeed: true) + } + + private func updateEstimate(completed: Int, total: Int, since start: Date) { + // 最初の数本は結果のキャッシュが効いて速いことがあるので、ある程度進んでから見積もる。 + guard completed >= 3, completed < total else { estimatedRemaining = nil; return } + let perVideo = Date().timeIntervalSince(start) / Double(completed) + let remaining = perVideo * Double(total - completed) + estimatedRemaining = remaining >= 5 ? remaining : nil + } + + private static func makePoolVideos(pool: [SourceMotionProfile], items: [UUID: VideoItem]) -> [MusicVideoPoolVideo] { + var seen = Set() + var videos: [MusicVideoPoolVideo] = [] + for profile in pool where seen.insert(profile.videoID).inserted { + videos.append(MusicVideoPoolVideo(id: profile.videoID, name: items[profile.videoID]?.originalFilename ?? "(不明な動画)")) + } + return videos.sorted { $0.name.localizedStandardCompare($1.name) == .orderedAscending } + } + + // MARK: - カットの編集 + + func selectCut(at time: Double) { + guard let plan else { return } + selectCut(index: plan.cutIndex(at: time)) + } + + func selectCut(index: Int?) { + guard let plan else { return } + guard let index, plan.cuts.indices.contains(index) else { + selectedCutIndex = nil + return + } + selectedCutIndex = index + seek(to: plan.cuts[index].timelineStart) + } + + func selectAdjacentCut(by step: Int) { + guard let plan, !plan.cuts.isEmpty else { return } + let current = selectedCutIndex ?? (plan.cutIndex(at: playbackTime) ?? 0) + selectCut(index: min(max(0, current + step), plan.cuts.count - 1)) + } + + /// 選んでいるカットだけを、別の素材区間にする。 + func replaceSelectedCut() { + guard let index = selectedCutIndex else { return } + applyEdit { planner, plan, analysis, pool, seed, excluded in + try planner.replaceCut(at: index, in: plan, analysis: analysis, pool: pool, seed: seed, excluding: excluded) + } + } + + /// 選んでいるカットの動画を使っているカットを、すべて別の動画にする。 + func replaceAllUsesOfSelectedVideo() { + guard let video = selectedCut?.videoID else { return } + applyEdit { planner, plan, analysis, pool, seed, excluded in + try planner.replaceAllCuts(usingVideo: video, in: plan, analysis: analysis, pool: pool, seed: seed, excluding: excluded) + } + } + + /// 選んでいるカットの動画を、以後の候補から外す(今のカット割りでの使用もすべて差し替える)。 + func excludeSelectedVideo() { + guard let video = selectedCut?.videoID else { return } + excludedVideoIDs.insert(video) + applyEdit { planner, plan, analysis, pool, seed, excluded in + try planner.replaceAllCuts(usingVideo: video, in: plan, analysis: analysis, pool: pool, seed: seed, excluding: excluded) + } + } + + func clearExclusions() { + excludedVideoIDs = [] + } + + /// 選んでいるカットを、指定した動画の区間にする。 + func replaceSelectedCut(withVideo video: UUID) { + guard let index = selectedCutIndex else { return } + applyEdit { planner, plan, analysis, pool, seed, _ in + try planner.replaceCut(at: index, in: plan, analysis: analysis, pool: pool, seed: seed, forcing: video) + } + } + + func undo() { + guard canUndo, let current = plan, let previous = undoStack.popLast() else { return } + redoStack.append(current) + syncHistoryDepth() + recompose(previous) + } + + func redo() { + guard canRedo, let current = plan, let next = redoStack.popLast() else { return } + undoStack.append(current) + syncHistoryDepth() + recompose(next) + } + + private func syncHistoryDepth() { + undoDepth = undoStack.count + redoDepth = redoStack.count + } + + private func applyEdit( + _ transform: (CutPlanner, CutPlan, MusicAnalysis, [SourceMotionProfile], UInt64, Set) throws -> CutPlan + ) { + guard canEdit, let current = plan, let analysis else { return } + editCounter += 1 + let editSeed = seed &+ editCounter &* 0xD1B5_4A32_D192_ED03 + do { + var planner = CutPlanner() + planner.style = cutStyle + let edited = try transform(planner, current, analysis, pool, editSeed, excludedVideoIDs) + guard edited != current else { return } + undoStack.append(current) + if undoStack.count > Self.undoLimit { undoStack.removeFirst(undoStack.count - Self.undoLimit) } + redoStack = [] + syncHistoryDepth() + recompose(edited) + } catch { + errorMessage = error.localizedDescription + } + } + + /// カット割りを入れ替えて合成し直し、再生位置と再生状態を保ったままプレイヤーを差し替える。 + private func recompose(_ newPlan: CutPlan) { + guard let musicURL else { return } + let render = renderPreset.settings + 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 + ) + guard let self, !Task.isCancelled else { return } + let time = self.player.currentTime() + let wasPlaying = self.player.timeControlStatus != .paused + self.plan = newPlan + self.composed = result + self.usedVideoCount = Set(newPlan.cuts.map(\.videoID)).count + self.player.replaceCurrentItem(with: result.makePlayerItem()) + await self.player.seek(to: time, toleranceBefore: .zero, toleranceAfter: .zero) + if wasPlaying { self.player.play() } + self.isApplyingEdit = false + } catch is CancellationError { + self?.isApplyingEdit = false + } catch { + self?.isApplyingEdit = false + self?.errorMessage = error.localizedDescription + } + } + } + + // MARK: - 書き出し + + /// 書き出して「HMV」アルバムに追加する。 + func exportToLibrary(dataManager: LibraryViewModel) { + 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) を追加しました." + } + } + + /// 書き出して、選んだ場所にファイルとして保存する(ライブラリには追加しない)。 + func exportToFile(at destination: URL) { + export { url in + try? FileManager.default.removeItem(at: destination) + try FileManager.default.moveItem(at: url, to: destination) + return "\(destination.lastPathComponent) を保存しました." + } + } + + var suggestedFileName: String { + Self.outputFileName(musicTitle: musicTitle ?? "music") + } + + private func export(finish: @escaping @MainActor (URL) async throws -> String) { + guard let composed, canExport else { return } + player.pause() + phase = .exporting(progress: 0) + let temporaryURL = FileManager.default.temporaryDirectory + .appendingPathComponent("hmv-\(UUID().uuidString).mp4") + let quality = exportQuality + + workTask = Task { [weak self] in + defer { try? FileManager.default.removeItem(at: temporaryURL) } + do { + try await MusicVideoComposer().export(composed, to: temporaryURL, quality: quality) { fraction in + await MainActor.run { self?.phase = .exporting(progress: fraction) } + } + try Task.checkCancellation() + let message = try await finish(temporaryURL) + self?.phase = .ready + self?.resultMessage = message + } catch is CancellationError { + self?.phase = .ready + } catch { + self?.phase = .ready + self?.errorMessage = error.localizedDescription + } + } + } + + private func hmvAlbumID(in dataManager: LibraryViewModel) -> UUID? { + if let existing = dataManager.albums.first(where: { $0.name == Self.hmvAlbumName && $0.type == .video }) { + return existing.id + } + return dataManager.createAlbum(name: Self.hmvAlbumName, type: .video) + } + + static let hmvAlbumName = "HMV" + + static func outputFileName(musicTitle: String, date: Date = Date()) -> String { + let formatter = DateFormatter() + formatter.locale = Locale(identifier: "en_US_POSIX") + formatter.dateFormat = "yyyyMMdd-HHmm" + // ファイル名に使えない文字を取り除く。 + let invalid = CharacterSet(charactersIn: "/:\\?%*|\"<>").union(.controlCharacters) + let safeTitle = musicTitle.components(separatedBy: invalid).joined(separator: "_") + return "HMV_\(safeTitle)_\(formatter.string(from: date)).mp4" + } + + // MARK: - 素材の解決 + + /// 選択内容から、実際に使える動画(実ファイルがあり、除外していない)を集める。映像を作る直前にだけ呼ぶ。 + func resolveSources(dataManager: LibraryViewModel) -> (sources: [ClipPoolSource], items: [UUID: VideoItem], missing: Int) { + let ids = MusicVideoSourceSelection.candidateIDs( + videos: dataManager.videos, + albums: dataManager.albums, + selectedAlbumIDs: selectedAlbumIDs, + selectedVideoIDs: selectedVideoIDs, + includeFavorites: includeFavorites + ) + let wanted = Set(ids).subtracting(excludedVideoIDs) + var sources: [ClipPoolSource] = [] + var items: [UUID: VideoItem] = [:] + var missing = 0 + for item in dataManager.videos where wanted.contains(item.id) { + guard let url = dataManager.fileURL(for: item) else { missing += 1; continue } + sources.append(ClipPoolSource(videoID: item.id, url: url, duration: item.duration)) + items[item.id] = item + } + return (sources, items, missing) + } + + /// 編集パネルのサムネイルや名前に使う、素材の動画情報。 + func sourceItem(for id: UUID) -> VideoItem? { + sourceItems[id] + } + + // MARK: - 再生・状態 + + func seek(to seconds: Double) { + player.seek(to: CMTime(seconds: seconds, preferredTimescale: 600), toleranceBefore: .zero, toleranceAfter: .zero) + } + + func pausePlayback() { + player.pause() + } + + func cancelWork() { + workTask?.cancel() + workTask = nil + if isWorking { phase = composed == nil ? .idle : .ready } + estimatedRemaining = nil + } + + private func clearResult() { + editTask?.cancel() + isApplyingEdit = false + player.pause() + player.replaceCurrentItem(with: nil) + plan = nil + composed = nil + selectedCutIndex = nil + playbackTime = 0 + } + + func clearError() { errorMessage = nil } + func clearResultMessage() { resultMessage = nil } +} diff --git a/ArkServer/Features/MusicVideo/Views/MusicTimelineView.swift b/ArkServer/Features/MusicVideo/Views/MusicTimelineView.swift new file mode 100644 index 0000000..609bb4c --- /dev/null +++ b/ArkServer/Features/MusicVideo/Views/MusicTimelineView.swift @@ -0,0 +1,148 @@ +// ArkServer/Features/MusicVideo/Views/MusicTimelineView.swift + +import SwiftUI + +/// 曲の盛り上がり・拍・カットの切り替え位置・再生位置を1本の帯に重ねて見せる。 +/// クリックやドラッグで再生位置を動かせる。 +struct MusicTimelineView: View { + let analysis: MusicAnalysis + let plan: CutPlan? + let playbackTime: Double + /// 選択中のカットの番号。タイムライン上で強調する。 + var selectedCutIndex: Int? = nil + /// ドラッグ中に呼ばれる(再生位置を動かす)。 + let onSeek: (Double) -> Void + /// クリックまたはドラッグの終わりに呼ばれる(その位置のカットを選ぶ)。 + var onSelect: (Double) -> Void = { _ in } + + var body: some View { + Canvas { context, size in + draw(in: &context, size: size) + } + .frame(height: 96) + .background( + RoundedRectangle(cornerRadius: 8, style: .continuous) + .fill(NeomorphicTheme.control) + ) + .clipShape(RoundedRectangle(cornerRadius: 8, style: .continuous)) + .overlay { + // クリック位置は Canvas の実際の幅に対する割合で扱う。 + GeometryReader { proxy in + Color.clear + .contentShape(Rectangle()) + .gesture( + DragGesture(minimumDistance: 0) + .onChanged { value in + guard let time = time(at: value.location.x, width: proxy.size.width) else { return } + onSeek(time) + } + .onEnded { value in + guard let time = time(at: value.location.x, width: proxy.size.width) else { return } + onSelect(time) + } + ) + } + } + .accessibilityLabel("曲の盛り上がりとカット位置") + .help("クリックでそのカットを選択,ドラッグで再生位置を動かせます") + } + + private func time(at x: CGFloat, width: CGFloat) -> Double? { + guard analysis.duration > 0, width > 0 else { return nil } + return min(1, max(0, Double(x / width))) * analysis.duration + } + + private func draw(in context: inout GraphicsContext, size: CGSize) { + guard analysis.duration > 0, size.width > 0 else { return } + let duration = analysis.duration + func x(_ time: Double) -> CGFloat { CGFloat(time / duration) * size.width } + + // 盛り上がりの段階を、背景の濃さで示す。 + let hop = analysis.energyHop + var runStart = 0 + for index in 1...max(1, analysis.intensity.count) { + let isEnd = index >= analysis.intensity.count + if isEnd || analysis.intensity[index] != analysis.intensity[runStart] { + guard runStart < analysis.intensity.count else { break } + let level = analysis.intensity[runStart] + let rect = CGRect( + x: x(Double(runStart) * hop), + y: 0, + width: max(1, x(Double(min(index, analysis.intensity.count)) * hop) - x(Double(runStart) * hop)), + height: size.height + ) + context.fill(Path(rect), with: .color(NeomorphicTheme.accent.opacity(bandOpacity(level)))) + runStart = index + } + } + + // 選択中のカット。 + if let plan, let index = selectedCutIndex, plan.cuts.indices.contains(index) { + let cut = plan.cuts[index] + let rect = CGRect( + x: x(cut.timelineStart), + y: 0, + width: max(3, x(cut.timelineEnd) - x(cut.timelineStart)), + height: size.height + ) + context.fill(Path(rect), with: .color(NeomorphicTheme.accent.opacity(0.35))) + context.stroke(Path(rect), with: .color(NeomorphicTheme.accent), lineWidth: 1.5) + } + + // 盛り上がりの曲線。 + if analysis.energy.count > 1 { + var line = Path() + for (index, value) in analysis.energy.enumerated() { + let point = CGPoint( + x: x(Double(index) * hop), + y: size.height - 8 - CGFloat(value) * (size.height - 24) + ) + if index == 0 { line.move(to: point) } else { line.addLine(to: point) } + } + context.stroke(line, with: .color(NeomorphicTheme.ink.opacity(0.75)), lineWidth: 1.5) + } + + // 拍(下端の短い目盛り)。間隔が詰まりすぎるときは間引く。 + var lastBeatX: CGFloat = -10 + for beat in analysis.beats { + let position = x(beat) + guard position - lastBeatX >= 3 else { continue } + lastBeatX = position + var tick = Path() + tick.move(to: CGPoint(x: position, y: size.height)) + tick.addLine(to: CGPoint(x: position, y: size.height - 6)) + context.stroke(tick, with: .color(NeomorphicTheme.muted.opacity(0.7)), lineWidth: 1) + } + + // カットの切り替え位置(上端の目盛り)。 + if let plan { + var lastCutX: CGFloat = -10 + for cut in plan.cuts.dropFirst() { + let position = x(cut.timelineStart) + guard position - lastCutX >= 2 else { continue } + lastCutX = position + var mark = Path() + mark.move(to: CGPoint(x: position, y: 0)) + mark.addLine(to: CGPoint(x: position, y: 10)) + context.stroke(mark, with: .color(NeomorphicTheme.accent), lineWidth: 1) + } + } + + // 再生位置。 + if plan != nil { + let position = x(min(max(0, playbackTime), duration)) + var head = Path() + head.move(to: CGPoint(x: position, y: 0)) + head.addLine(to: CGPoint(x: position, y: size.height)) + context.stroke(head, with: .color(NeomorphicTheme.ink), lineWidth: 2) + } + } + + private func bandOpacity(_ level: MusicIntensity) -> Double { + switch level { + case .calm: return 0.06 + case .medium: return 0.14 + case .intense: return 0.26 + } + } +} diff --git a/ArkServer/Features/MusicVideo/Views/MusicVideoCutEditorView.swift b/ArkServer/Features/MusicVideo/Views/MusicVideoCutEditorView.swift new file mode 100644 index 0000000..3a4827c --- /dev/null +++ b/ArkServer/Features/MusicVideo/Views/MusicVideoCutEditorView.swift @@ -0,0 +1,120 @@ +// ArkServer/Features/MusicVideo/Views/MusicVideoCutEditorView.swift + +import SwiftUI + +/// 選んだカットの内容と、そのカットだけを直す操作。設定画面と同じ「行をまとめた面」で並べる。 +struct MusicVideoCutEditorView: View { + @ObservedObject var viewModel: MusicVideoViewModel + @ObservedObject var dataManager: LibraryViewModel + + var body: some View { + MVSection(title: "カットの編集") { + MVRowGroup { + if let cut = viewModel.selectedCut, let plan = viewModel.plan, let index = viewModel.selectedCutIndex { + MVRow( + 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: "同じ長さのまま,別の映像に差し替えます.") { + HStack(spacing: 8) { + Button("差し替える") { viewModel.replaceSelectedCut() } + .buttonStyle(.mvSmall) + .accessibilityIdentifier("musicvideo.replaceCut") + moreMenu + } + .disabled(!viewModel.canEdit) + } + } else { + MVRow( + title: "カットを選んでください", + detail: "上のタイムラインをクリックすると,その位置のカットを選べます.選んだカットだけを差し替えられます." + ) { + EmptyView() + } + } + MVRow(title: "移動と履歴") { + HStack(spacing: 8) { + Button { + viewModel.selectAdjacentCut(by: -1) + } label: { + Image(systemName: "chevron.left") + } + .buttonStyle(.mvSmall) + .help("前のカット") + .accessibilityLabel("前のカット") + Button { + viewModel.selectAdjacentCut(by: 1) + } label: { + Image(systemName: "chevron.right") + } + .buttonStyle(.mvSmall) + .help("次のカット") + .accessibilityLabel("次のカット") + + if viewModel.isApplyingEdit { + ProgressView().controlSize(.small) + } + + Button("元に戻す") { viewModel.undo() } + .buttonStyle(.mvSmall) + .disabled(!viewModel.canUndo) + .accessibilityIdentifier("musicvideo.undo") + Button("やり直す") { viewModel.redo() } + .buttonStyle(.mvSmall) + .disabled(!viewModel.canRedo) + } + .disabled(viewModel.plan == nil) + } + if !viewModel.excludedVideoIDs.isEmpty { + MVRow( + title: "除外した動画 \(viewModel.excludedVideoIDs.count)本", + detail: "次に映像を作るときも使いません." + ) { + Button("除外を解除") { viewModel.clearExclusions() } + .buttonStyle(.mvSmall) + } + } + } + } + } + + private var moreMenu: some View { + Menu { + Button("この動画を使っているカットをすべて差し替え") { viewModel.replaceAllUsesOfSelectedVideo() } + Button("この動画を外す(以後も使わない)") { viewModel.excludeSelectedVideo() } + Divider() + Menu("指定の動画に差し替え") { + ForEach(viewModel.poolVideos) { video in + Button(video.name) { viewModel.replaceSelectedCut(withVideo: video.id) } + } + } + } label: { + Text("その他") + } + .menuStyle(.button) + .buttonStyle(.mvSmall) + .menuIndicator(.visible) + .fixedSize() + } + + @ViewBuilder + private func thumbnail(for cut: PlannedCut) -> some View { + Group { + if let item = viewModel.sourceItem(for: cut.videoID) { + MacVideoThumbnailView(videoItem: item, dataManager: dataManager, showsPlayGlyph: false) + } else { + Rectangle().fill(NeomorphicTheme.control) + } + } + .frame(width: 96, height: 54) + .clipShape(RoundedRectangle(cornerRadius: 6, style: .continuous)) + } + + private func fineTime(_ seconds: Double) -> String { + let minutes = Int(seconds) / 60 + let rest = seconds - Double(minutes * 60) + return String(format: "%d:%04.1f", minutes, rest) + } +} diff --git a/ArkServer/Features/MusicVideo/Views/MusicVideoMusicPickerSheet.swift b/ArkServer/Features/MusicVideo/Views/MusicVideoMusicPickerSheet.swift new file mode 100644 index 0000000..452545c --- /dev/null +++ b/ArkServer/Features/MusicVideo/Views/MusicVideoMusicPickerSheet.swift @@ -0,0 +1,194 @@ +// ArkServer/Features/MusicVideo/Views/MusicVideoMusicPickerSheet.swift + +import AppKit +import SwiftUI +import UniformTypeIdentifiers + +/// 曲を置いてあるフォルダから、曲を探して選ぶシート。フォルダは一度選べば覚える。 +struct MusicVideoMusicPickerSheet: View { + @ObservedObject var viewModel: MusicVideoViewModel + @Environment(\.dismiss) private var dismiss + + struct MusicFile: Identifiable, Hashable, Sendable { + let url: URL + let size: Int64 + let modified: Date + var id: URL { url } + var title: String { url.deletingPathExtension().lastPathComponent } + } + + enum Order: String, CaseIterable, Identifiable { + case name = "名前" + case recent = "新しい順" + var id: String { rawValue } + } + + @State private var files: [MusicFile] = [] + @State private var isLoading = false + @State private var didHitLimit = false + @State private var searchText = "" + @AppStorage("musicVideo.musicPicker.order") private var order: Order = .name + + private static let fileLimit = 2000 + + private var visibleFiles: [MusicFile] { + let query = searchText.trimmingCharacters(in: .whitespacesAndNewlines) + var result = query.isEmpty ? files : files.filter { $0.title.localizedCaseInsensitiveContains(query) } + switch order { + case .name: result.sort { $0.title.localizedStandardCompare($1.title) == .orderedAscending } + case .recent: result.sort { $0.modified > $1.modified } + } + return result + } + + var body: some View { + VStack(spacing: 0) { + SheetHeader( + icon: "music.note.list", + title: "曲を選ぶ", + subtitle: viewModel.musicFolderURL?.path ?? "曲を置いてあるフォルダを選んでください" + ) + .padding(20) + + HStack(spacing: 12) { + TextField("曲名で検索", text: $searchText) + .textFieldStyle(.roundedBorder) + Picker("並べ替え", selection: $order) { + ForEach(Order.allCases) { Text($0.rawValue).tag($0) } + } + .frame(width: 180) + Button("フォルダを選ぶ…", action: chooseFolder) + } + .padding(.horizontal, 20) + .padding(.bottom, 12) + + Divider() + + content + + Divider() + HStack { + Text(footerText) + .font(.appCaption) + .foregroundStyle(NeomorphicTheme.muted) + Spacer() + Button("閉じる") { dismiss() } + .keyboardShortcut(.cancelAction) + } + .padding(16) + } + .frame(minWidth: 640, idealWidth: 700, minHeight: 520, idealHeight: 620) + .appSheet() + .task(id: viewModel.musicFolderURL) { await load() } + } + + @ViewBuilder + private var content: some View { + if viewModel.musicFolderURL == nil { + placeholder(icon: "folder.badge.plus", message: "「フォルダを選ぶ…」で,曲を置いてあるフォルダを選んでください") + } else if isLoading { + VStack(spacing: 10) { + ProgressView() + Text("曲を探しています…").font(.appBody).foregroundStyle(NeomorphicTheme.muted) + } + .frame(maxWidth: .infinity, maxHeight: .infinity) + } else if visibleFiles.isEmpty { + 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) + } + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + .accessibilityLabel(file.title) + } + .listStyle(.plain) + } + } + + private func placeholder(icon: String, message: String) -> some View { + VStack(spacing: 8) { + Image(systemName: icon).font(.system(size: 28, weight: .light)) + Text(message).font(.appBody).multilineTextAlignment(.center) + } + .foregroundStyle(NeomorphicTheme.muted) + .padding(24) + .frame(maxWidth: .infinity, maxHeight: .infinity) + } + + private var footerText: String { + guard viewModel.musicFolderURL != nil, !isLoading else { return "" } + let shown = visibleFiles.count + let base = shown == files.count ? "\(files.count)曲" : "\(shown) / \(files.count)曲" + return didHitLimit ? "\(base)(多いため先頭\(Self.fileLimit)曲まで)" : base + } + + private func chooseFolder() { + let panel = NSOpenPanel() + panel.canChooseFiles = false + panel.canChooseDirectories = true + panel.allowsMultipleSelection = false + panel.prompt = "選択" + panel.message = "曲を置いてあるフォルダを選んでください(中のフォルダも探します)" + if let current = viewModel.musicFolderURL { panel.directoryURL = current } + if panel.runModal() == .OK, let url = panel.url { + viewModel.setMusicFolder(url) + } + } + + private func load() async { + guard let folder = viewModel.musicFolderURL else { + files = [] + return + } + isLoading = true + let limit = Self.fileLimit + let result = await Task.detached(priority: .userInitiated) { + Self.scan(folder: folder, limit: limit) + }.value + guard !Task.isCancelled else { return } + files = result.files + didHitLimit = result.hitLimit + isLoading = false + } + + /// フォルダの中(サブフォルダも含む)の音声ファイルを集める。 + nonisolated private static func scan(folder: URL, limit: Int) -> (files: [MusicFile], hitLimit: Bool) { + let keys: [URLResourceKey] = [.isRegularFileKey, .fileSizeKey, .contentModificationDateKey] + guard let enumerator = FileManager.default.enumerator( + at: folder, + includingPropertiesForKeys: keys, + options: [.skipsHiddenFiles, .skipsPackageDescendants] + ) else { return ([], false) } + + var found: [MusicFile] = [] + for case let url as URL in enumerator { + guard let type = UTType(filenameExtension: url.pathExtension), type.conforms(to: .audio) else { continue } + let values = try? url.resourceValues(forKeys: Set(keys)) + guard values?.isRegularFile == true else { continue } + found.append(MusicFile( + url: url, + size: Int64(values?.fileSize ?? 0), + modified: values?.contentModificationDate ?? .distantPast + )) + if found.count >= limit { return (found, true) } + } + return (found, false) + } +} diff --git a/ArkServer/Features/MusicVideo/Views/MusicVideoSettingsComponents.swift b/ArkServer/Features/MusicVideo/Views/MusicVideoSettingsComponents.swift new file mode 100644 index 0000000..d866e42 --- /dev/null +++ b/ArkServer/Features/MusicVideo/Views/MusicVideoSettingsComponents.swift @@ -0,0 +1,139 @@ +// ArkServer/Features/MusicVideo/Views/MusicVideoSettingsComponents.swift + +import SwiftUI + +// 設定画面のような「見出し + 行をまとめた面」で画面を組むための部品。 +// +// セクション名(控えめな小さい文字) +// ┌──────────────────────────────────────────┐ +// │ 項目名 [ 操作 ] │ ← 行:左に項目名と薄い説明、右に操作 +// │ 薄い説明 │ +// ├──────────────────────────────────────────┤ ← 行どうしは細い線で区切る +// │ 項目名 ( スイッチ ) │ +// └──────────────────────────────────────────┘ +// +// アイコン付きの見出しや色付きの面は使わない。色は、スイッチ・決定ボタン・選択中の印だけにする。 + +/// 画面を中央の1列に収める幅。 +let musicVideoColumnWidth: CGFloat = 760 + +/// セクション名と、その下の内容。 +struct MVSection: View { + let title: String + var footer: String? = nil + @ViewBuilder var content: Content + + var body: some View { + VStack(alignment: .leading, spacing: 10) { + Text(title) + .font(.appBody.weight(.medium)) + .foregroundStyle(NeomorphicTheme.muted) + .padding(.horizontal, 2) + .accessibilityAddTraits(.isHeader) + content + if let footer { + Text(footer) + .font(.appCaption) + .foregroundStyle(NeomorphicTheme.muted) + .padding(.horizontal, 2) + .fixedSize(horizontal: false, vertical: true) + } + } + } +} + +/// 行をまとめる角丸の面。行の間に細い区切り線を入れる。 +struct MVRowGroup: View { + @ViewBuilder var content: Content + + var body: some View { + VStack(spacing: 0) { + Group(subviews: content) { subviews in + ForEach(subviews.indices, id: \.self) { index in + subviews[index] + if index < subviews.count - 1 { + Divider().overlay(NeomorphicTheme.separator) + } + } + } + } + .frame(maxWidth: .infinity, alignment: .leading) + .background(GlassCardSurface()) + .clipShape(RoundedRectangle(cornerRadius: DS.cardCornerRadius, style: .continuous)) + } +} + +/// 1行。左に項目名と薄い説明、右に操作。 +struct MVRow: View { + let title: String + var detail: String? = nil + @ViewBuilder var leading: Leading + @ViewBuilder var control: Control + + var body: some View { + HStack(alignment: .center, spacing: 14) { + leading + VStack(alignment: .leading, spacing: 3) { + Text(title) + .font(.appBody.weight(.medium)) + .foregroundStyle(NeomorphicTheme.ink) + .lineLimit(2) + if let detail { + Text(detail) + .font(.appCaption) + .foregroundStyle(NeomorphicTheme.muted) + .fixedSize(horizontal: false, vertical: true) + } + } + Spacer(minLength: 12) + control + } + .padding(.horizontal, 16) + .padding(.vertical, 12) + .frame(minHeight: 52) + } +} + +extension MVRow where Leading == EmptyView { + init(title: String, detail: String? = nil, @ViewBuilder control: () -> Control) { + self.title = title + self.detail = detail + self.leading = EmptyView() + self.control = control() + } +} + +/// 行の右に置く、小さな操作ボタン(「変更」のような見た目)。 +struct MVSmallButtonStyle: ButtonStyle { + @Environment(\.isEnabled) private var isEnabled + + func makeBody(configuration: Configuration) -> some View { + configuration.label + .font(.appCaption.weight(.medium)) + .foregroundStyle(NeomorphicTheme.ink.opacity(isEnabled ? 1 : 0.4)) + .padding(.horizontal, 11) + .padding(.vertical, 5) + .background( + RoundedRectangle(cornerRadius: 8, style: .continuous) + .fill(configuration.isPressed ? NeomorphicTheme.controlSelected : NeomorphicTheme.control) + ) + .contentShape(RoundedRectangle(cornerRadius: 8, style: .continuous)) + } +} + +extension ButtonStyle where Self == MVSmallButtonStyle { + static var mvSmall: MVSmallButtonStyle { MVSmallButtonStyle() } +} + +/// 行の右に置く、スイッチ。 +struct MVSwitch: View { + let title: String + @Binding var isOn: Bool + + var body: some View { + Toggle(title, isOn: $isOn) + .labelsHidden() + .toggleStyle(.switch) + .controlSize(.small) + } +} diff --git a/ArkServer/Features/MusicVideo/Views/MusicVideoSourcePickerSheet.swift b/ArkServer/Features/MusicVideo/Views/MusicVideoSourcePickerSheet.swift new file mode 100644 index 0000000..5a612cb --- /dev/null +++ b/ArkServer/Features/MusicVideo/Views/MusicVideoSourcePickerSheet.swift @@ -0,0 +1,373 @@ +// ArkServer/Features/MusicVideo/Views/MusicVideoSourcePickerSheet.swift + +import SwiftUI + +/// 素材にする動画を選ぶシート。アルバム単位と動画単位のどちらでも、まとめて選べる。 +/// 数百のアルバムや千本以上の動画から探せるよう、検索・並べ替え・絞り込みを備える。 +struct MusicVideoSourcePickerSheet: View { + @ObservedObject var viewModel: MusicVideoViewModel + @ObservedObject var dataManager: LibraryViewModel + @Environment(\.dismiss) private var dismiss + + private enum Tab: String, CaseIterable, Hashable { + case albums = "アルバム" + case videos = "動画" + } + + enum AlbumOrder: String, CaseIterable, Identifiable { + case name = "名前" + case count = "件数の多い順" + case recent = "最近追加した順" + var id: String { rawValue } + } + + enum VideoOrder: String, CaseIterable, Identifiable { + case recent = "追加が新しい順" + case longest = "長い順" + case name = "名前" + 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 + @AppStorage("musicVideo.picker.videoOrder") private var videoOrder: VideoOrder = .recent + @AppStorage("musicVideo.picker.hideEmpty") private var hidesEmptyAlbums = true + @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 allVideos: [VideoItem] = [] + + private var query: String { searchText.trimmingCharacters(in: .whitespacesAndNewlines) } + + var body: some View { + VStack(spacing: 0) { + SheetHeader( + icon: "film.stack", + title: "素材を選ぶ", + subtitle: "アルバムと動画は,どちらも組み合わせて選べます" + ) + .padding(20) + + controls + .padding(.horizontal, 20) + .padding(.bottom, 12) + + Divider() + + Group { + switch tab { + case .albums: albumList + case .videos: videoList + } + } + + Divider() + footer + .padding(16) + } + .frame(minWidth: 760, idealWidth: 800, minHeight: 620, idealHeight: 700) + .appSheet() + .onAppear(perform: rebuild) + .onChange(of: dataManager.albums) { rebuild() } + .onChange(of: dataManager.videos) { rebuild() } + } + + // MARK: - 操作部 + + private var controls: some View { + VStack(spacing: 10) { + HStack(spacing: 12) { + FlatSegmentedControl( + options: Tab.allCases, + title: { tab in + switch tab { + case .albums: return "アルバム(\(viewModel.selectedAlbumIDs.count))" + case .videos: return "動画(\(viewModel.selectedVideoIDs.count))" + } + }, + selection: $tab, + width: 280 + ) + TextField(tab == .albums ? "アルバム名で検索" : "動画名で検索", text: $searchText) + .textFieldStyle(.roundedBorder) + } + HStack(spacing: 14) { + switch tab { + case .albums: + Picker("並べ替え", selection: $albumOrder) { + ForEach(AlbumOrder.allCases) { Text($0.rawValue).tag($0) } + } + .frame(width: 210) + Toggle("空を隠す", isOn: $hidesEmptyAlbums) + .fixedSize() + .help("動画が1本もないアルバムを一覧から隠します") + case .videos: + Picker("並べ替え", selection: $videoOrder) { + ForEach(VideoOrder.allCases) { Text($0.rawValue).tag($0) } + } + .frame(width: 210) + Picker("長さ", selection: $minimumLength) { + Text("すべて").tag(1.0) + Text("5秒以上").tag(5.0) + Text("10秒以上").tag(10.0) + Text("30秒以上").tag(30.0) + } + .frame(width: 150) + Toggle("お気に入りのみ", isOn: $favoritesOnly) + .fixedSize() + } + Toggle("選択中のみ", isOn: $onlySelected) + .fixedSize() + Spacer(minLength: 0) + Button("表示中を選択") { selectAllVisible() } + .help("いま一覧に出ているものをすべて選びます") + Button("表示中を解除") { deselectAllVisible() } + .help("いま一覧に出ているものの選択をすべて外します") + } + .font(.appCaption) + } + } + + // MARK: - アルバム + + private var visibleAlbums: [AlbumRow] { + 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) + } + } + switch albumOrder { + case .name: + rows.sort { ($0.parent + "/" + $0.title).localizedStandardCompare($1.parent + "/" + $1.title) == .orderedAscending } + case .count: + rows.sort { $0.count > $1.count } + case .recent: + rows.sort { $0.latestImport > $1.latestImport } + } + return rows + } + + private var albumList: some View { + let rows = visibleAlbums + return Group { + if rows.isEmpty { + emptyState("条件に合うアルバムがありません") + } else { + List(rows) { row in + let isSelected = viewModel.selectedAlbumIDs.contains(row.id) + Button { + if isSelected { viewModel.selectedAlbumIDs.remove(row.id) } else { viewModel.selectedAlbumIDs.insert(row.id) } + } label: { + HStack(spacing: 10) { + checkmark(isSelected) + VStack(alignment: .leading, spacing: 2) { + Text(row.title) + .font(.appBody) + .lineLimit(1) + .truncationMode(.middle) + if !row.parent.isEmpty { + Text(row.parent) + .font(.appMicro) + .foregroundStyle(NeomorphicTheme.muted) + .lineLimit(1) + .truncationMode(.head) + } + } + Spacer(minLength: 8) + VStack(alignment: .trailing, spacing: 2) { + Text("\(row.count)本") + .font(.appCaption.monospacedDigit()) + Text(durationText(row.totalDuration)) + .font(.appMicro.monospacedDigit()) + .foregroundStyle(NeomorphicTheme.muted) + } + } + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + .accessibilityLabel("\(row.title) \(row.count)本") + .accessibilityAddTraits(isSelected ? .isSelected : []) + } + .listStyle(.plain) + } + } + } + + // MARK: - 動画 + + private var visibleVideos: [VideoItem] { + var items = allVideos.filter { $0.duration >= minimumLength } + if favoritesOnly { items = items.filter(\.isFavorite) } + if onlySelected { items = items.filter { viewModel.selectedVideoIDs.contains($0.id) } } + if !query.isEmpty { items = items.filter { $0.originalFilename.localizedCaseInsensitiveContains(query) } } + switch videoOrder { + case .recent: + items.sort { $0.importDate > $1.importDate } + case .longest: + items.sort { $0.duration > $1.duration } + case .name: + items.sort { $0.originalFilename.localizedStandardCompare($1.originalFilename) == .orderedAscending } + } + return items + } + + private var videoList: some View { + let items = visibleVideos + return Group { + if items.isEmpty { + emptyState("条件に合う動画がありません") + } else { + List(items) { video in + let isSelected = viewModel.selectedVideoIDs.contains(video.id) + Button { + if isSelected { viewModel.selectedVideoIDs.remove(video.id) } else { viewModel.selectedVideoIDs.insert(video.id) } + } label: { + HStack(spacing: 10) { + checkmark(isSelected) + MacVideoThumbnailView(videoItem: video, dataManager: dataManager, showsPlayGlyph: false) + .frame(width: 80, height: 45) + .clipShape(RoundedRectangle(cornerRadius: 4, style: .continuous)) + Text(video.originalFilename) + .font(.appBody) + .lineLimit(2) + .truncationMode(.middle) + Spacer(minLength: 8) + if video.isFavorite { + Image(systemName: "heart.fill") + .font(.appMicro) + .foregroundStyle(NeomorphicTheme.muted) + } + Text(durationText(video.duration)) + .font(.appMicro.monospacedDigit()) + .foregroundStyle(NeomorphicTheme.muted) + } + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + .accessibilityLabel(video.originalFilename) + .accessibilityAddTraits(isSelected ? .isSelected : []) + } + .listStyle(.plain) + } + } + } + + // MARK: - 共通部品 + + /// 選択の印。サイドバーの複数選択と同じく、色を付けず、選択中は文字色・未選択は控えめな色にする。 + private func checkmark(_ isSelected: Bool) -> some View { + Image(systemName: isSelected ? "checkmark.circle.fill" : "circle") + .font(.system(size: 15)) + .foregroundStyle(isSelected ? NeomorphicTheme.ink : NeomorphicTheme.muted) + .frame(width: 18) + } + + private func emptyState(_ message: String) -> some View { + VStack(spacing: 8) { + Image(systemName: "magnifyingglass") + .font(.system(size: 28, weight: .light)) + Text(message) + .font(.appBody) + } + .foregroundStyle(NeomorphicTheme.muted) + .frame(maxWidth: .infinity, maxHeight: .infinity) + } + + private var footer: some View { + HStack(spacing: 12) { + VStack(alignment: .leading, spacing: 2) { + Text("使える動画 \(viewModel.candidateCount.formatted())本") + .font(.appBody.weight(.semibold)) + Text(summaryDetail) + .font(.appCaption) + .foregroundStyle(NeomorphicTheme.muted) + } + Spacer() + Button("すべて解除") { viewModel.clearSourceSelection() } + .disabled(viewModel.selectedAlbumIDs.isEmpty && viewModel.selectedVideoIDs.isEmpty && !viewModel.includeFavorites) + Button("完了") { dismiss() } + .keyboardShortcut(.defaultAction) + .accessibilityIdentifier("musicvideo.sourceDone") + } + } + + private var summaryDetail: String { + var parts: [String] = [] + if !viewModel.selectedAlbumIDs.isEmpty { parts.append("アルバム \(viewModel.selectedAlbumIDs.count)個") } + 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 + return viewModel.candidateCount > limit + ? "\(selection)(解析は無作為に選ぶ\(limit)本まで)" + : selection + } + + private func durationText(_ seconds: Double) -> String { + let total = Int(seconds.rounded()) + if total >= 3600 { return String(format: "%d時間%02d分", total / 3600, (total % 3600) / 60) } + return String(format: "%d:%02d", total / 60, total % 60) + } + + // MARK: - 選択の一括操作 + + private func selectAllVisible() { + switch tab { + case .albums: viewModel.selectedAlbumIDs.formUnion(visibleAlbums.map(\.id)) + case .videos: viewModel.selectedVideoIDs.formUnion(visibleVideos.map(\.id)) + } + } + + private func deselectAllVisible() { + switch tab { + case .albums: viewModel.selectedAlbumIDs.subtract(visibleAlbums.map(\.id)) + case .videos: viewModel.selectedVideoIDs.subtract(visibleVideos.map(\.id)) + } + } + + // MARK: - 一覧の作成 + + private func rebuild() { + 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 + ) + } + } +} diff --git a/ArkServer/Features/MusicVideo/Views/MusicVideoView.swift b/ArkServer/Features/MusicVideo/Views/MusicVideoView.swift new file mode 100644 index 0000000..1d99796 --- /dev/null +++ b/ArkServer/Features/MusicVideo/Views/MusicVideoView.swift @@ -0,0 +1,453 @@ +// ArkServer/Features/MusicVideo/Views/MusicVideoView.swift + +import AppKit +import AVKit +import SwiftUI +import UniformTypeIdentifiers + +/// 曲を選ぶと、ライブラリの動画から曲に合わせた映像を自動で作る画面。 +/// +/// 設定画面のように、中央の1列に「セクション名 + 行をまとめた面」を縦に並べる。 +/// 結果ができたら、プレビューとカットの編集を一番上に出す。実行ボタンは下に固定して常に見せる。 +struct MusicVideoView: View { + @ObservedObject var viewModel: MusicVideoViewModel + @ObservedObject var dataManager: LibraryViewModel + + @State private var isDropTargeted = false + @State private var isShowingSourcePicker = false + @State private var isShowingMusicPicker = false + + private static let topAnchor = "musicvideo.top" + + 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 + } + .frame(maxWidth: musicVideoColumnWidth) + .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 + } + .background(CommandDeckBackground()) + .navigationTitle("ミュージックビデオ") + // 設定画面と同じく、スイッチなどの「入」の色は青にする(内容側の既定は文字色の中立色)。 + .tint(NeomorphicTheme.accent) + .overlay { + if isDropTargeted { + RoundedRectangle(cornerRadius: DS.cardCornerRadius, style: .continuous) + .strokeBorder(NeomorphicTheme.accent, style: StrokeStyle(lineWidth: 2, dash: [8, 6])) + .padding(8) + .allowsHitTesting(false) + } + } + .onDrop(of: [.fileURL], isTargeted: $isDropTargeted, perform: handleMusicDrop) + .onAppear { viewModel.attach(dataManager: dataManager) } + .onDisappear { viewModel.pausePlayback() } + .sheet(isPresented: $isShowingSourcePicker) { + MusicVideoSourcePickerSheet(viewModel: viewModel, dataManager: dataManager) + } + .sheet(isPresented: $isShowingMusicPicker) { + MusicVideoMusicPickerSheet(viewModel: viewModel) + } + .alert( + "処理に失敗しました", + isPresented: Binding( + get: { viewModel.errorMessage != nil }, + set: { if !$0 { viewModel.clearError() } } + ) + ) { + Button("OK", role: .cancel) { viewModel.clearError() } + } message: { + Text(viewModel.errorMessage ?? "不明なエラーです.") + } + .alert( + "書き出しが完了しました", + isPresented: Binding( + get: { viewModel.resultMessage != nil }, + set: { if !$0 { viewModel.clearResultMessage() } } + ) + ) { + Button("OK", role: .cancel) { viewModel.clearResultMessage() } + } message: { + Text(viewModel.resultMessage ?? "") + } + } + + // 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) + } + } + } + } + } + + private var previewAspectRatio: CGFloat { + let size = viewModel.renderPreset.settings.size + return size.width / size.height + } + + // MARK: - 曲 + + private var musicSection: some View { + MVSection(title: "曲") { + MVRowGroup { + MVRow(title: viewModel.musicTitle ?? "曲を選んでください", detail: musicDetail) { + HStack(spacing: 8) { + if viewModel.phase == .analyzingMusic { ProgressView().controlSize(.small) } + Button("フォルダから…") { isShowingMusicPicker = true } + .buttonStyle(.mvSmall) + .help("曲を置いてあるフォルダから探して選びます") + .accessibilityIdentifier("musicvideo.musicFolder") + Button("ファイル…") { chooseMusicFile() } + .buttonStyle(.mvSmall) + .help("曲のファイルを1つ選びます") + .accessibilityIdentifier("musicvideo.musicFile") + if !viewModel.recentMusicURLs.isEmpty { recentMenu } + } + .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") + } + } + if let analysis = viewModel.analysis { + MVRow(title: "テンポと拍") { + Text("\(formatTime(analysis.duration))・\(Int(analysis.tempo.rounded())) BPM・拍 \(analysis.beats.count)個") + .font(.appBody.monospacedDigit()) + .foregroundStyle(NeomorphicTheme.muted) + } + } + } + } + } + + private var musicDetail: String { + if viewModel.musicURL == nil { return "mp3 などの曲を選ぶか,この画面へドロップしてください." } + return viewModel.phase == .analyzingMusic ? "拍と盛り上がりを解析しています…" : "この曲に合わせて映像を作ります." + } + + private var recentMenu: some View { + Menu { + ForEach(viewModel.recentMusicURLs, id: \.self) { url in + Button(url.deletingPathExtension().lastPathComponent) { viewModel.chooseMusic(url) } + } + } label: { + Text("最近") + } + .menuStyle(.button) + .buttonStyle(.mvSmall) + .menuIndicator(.visible) + .fixedSize() + } + + private func chooseMusicFile() { + let panel = NSOpenPanel() + panel.canChooseFiles = true + panel.canChooseDirectories = false + panel.allowsMultipleSelection = false + panel.allowedContentTypes = [.audio] + panel.prompt = "選択" + if let folder = viewModel.musicFolderURL { panel.directoryURL = folder } + if panel.runModal() == .OK, let url = panel.url { + viewModel.chooseMusic(url) + } + } + + private func handleMusicDrop(_ providers: [NSItemProvider]) -> Bool { + guard !viewModel.isWorking, + let provider = providers.first(where: { $0.hasItemConformingToTypeIdentifier(UTType.fileURL.identifier) }) else { + return false + } + _ = provider.loadObject(ofClass: URL.self) { url, _ in + guard let url, UTType(filenameExtension: url.pathExtension)?.conforms(to: .audio) == true else { return } + Task { @MainActor in viewModel.chooseMusic(url) } + } + return true + } + + // MARK: - 素材 + + private var selectedAlbums: [Album] { + dataManager.albums + .filter { viewModel.selectedAlbumIDs.contains($0.id) } + .sorted { $0.displayTitle.localizedStandardCompare($1.displayTitle) == .orderedAscending } + } + + private var sourceSection: some View { + MVSection(title: "素材") { + MVRowGroup { + MVRow( + title: viewModel.candidateCount == 0 ? "素材がまだ選ばれていません" : "使える動画 \(viewModel.candidateCount.formatted())本", + detail: sourceDetail + ) { + HStack(spacing: 8) { + if !(viewModel.selectedAlbumIDs.isEmpty && viewModel.selectedVideoIDs.isEmpty) { + Button("解除") { viewModel.clearSourceSelection() } + .buttonStyle(.mvSmall) + .help("アルバムと動画の選択をすべて外します") + } + Button("選ぶ…") { isShowingSourcePicker = true } + .buttonStyle(.mvSmall) + .accessibilityIdentifier("musicvideo.chooseSource") + } + .disabled(viewModel.isWorking) + } + MVRow(title: "お気に入りを含める", detail: "お気に入りにした動画も素材に加えます.") { + MVSwitch(title: "お気に入りを含める", isOn: $viewModel.includeFavorites) + .disabled(viewModel.isWorking) + } + } + } + } + + /// 選んだアルバム・動画の内訳(例: 「fontene・acid39 ほかアルバム2個・個別の動画 3本」)。 + private var sourceDetail: String? { + let albums = selectedAlbums + var parts: [String] = [] + if !albums.isEmpty { + let names = albums.prefix(3).map(\.displayTitle).joined(separator: "・") + 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)本までです." + } + 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 { + VStack(spacing: 0) { + Divider().overlay(NeomorphicTheme.separator) + HStack(spacing: 12) { + statusView + .frame(maxWidth: .infinity, alignment: .leading) + + if viewModel.isWorking { + Button("中止") { viewModel.cancelWork() } + .buttonStyle(.bordered) + .controlSize(.large) + .accessibilityIdentifier("musicvideo.cancel") + } else { + if viewModel.plan != nil { + Button("ファイルに保存…") { saveToFile() } + .buttonStyle(.bordered) + .controlSize(.large) + .disabled(!viewModel.canExport) + .accessibilityIdentifier("musicvideo.saveFile") + Button("「HMV」に追加") { viewModel.exportToLibrary(dataManager: dataManager) } + .buttonStyle(.bordered) + .controlSize(.large) + .disabled(!viewModel.canExport) + .help("書き出して「HMV」アルバムに追加します") + .accessibilityIdentifier("musicvideo.exportLibrary") + } + Button(viewModel.plan == nil ? "映像を作る" : "作り直す") { + viewModel.generate(dataManager: dataManager) + } + .buttonStyle(.borderedProminent) + .controlSize(.large) + .disabled(!viewModel.canGenerate) + .help(viewModel.plan == nil ? "曲に合わせて映像を作ります" : "別のカット割りで作り直します") + .accessibilityIdentifier("musicvideo.generate") + } + } + .frame(maxWidth: musicVideoColumnWidth) + .frame(maxWidth: .infinity) + .padding(.horizontal, 24) + .padding(.vertical, 14) + } + .background(NeomorphicTheme.canvas) + } + + @ViewBuilder + private var statusView: some View { + switch viewModel.phase { + case .idle: + if let blocker = viewModel.generateBlocker { + statusText(blocker) + } else if viewModel.plan == nil { + statusText("「映像を作る」を押すと始まります.") + } + case .analyzingMusic: + progressRow("曲を解析中…", value: nil) + case .analyzingSources(let completed, let total): + progressRow( + "素材の動きを解析中 \(completed)/\(total)" + (remainingText.map { "・\($0)" } ?? ""), + value: total > 0 ? Double(completed) / Double(total) : nil, + note: completed < total && completed < 3 ? "初回は時間がかかります.結果は保存され,次回から速くなります." : nil + ) + case .composing: + progressRow("カット割りを作って合成中…", value: nil) + case .ready: + if let plan = viewModel.plan { + VStack(alignment: .leading, spacing: 2) { + Text("\(plan.cuts.count)カット・使った動画 \(viewModel.usedVideoCount)本") + .font(.appCaption.weight(.medium)) + .foregroundStyle(NeomorphicTheme.ink) + if viewModel.missingFileCount > 0 { + Text("ファイルが見つからない動画 \(viewModel.missingFileCount)本は使っていません") + .font(.appMicro) + .foregroundStyle(NeomorphicTheme.muted) + } + } + } + case .exporting(let progress): + progressRow("書き出し中 \(Int(progress * 100))%", value: progress) + } + } + + private func statusText(_ text: String) -> some View { + Text(text) + .font(.appCaption) + .foregroundStyle(NeomorphicTheme.muted) + } + + private var remainingText: String? { + guard let remaining = viewModel.estimatedRemaining else { return nil } + return remaining >= 90 ? "残り約\(Int((remaining / 60).rounded(.up)))分" : "残り約\(Int(remaining.rounded()))秒" + } + + private func progressRow(_ text: String, value: Double?, note: String? = nil) -> some View { + VStack(alignment: .leading, spacing: 5) { + Text(text) + .font(.appCaption) + .foregroundStyle(NeomorphicTheme.muted) + .lineLimit(1) + if let value { + ProgressView(value: value) + } else { + ProgressView().controlSize(.small) + } + if let note { + Text(note) + .font(.appMicro) + .foregroundStyle(NeomorphicTheme.muted) + .lineLimit(2) + } + } + .frame(maxWidth: 320, alignment: .leading) + } + + private func saveToFile() { + let panel = NSSavePanel() + panel.allowedContentTypes = [.mpeg4Movie] + panel.nameFieldStringValue = viewModel.suggestedFileName + panel.canCreateDirectories = true + panel.prompt = "保存" + if panel.runModal() == .OK, let url = panel.url { + viewModel.exportToFile(at: url) + } + } + + private func formatTime(_ seconds: Double) -> String { + let total = Int(seconds.rounded()) + return String(format: "%d:%02d", total / 60, total % 60) + } +} diff --git a/ArkServer/Features/Navigation/Views/SidebarRailView.swift b/ArkServer/Features/Navigation/Views/SidebarRailView.swift index 1d0a105..f135953 100644 --- a/ArkServer/Features/Navigation/Views/SidebarRailView.swift +++ b/ArkServer/Features/Navigation/Views/SidebarRailView.swift @@ -122,7 +122,7 @@ struct SidebarRailView: View { var count: Int? = nil } - /// 区切り線で分ける3つのまとまり:ホーム/ライブラリ全体/自分用の入口。 + /// 区切り線で分ける4つのまとまり:ホーム/ライブラリ全体/自分用の入口/作成ツール。 private var groups: [[Destination]] { let c = countsModel.counts return [ @@ -140,6 +140,9 @@ struct SidebarRailView: View { Destination(id: "history", title: "再生履歴", symbol: "clock.arrow.circlepath", target: .history, count: c.history), Destination(id: "trash", title: "ゴミ箱", symbol: "trash", target: .trash, count: c.trash), ], + [ + Destination(id: "musicVideo", title: "ミュージックビデオ", symbol: "music.note.tv", target: .musicVideo), + ], ] } diff --git a/ArkServer/Features/SceneExtraction/Services/VisualAnalyzer.swift b/ArkServer/Features/SceneExtraction/Services/VisualAnalyzer.swift index 2aad3ca..1c139a7 100644 --- a/ArkServer/Features/SceneExtraction/Services/VisualAnalyzer.swift +++ b/ArkServer/Features/SceneExtraction/Services/VisualAnalyzer.swift @@ -35,7 +35,12 @@ nonisolated struct VisualAnalyzer: Sendable { private let luminanceWeight = 0.8 private let edgeWeight = 0.2 - func analyze(url: URL, settings: AnalysisSettings) async throws -> [VisualFeaturePoint] { + /// - Parameter timeRange: 解析する区間(秒)。nil なら動画全体。長い動画の一部だけを調べたいときに使う。 + func analyze( + url: URL, + settings: AnalysisSettings, + timeRange: ClosedRange? = nil + ) async throws -> [VisualFeaturePoint] { let asset = AVURLAsset(url: url) guard let videoTrack = try await asset.loadTracks(withMediaType: .video).first else { throw VisualAnalyzerError.missingVideoTrack @@ -57,6 +62,12 @@ nonisolated struct VisualAnalyzer: Sendable { throw VisualAnalyzerError.cannotAddOutput } reader.add(output) + if let timeRange { + reader.timeRange = CMTimeRange( + start: CMTime(seconds: timeRange.lowerBound, preferredTimescale: 600), + duration: CMTime(seconds: timeRange.upperBound - timeRange.lowerBound, preferredTimescale: 600) + ) + } guard reader.startReading() else { throw VisualAnalyzerError.readerFailed(reader.error?.localizedDescription ?? "開始できませんでした.") diff --git a/ArkServerTests/MusicVideoTests.swift b/ArkServerTests/MusicVideoTests.swift new file mode 100644 index 0000000..40e12d1 --- /dev/null +++ b/ArkServerTests/MusicVideoTests.swift @@ -0,0 +1,1271 @@ +// ArkServerTests/MusicVideoTests.swift + +import AVFoundation +import Foundation +import Testing +@testable import ArkServer + +// MARK: - 合成音声 + +private let testSampleRate = 22_050.0 + +/// 指定した時刻にクリック音(減衰する1.5kHzの短い音)を置いた音声を作る。 +private 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 { + let start = Int(click.time * testSampleRate) + for offset in 0.. [Double] { + Array(stride(from: first, to: end, by: interval)) +} + +private func nearestDistance(to time: Double, in times: [Double]) -> Double { + times.map { abs($0 - time) }.min() ?? .infinity +} + +// MARK: - 合成動画 + +/// 単色のフレームだけからなる小さな動画を書き出す。`brightness` でフレームごとの明るさを決める。 +private func makeTestVideo( + at url: URL, + duration: Double, + size: (width: Int, height: Int) = (160, 90), + framesPerSecond: Int32 = 30, + brightness: (Int) -> UInt8 +) async throws { + let writer = try AVAssetWriter(outputURL: url, fileType: .mp4) + let input = AVAssetWriterInput( + mediaType: .video, + outputSettings: [ + AVVideoCodecKey: AVVideoCodecType.h264, + AVVideoWidthKey: size.width, + AVVideoHeightKey: size.height + ] + ) + let adaptor = AVAssetWriterInputPixelBufferAdaptor( + assetWriterInput: input, + sourcePixelBufferAttributes: [ + kCVPixelBufferPixelFormatTypeKey as String: kCVPixelFormatType_32BGRA, + kCVPixelBufferWidthKey as String: size.width, + kCVPixelBufferHeightKey as String: size.height + ] + ) + writer.add(input) + #expect(writer.startWriting()) + writer.startSession(atSourceTime: .zero) + + for frameIndex in 0.. URL { + let url = FileManager.default.temporaryDirectory.appendingPathComponent("\(name)-\(UUID().uuidString)") + try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true) + return url +} + +// MARK: - ビート解析 + +@Suite(.serialized) +struct BeatAnalyzerTests { + @Test + func detectsTempoAndBeatPositionsOfClickTrack() { + let clicks = evenClicks(from: 0.25, interval: 0.5, until: 20) + let samples = clickTrack(duration: 20, clicks: clicks.map { ($0, 0.8) }) + + let analysis = BeatAnalyzer().analyze(samples: samples, sampleRate: testSampleRate) + + #expect(abs(analysis.tempo - 120) < 2) + #expect(abs(analysis.duration - 20) < 0.01) + #expect(analysis.beats.count >= 30) + let aligned = analysis.beats.filter { nearestDistance(to: $0, in: clicks) < 0.03 } + #expect(Double(aligned.count) / Double(analysis.beats.count) >= 0.9) + } + + @Test + func detectsDifferentTempo() { + let clicks = evenClicks(from: 0.2, interval: 60.0 / 90.0, until: 24) + let samples = clickTrack(duration: 24, clicks: clicks.map { ($0, 0.8) }) + + let analysis = BeatAnalyzer().analyze(samples: samples, sampleRate: testSampleRate) + + #expect(abs(analysis.tempo - 90) < 2) + } + + @Test + func separatesQuietAndLoudSections() { + // 前半は小さい音でまばら、後半は大きい音で密(ノイズの下地つき)。 + var clicks: [(time: Double, amplitude: Float)] = [] + clicks += evenClicks(from: 0.5, interval: 1.0, until: 10).map { ($0, 0.05) } + clicks += evenClicks(from: 10.25, interval: 0.5, until: 20).map { ($0, 0.8) } + var samples = clickTrack(duration: 20, clicks: clicks) + var generator = SeededGenerator(seed: 7) + for index in Int(10 * testSampleRate).. 0) + #expect(silent.intensity.count == silent.energy.count) + } + + @Test + func readsAudioFileAndConvertsSampleRate() async throws { + let clicks = evenClicks(from: 0.25, interval: 0.5, until: 14) + let samples = clickTrack(duration: 14, clicks: clicks.map { ($0, 0.8) }) + // 解析用とは別の標本化周波数・ステレオで書き出し、読み込み側の変換も確かめる。 + let url = FileManager.default.temporaryDirectory + .appendingPathComponent("beat-test-\(UUID().uuidString).wav") + defer { try? FileManager.default.removeItem(at: url) } + try writeStereoWAV(samples: samples, sampleRate: testSampleRate, to: url) + + let analysis = try await BeatAnalyzer().analyze(url: url) + + #expect(abs(analysis.tempo - 120) < 2) + #expect(abs(analysis.duration - 14) < 0.1) + } + + private func writeStereoWAV(samples: [Float], sampleRate: Double, to url: URL) throws { + let format = try #require(AVAudioFormat(commonFormat: .pcmFormatFloat32, sampleRate: 44_100, channels: 2, interleaved: false)) + let ratio = 44_100 / sampleRate + let frameCount = AVAudioFrameCount(Double(samples.count) * ratio) + let buffer = try #require(AVAudioPCMBuffer(pcmFormat: format, frameCapacity: frameCount)) + buffer.frameLength = frameCount + let left = try #require(buffer.floatChannelData?[0]) + let right = try #require(buffer.floatChannelData?[1]) + for frame in 0.. MusicAnalysis { + let beats = Array(stride(from: 0.5, 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)) + ) + } + + @Test + func cutLengthFollowsIntensityAndBoundariesStayOnBeats() throws { + let analysis = makeAnalysis() + let pool = [profile(motion: 0.5), profile(motion: 0.5), profile(motion: 0.5)] + + let plan = try CutPlanner().plan(analysis: analysis, pool: pool, seed: 1) + + // 標準: 静か=4拍(2秒)、中=2拍(1秒)、盛り上がり=1拍(0.5秒) + for cut in plan.cuts where cut.timelineStart >= 0.5 && cut.timelineStart < 19 { + #expect(abs(cut.duration - 2.0) < 1e-9) + } + for cut in plan.cuts where cut.timelineStart >= 21 && cut.timelineStart < 39 { + #expect(abs(cut.duration - 0.5) < 1e-9) + } + for cut in plan.cuts where cut.timelineStart >= 41 && cut.timelineStart < 58 { + #expect(abs(cut.duration - 1.0) < 1e-9) + } + // すべての境界は拍の上(または曲の終わり) + for cut in plan.cuts { + let end = cut.timelineEnd + let onBeat = analysis.beats.contains { abs($0 - end) < 1e-9 } || abs(end - duration) < 1e-9 + #expect(onBeat) + } + } + + @Test + func cutsAreContiguousAndCoverTheWholeTrack() throws { + let plan = try CutPlanner().plan( + analysis: makeAnalysis(), + pool: [profile(motion: 0.3), profile(motion: 0.6)], + seed: 5 + ) + + #expect(plan.cuts.first?.timelineStart == 0) + for (previous, next) in zip(plan.cuts, plan.cuts.dropFirst()) { + #expect(abs(previous.timelineEnd - next.timelineStart) < 1e-9) + } + #expect(abs((plan.cuts.last?.timelineEnd ?? 0) - duration) < 1e-9) + #expect(abs(plan.cuts.reduce(0) { $0 + $1.duration } - duration) < 1e-6) + } + + @Test + func neverUsesTheSameVideoTwiceInARow() throws { + let pool = (0..<4).map { _ in profile(motion: 0.5) } + let plan = try CutPlanner().plan(analysis: makeAnalysis(), pool: pool, seed: 3) + + for (previous, next) in zip(plan.cuts, plan.cuts.dropFirst()) { + #expect(previous.videoID != next.videoID) + } + } + + @Test + func prefersCalmVideosForQuietPartsAndActiveVideosForLoudParts() throws { + let calmVideos = [profile(motion: 0.1), profile(motion: 0.1)] + let activeVideos = [profile(motion: 0.9), profile(motion: 0.9)] + let calmIDs = Set(calmVideos.map(\.videoID)) + let activeIDs = Set(activeVideos.map(\.videoID)) + + let plan = try CutPlanner().plan( + analysis: makeAnalysis(), + pool: calmVideos + activeVideos, + seed: 11 + ) + + let quiet = plan.cuts.filter { $0.timelineStart >= 0.5 && $0.timelineStart < 19 } + let loud = plan.cuts.filter { $0.timelineStart >= 21 && $0.timelineStart < 39 } + let quietShare = Double(quiet.filter { calmIDs.contains($0.videoID) }.count) / Double(quiet.count) + let loudShare = Double(loud.filter { activeIDs.contains($0.videoID) }.count) / Double(loud.count) + #expect(quietShare >= 0.8) + #expect(loudShare >= 0.8) + } + + @Test + func sourceRangesStayInsideEachVideoAndSkipTooShortVideos() throws { + let tooShort = profile(duration: 0.3, motion: 0.5) + let pool = [tooShort, profile(duration: 30, motion: 0.4), profile(duration: 9, motion: 0.7)] + let durations = Dictionary(uniqueKeysWithValues: pool.map { ($0.videoID, $0.duration) }) + + let plan = try CutPlanner().plan(analysis: makeAnalysis(), pool: pool, seed: 2) + + for cut in plan.cuts { + #expect(cut.videoID != tooShort.videoID) + #expect(cut.sourceStart >= 0) + #expect(cut.sourceStart + cut.duration <= durations[cut.videoID]! + 1e-9) + } + } + + @Test + func cutsStayInsideTheAnalyzedWindowsOfALongVideo() throws { + // 長い動画は離れた複数の窓だけを解析する。カットはその窓の内側(動画全体での位置)から選ばれる。 + let longVideo = UUID() + let windows = [ + SourceMotionProfile(videoID: longVideo, offset: 10, duration: 15, hop: 0.5, values: [Double](repeating: 0.5, count: 30)), + SourceMotionProfile(videoID: longVideo, offset: 200, duration: 15, hop: 0.5, values: [Double](repeating: 0.5, count: 30)) + ] + let other = UUID() + let otherWindow = SourceMotionProfile(videoID: other, offset: 60, duration: 15, hop: 0.5, values: [Double](repeating: 0.5, count: 30)) + + let plan = try CutPlanner().plan(analysis: makeAnalysis(), pool: windows + [otherWindow], seed: 8) + + #expect(!plan.cuts.isEmpty) + for cut in plan.cuts { + let inside = (windows + [otherWindow]).contains { window in + window.videoID == cut.videoID + && cut.sourceStart >= window.offset - 1e-9 + && cut.sourceStart + cut.duration <= window.offset + window.duration + 1e-9 + } + #expect(inside, "カット \(cut.timelineStart)s は解析した窓の外(元動画の \(cut.sourceStart)s)を指している") + } + } + + @Test + func isDeterministicForTheSameSeed() throws { + let pool = (0..<5).map { index in profile(motion: Double(index) / 4) } + let planner = CutPlanner() + let first = try planner.plan(analysis: makeAnalysis(), pool: pool, seed: 99) + let second = try planner.plan(analysis: makeAnalysis(), pool: pool, seed: 99) + let other = try planner.plan(analysis: makeAnalysis(), pool: pool, seed: 100) + + #expect(first == second) + #expect(first != other) + } + + @Test + func doublesCutLengthWhenBeatsAreTooFast() throws { + // 0.25秒間隔の拍。最短カットは0.3秒なので、1拍ごとの切り替えは2拍(0.5秒)になる。 + let analysis = makeAnalysis(beatInterval: 0.25) + let plan = try CutPlanner().plan(analysis: analysis, pool: [profile(motion: 0.5), profile(motion: 0.5)], seed: 4) + + for cut in plan.cuts { + #expect(cut.duration >= 0.3 - 1e-9) + } + } + + @Test + func cutStyleChangesHowOftenTheVideoSwitches() throws { + let pool = [profile(motion: 0.5), profile(motion: 0.5), profile(motion: 0.5)] + var relaxed = CutPlanner() + relaxed.style = .relaxed + var energetic = CutPlanner() + energetic.style = .energetic + + let relaxedPlan = try relaxed.plan(analysis: makeAnalysis(), pool: pool, seed: 1) + let energeticPlan = try energetic.plan(analysis: makeAnalysis(), pool: pool, seed: 1) + + #expect(relaxedPlan.cuts.count < energeticPlan.cuts.count) + } + + @Test + func reportsClearErrors() { + let planner = CutPlanner() + let analysis = makeAnalysis() + #expect(throws: CutPlannerError.emptyPool) { + try planner.plan(analysis: analysis, pool: [], seed: 1) + } + var noBeats = analysis + noBeats.beats = [] + #expect(throws: CutPlannerError.noBeats) { + try planner.plan(analysis: noBeats, pool: [profile(motion: 0.5)], seed: 1) + } + #expect(throws: CutPlannerError.noClipLongEnough) { + try planner.plan(analysis: analysis, pool: [profile(duration: 0.2, motion: 0.5)], seed: 1) + } + } + + @Test + func motionProfileAveragesAndSurvivesEncoding() throws { + let source = SourceMotionProfile( + videoID: UUID(), + duration: 4, + hop: 1, + values: [0, 0.5, 1, 1] + ) + #expect(abs(source.meanMotion(start: 0, length: 2) - 0.25) < 1e-9) + #expect(abs(source.meanMotion(start: 2, length: 2) - 1.0) < 1e-9) + + let decoded = try JSONDecoder().decode(SourceMotionProfile.self, from: JSONEncoder().encode(source)) + #expect(decoded == source) + #expect(abs(decoded.meanMotion(start: 1, length: 2) - 0.75) < 1e-9) + } +} + + +// MARK: - 素材の動きの解析 + +@Suite(.serialized) +struct ClipPoolBuilderTests { + private func point(_ time: Double, _ frameDiff: Double) -> VisualFeaturePoint { + VisualFeaturePoint( + time: time, frameDiff: frameDiff, meanLuminance: 0.5, luminanceDiff: 0, + edgeDiff: 0, motionSpike: 0, motionDrop: 0, zScore: 0 + ) + } + + @Test + func placesWindowsInsideTheVideoWithoutOverlap() { + let builder = ClipPoolBuilder() + + #expect(builder.windowRanges(forDuration: 0).isEmpty) + let short = builder.windowRanges(forDuration: 10) + #expect(short.count == 1 && short[0].offset == 0 && short[0].length == 10) + + for duration in [20.0, 45, 100, 600, 7_200] { + let windows = builder.windowRanges(forDuration: duration) + #expect(!windows.isEmpty) + #expect(windows.count <= builder.maxWindowsPerVideo) + for window in windows { + #expect(window.offset >= 0) + #expect(window.offset + window.length <= duration + 1e-9) + } + for (previous, next) in zip(windows, windows.dropFirst()) { + #expect(previous.offset + previous.length <= next.offset + 1e-9) + } + } + #expect(builder.windowRanges(forDuration: 600).count == builder.maxWindowsPerVideo) + } + + @Test + func limitsVideoCountDeterministically() { + var builder = ClipPoolBuilder() + builder.maxVideos = 5 + let sources = (0..<20).map { _ in ClipPoolSource(videoID: UUID(), url: URL(fileURLWithPath: "/dev/null"), duration: 60) } + + let first = builder.select(sources, seed: 1).map(\.videoID) + let again = builder.select(sources, seed: 1).map(\.videoID) + let other = builder.select(sources, seed: 2).map(\.videoID) + + #expect(first.count == 5) + #expect(first == again) + #expect(first != other) + #expect(builder.select(Array(sources.prefix(3)), seed: 1).count == 3) + } + + @Test + func resamplesPointsOntoAnEvenGridAndFillsGaps() { + // 窓は10〜12秒、間隔0.5秒。先頭の点(差が0)は捨てる。10.5〜11の区間には点が無いので直前の値で埋める。 + let points = [point(10.0, 0), point(10.25, 0.2), point(10.5, 0.4), point(11.5, 0.8)] + + let values = ClipPoolBuilder.resample(points: points, offset: 10, length: 2, hop: 0.5) + + #expect(values.count == 4) + #expect(values[0] == 0.2) + #expect(abs(values[1] - 0.4) < 1e-9) + #expect(abs(values[2] - 0.4) < 1e-9) + #expect(abs(values[3] - 0.8) < 1e-9) + #expect(ClipPoolBuilder.resample(points: [point(0, 0)], offset: 0, length: 2, hop: 0.5).isEmpty) + } + + @Test + func normalizesAcrossAllVideosNotPerVideo() { + let quiet = ClipPoolSource(videoID: UUID(), url: URL(fileURLWithPath: "/dev/null"), duration: 10) + let busy = ClipPoolSource(videoID: UUID(), url: URL(fileURLWithPath: "/dev/null"), duration: 10) + let quietWindow = RawMotionWindow(offset: 0, duration: 10, hop: 0.5, values: (0..<20).map { 0.01 + Double($0) * 0.0005 }) + let busyWindow = RawMotionWindow(offset: 5, duration: 10, hop: 0.5, values: (0..<20).map { 0.20 + Double($0) * 0.005 }) + + let profiles = ClipPoolBuilder.normalizedProfiles(from: [(quiet, [quietWindow]), (busy, [busyWindow])]) + + #expect(profiles.count == 2) + let quietMean = profiles[0].meanMotion(start: 0, length: 10) + let busyMean = profiles[1].meanMotion(start: 0, length: 10) + #expect(quietMean < 0.2) + #expect(busyMean > 0.8) + #expect(profiles[1].offset == 5) + for profile in profiles { + #expect(profile.values.allSatisfy { (0...1).contains($0) }) + } + } + + @Test + func measuresRealVideosAndReusesTheCache() async throws { + let directory = try temporaryDirectory("clip-pool") + defer { try? FileManager.default.removeItem(at: directory) } + let activeURL = directory.appendingPathComponent("active.mp4") + let calmURL = directory.appendingPathComponent("calm.mp4") + // 明滅を繰り返す動画と、変化のない動画。 + try await makeTestVideo(at: activeURL, duration: 6) { ($0 / 3) % 2 == 0 ? 40 : 220 } + try await makeTestVideo(at: calmURL, duration: 6) { _ in 128 } + + let active = ClipPoolSource(videoID: UUID(), url: activeURL, duration: 6) + let calm = ClipPoolSource(videoID: UUID(), url: calmURL, duration: 6) + var builder = ClipPoolBuilder() + builder.cacheDirectory = directory.appendingPathComponent("cache") + let reported = LockedCounter() + + let profiles = try await builder.build(sources: [active, calm], seed: 1) { completed, total in + reported.record(completed, of: total) + } + + let activeProfile = try #require(profiles.first { $0.videoID == active.videoID }) + let calmProfile = try #require(profiles.first { $0.videoID == calm.videoID }) + #expect(activeProfile.meanMotion(start: 0, length: 5) > calmProfile.meanMotion(start: 0, length: 5) + 0.5) + #expect(reported.last == (2, 2)) + + let cached = try FileManager.default.contentsOfDirectory(atPath: directory.appendingPathComponent("cache").path) + #expect(cached.count == 2) + let again = try await builder.build(sources: [active, calm], seed: 1) + #expect(again == profiles) + } + + @Test + func skipsUnreadableVideosButFailsWhenNoneWork() async throws { + let directory = try temporaryDirectory("clip-pool-missing") + defer { try? FileManager.default.removeItem(at: directory) } + let goodURL = directory.appendingPathComponent("good.mp4") + try await makeTestVideo(at: goodURL, duration: 3) { _ in 100 } + let good = ClipPoolSource(videoID: UUID(), url: goodURL, duration: 3) + let missing = ClipPoolSource(videoID: UUID(), url: directory.appendingPathComponent("missing.mp4"), duration: 3) + + let profiles = try await ClipPoolBuilder().build(sources: [missing, good], seed: 1) + #expect(Set(profiles.map(\.videoID)) == [good.videoID]) + + await #expect(throws: ClipPoolError.self) { + try await ClipPoolBuilder().build(sources: [missing], seed: 1) + } + await #expect(throws: ClipPoolError.self) { + try await ClipPoolBuilder().build(sources: [], seed: 1) + } + } +} + +/// 進捗コールバックから呼ばれるので、ロックで守った記録用の入れ物。 +private final class LockedCounter: @unchecked Sendable { + private let lock = NSLock() + private var value: (Int, Int) = (-1, -1) + + func record(_ completed: Int, of total: Int) { + lock.lock(); defer { lock.unlock() } + value = (completed, total) + } + + var last: (Int, Int) { + lock.lock(); defer { lock.unlock() } + return value + } +} + +// MARK: - 合成と書き出し + +/// 画像を `columns`×`rows` に区切り、各区画の平均の明るさ(0〜255)を返す。 +private 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 + guard let context = CGContext( + data: buffer.baseAddress, width: width, height: height, bitsPerComponent: 8, + bytesPerRow: width, space: CGColorSpaceCreateDeviceGray(), + bitmapInfo: CGImageAlphaInfo.none.rawValue + ) else { return } + context.draw(image, in: CGRect(x: 0, y: 0, width: width, height: height)) + } + var result: [Double] = [] + let cellWidth = width / columns, cellHeight = height / rows + for row in 0..(_ label: String, _ body: () async throws -> T) async throws -> T { + do { + return try await body() + } catch { + Issue.record("[\(label)] \(error)") + throw error + } +} + +@Suite(.serialized) +struct MusicVideoComposerTests { + private func cut(_ video: UUID, from sourceStart: Double, at start: Double, length: Double) -> PlannedCut { + PlannedCut(videoID: video, sourceStart: sourceStart, duration: length, timelineStart: start, intensity: .medium) + } + + @Test + func composesCutsAtTheRightTimesAndExportsPlayableMP4() async throws { + let directory = try temporaryDirectory("composer") + defer { try? FileManager.default.removeItem(at: directory) } + 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: 6) { _ in 30 } } + try await step("bright video") { try await makeTestVideo(at: brightURL, duration: 6) { _ in 230 } } + try await step("portrait video") { try await makeTestVideo(at: portraitURL, duration: 6, size: (90, 160)) { _ in 128 } } + try await step("audio") { try writeSineWAV(to: musicURL, duration: 6) } + + let dark = UUID(), bright = UUID(), portrait = UUID() + let plan = CutPlan( + cuts: [ + cut(dark, from: 0, at: 0, length: 1), + cut(bright, from: 2, at: 1, length: 1), + cut(dark, from: 3.5, at: 2, length: 1), + cut(portrait, from: 1, at: 3, length: 1), + cut(bright, from: 5, at: 4, length: 1) + ], + duration: 5 + ) + let render = MusicVideoRenderSettings(width: 320, height: 180, framesPerSecond: 30) + let composer = MusicVideoComposer() + + let composed = try await step("compose") { + try await composer.makeComposition( + plan: plan, + sourceURLs: [dark: darkURL, bright: brightURL, portrait: portraitURL], + audioURL: musicURL, + render: render + ) + } + + #expect(abs(composed.duration - 5) < 0.02) + #expect(composed.composition.tracks(withMediaType: .video).count == 1) + #expect(composed.composition.tracks(withMediaType: .audio).count == 1) + #expect(composed.videoComposition.renderSize == render.size) + + let outputURL = directory.appendingPathComponent("out/hmv.mp4") + let progress = LockedCounter() + try await step("export") { + try await composer.export(composed, to: outputURL) { fraction in + progress.record(Int(fraction * 100), of: 100) + } + } + + let output = AVURLAsset(url: outputURL) + let videoTrack = try #require(try await output.loadTracks(withMediaType: .video).first) + #expect(try await output.loadTracks(withMediaType: .audio).count == 1) + #expect(abs(try await output.load(.duration).seconds - 5) < 0.2) + let size = try await videoTrack.load(.naturalSize) + #expect(Int(size.width) == 320 && Int(size.height) == 180) + #expect(progress.last.0 == 100) + + // 各カットの真ん中のフレームの明るさが、計画した素材と一致する。 + let generator = AVAssetImageGenerator(asset: output) + generator.requestedTimeToleranceBefore = .zero + generator.requestedTimeToleranceAfter = .zero + func frame(at seconds: Double) async throws -> [Double] { + try await step("frame at \(seconds)s") { + let (image, _) = try await generator.image(at: CMTime(seconds: seconds, preferredTimescale: 600)) + return lumaGrid(image) + } + } + #expect(try await frame(at: 0.5).allSatisfy { $0 < 80 }) + #expect(try await frame(at: 1.5).allSatisfy { $0 > 170 }) + #expect(try await frame(at: 2.5).allSatisfy { $0 < 80 }) + // 縦長の素材は画面いっぱいに拡大され、四隅まで黒帯にならない。 + #expect(try await frame(at: 3.5).allSatisfy { $0 > 90 && $0 < 170 }) + #expect(try await frame(at: 4.5).allSatisfy { $0 > 170 }) + } + + @Test + func rejectsEmptyPlansAndMissingSources() async throws { + let directory = try temporaryDirectory("composer-errors") + defer { try? FileManager.default.removeItem(at: directory) } + let musicURL = directory.appendingPathComponent("music.wav") + try writeSineWAV(to: musicURL, duration: 2) + let composer = MusicVideoComposer() + + await #expect(throws: MusicVideoComposerError.self) { + try await composer.makeComposition( + plan: CutPlan(cuts: [], duration: 2), sourceURLs: [:], audioURL: musicURL, render: .landscapeHD + ) + } + let unknown = UUID() + await #expect(throws: MusicVideoComposerError.self) { + try await composer.makeComposition( + plan: CutPlan(cuts: [cut(unknown, from: 0, at: 0, length: 2)], duration: 2), + sourceURLs: [:], audioURL: musicURL, render: .landscapeHD + ) + } + } +} + +// MARK: - 曲の解析から書き出しまで通した確認 + +private 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) + let data = try #require(buffer.floatChannelData?[0]) + for (index, sample) in samples.enumerated() { data[index] = sample } + let file = try AVAudioFile(forWriting: url, settings: format.settings) + try file.write(from: buffer) +} + +@Suite(.serialized) +struct MusicVideoPipelineTests { + /// 曲の解析 → 素材の解析 → カット割り → 合成 → 書き出し を通しで動かし、 + /// 完成映像の各カットが、計画した素材の「その時刻」の絵になっていることを確かめる。 + /// 素材の明るさを元動画の時刻に対応させてあるので、位置の取り違えは明るさのずれとして現れる。 + @Test + func exportedFramesMatchThePlannedSourcePositions() async throws { + let directory = try temporaryDirectory("pipeline") + defer { try? FileManager.default.removeItem(at: directory) } + + // 曲: 120BPMのクリック(16秒)。 + 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 + ) + + // 素材: 40秒の動画3本。明るさが時刻に比例して上がる(A, C)ものと下がる(B)もの。 + let rampUp: (Int) -> UInt8 = { frame in UInt8(min(250, 20 + 5 * Double(frame) / 30)) } + let rampDown: (Int) -> UInt8 = { frame in UInt8(max(5, 230 - 5 * Double(frame) / 30)) } + let kinds: [(name: String, brightness: (Int) -> UInt8, rises: Bool)] = [ + ("a", rampUp, true), ("b", rampDown, false), ("c", rampUp, true) + ] + var sources: [ClipPoolSource] = [] + var rises: [UUID: Bool] = [:] + for kind in kinds { + let url = directory.appendingPathComponent("\(kind.name).mp4") + try await makeTestVideo(at: url, duration: 40, brightness: kind.brightness) + let source = ClipPoolSource(videoID: UUID(), url: url, duration: 40) + sources.append(source) + rises[source.videoID] = kind.rises + } + + let analysis = try await BeatAnalyzer().analyze(url: musicURL) + #expect(abs(analysis.tempo - 120) < 2) + + let pool = try await ClipPoolBuilder().build(sources: sources, seed: 1) + // 40秒の動画は、冒頭・末尾を避けた2つの窓に分かれる(窓の開始位置が0でない)。 + #expect(pool.contains { $0.offset > 1 }) + + var planner = CutPlanner() + planner.style = .relaxed + let plan = try planner.plan(analysis: analysis, pool: pool, seed: 3) + #expect(plan.cuts.count >= 3) + // 計画した位置は、すべて解析した窓の内側にある。 + for cut in plan.cuts { + #expect(pool.contains { window in + window.videoID == cut.videoID + && cut.sourceStart >= window.offset - 1e-6 + && cut.sourceStart + cut.duration <= window.offset + window.duration + 1e-6 + }) + } + + let render = MusicVideoRenderSettings(width: 320, height: 180, framesPerSecond: 30) + let composer = MusicVideoComposer() + let composed = try await composer.makeComposition( + plan: plan, + sourceURLs: Dictionary(uniqueKeysWithValues: sources.map { ($0.videoID, $0.url) }), + audioURL: musicURL, + render: render + ) + let outputURL = directory.appendingPathComponent("hmv.mp4") + try await composer.export(composed, to: outputURL) + + let output = AVURLAsset(url: outputURL) + #expect(abs(try await output.load(.duration).seconds - analysis.duration) < 0.3) + + let generator = AVAssetImageGenerator(asset: output) + generator.requestedTimeToleranceBefore = .zero + generator.requestedTimeToleranceAfter = .zero + for cut in plan.cuts { + let middle = cut.timelineStart + cut.duration / 2 + let (image, _) = try await generator.image(at: CMTime(seconds: middle, preferredTimescale: 600)) + let actual = lumaGrid(image).reduce(0, +) / 16 + let sourceTime = cut.sourceStart + cut.duration / 2 + let expected = (rises[cut.videoID] ?? true) ? 20 + 5 * sourceTime : 230 - 5 * sourceTime + #expect(abs(actual - expected) < 25, "t=\(middle) 期待 \(expected) 実際 \(actual)") + } + } +} + +// MARK: - 素材の選び方と設定の保存 + +@Suite(.serialized) +struct MusicVideoSelectionTests { + @MainActor + private func video( + _ id: UUID = UUID(), duration: Double = 30, type: MediaType = .video, + favorite: Bool = false, trashed: Bool = false + ) -> VideoItem { + VideoItem( + id: id, originalFilename: "\(id.uuidString).mp4", internalFilename: "", duration: duration, + importDate: Date(), creationDate: nil, fileHash: "", mediaType: type, + isFavorite: favorite, isInTrash: trashed + ) + } + + @Test @MainActor + func combinesAlbumsIndividualVideosAndFavoritesWithoutDuplicates() { + let (a, b, c, d, e, f) = (UUID(), UUID(), UUID(), UUID(), UUID(), UUID()) + let videos = [video(a), video(b), video(c), video(d), video(e, favorite: true), video(f)] + let albums = [ + Album(id: UUID(), name: "one", videoIDs: [a, b], type: .video), + Album(id: UUID(), name: "two", videoIDs: [b, c], type: .video), + Album(id: UUID(), name: "unselected", videoIDs: [f], type: .video) + ] + + let ids = MusicVideoSourceSelection.candidateIDs( + videos: videos, albums: albums, + selectedAlbumIDs: [albums[0].id, albums[1].id], + selectedVideoIDs: [d], + includeFavorites: true + ) + + // ライブラリの並び順のまま、重複なし。選ばれていない f は入らない。 + #expect(ids == [a, b, c, d, e]) + } + + @Test @MainActor + func excludesTrashPhotosAndTooShortVideos() { + let (ok, trashed, photo, tiny) = (UUID(), UUID(), UUID(), UUID()) + let videos = [ + video(ok), video(trashed, trashed: true), video(photo, type: .photo), video(tiny, duration: 0.4) + ] + let album = Album(id: UUID(), name: "all", videoIDs: [ok, trashed, photo, tiny], type: .mixed) + + let ids = MusicVideoSourceSelection.candidateIDs( + videos: videos, albums: [album], selectedAlbumIDs: [album.id], selectedVideoIDs: [], includeFavorites: false + ) + + #expect(ids == [ok]) + } + + @Test @MainActor + func favoritesOnlyCountWhenTheToggleIsOn() { + let favorite = UUID() + let videos = [video(favorite, favorite: true), video()] + + let off = MusicVideoSourceSelection.candidateIDs( + videos: videos, albums: [], selectedAlbumIDs: [], selectedVideoIDs: [], includeFavorites: false + ) + let on = MusicVideoSourceSelection.candidateIDs( + videos: videos, albums: [], selectedAlbumIDs: [], selectedVideoIDs: [], includeFavorites: true + ) + + #expect(off.isEmpty) + #expect(on == [favorite]) + } + + @Test + func preferencesRoundTripThroughUserDefaults() throws { + let suite = "musicvideo-tests-\(UUID().uuidString)" + let defaults = try #require(UserDefaults(suiteName: suite)) + defer { defaults.removePersistentDomain(forName: suite) } + let store = MusicVideoPreferencesStore(defaults: defaults) + #expect(store.load() == MusicVideoPreferences()) + + var preferences = MusicVideoPreferences() + preferences.cutStyle = .energetic + preferences.renderPreset = .portraitHD + preferences.exportQuality = .compact + preferences.selectedAlbumIDs = [UUID(), UUID()] + preferences.selectedVideoIDs = [UUID()] + preferences.includeFavorites = true + preferences.musicFolderPath = "/Users/example/Music" + preferences.recordRecentMusic("/Users/example/Music/a.mp3") + store.save(preferences) + + #expect(store.load() == preferences) + } + + @Test + func brokenOrOldPreferencesFallBackToDefaults() throws { + let suite = "musicvideo-tests-\(UUID().uuidString)" + let defaults = try #require(UserDefaults(suiteName: suite)) + defer { defaults.removePersistentDomain(forName: suite) } + let store = MusicVideoPreferencesStore(defaults: defaults) + + defaults.set(Data("not json".utf8), forKey: store.key) + #expect(store.load() == MusicVideoPreferences()) + + // 項目が足りない古い保存データでも、読めた分は使い、残りは既定値になる。 + defaults.set(Data(#"{"cutStyle":"relaxed"}"#.utf8), forKey: store.key) + let loaded = store.load() + #expect(loaded.cutStyle == .relaxed) + #expect(loaded.renderPreset == .landscapeFullHD) + #expect(loaded.exportQuality == .high) + #expect(loaded.selectedAlbumIDs.isEmpty) + } + + @Test + func recentMusicKeepsNewestFirstWithoutDuplicatesUpToTheLimit() { + var preferences = MusicVideoPreferences() + for index in 0..<12 { preferences.recordRecentMusic("/m/\(index).mp3") } + preferences.recordRecentMusic("/m/5.mp3") + + #expect(preferences.recentMusicPaths.count == MusicVideoPreferences.recentMusicLimit) + #expect(preferences.recentMusicPaths.first == "/m/5.mp3") + #expect(Set(preferences.recentMusicPaths).count == preferences.recentMusicPaths.count) + #expect(!preferences.recentMusicPaths.contains("/m/0.mp3")) + } + + @Test + func prunedDropsSelectionsThatNoLongerExistInTheLibrary() { + let (keptAlbum, goneAlbum, keptVideo, goneVideo) = (UUID(), UUID(), UUID(), UUID()) + var preferences = MusicVideoPreferences() + preferences.selectedAlbumIDs = [keptAlbum, goneAlbum] + preferences.selectedVideoIDs = [goneVideo, keptVideo] + + let pruned = preferences.pruned(validAlbumIDs: [keptAlbum], validVideoIDs: [keptVideo]) + + #expect(pruned.selectedAlbumIDs == [keptAlbum]) + #expect(pruned.selectedVideoIDs == [keptVideo]) + } +} + +// MARK: - カット単位の差し替え + +@Suite(.serialized) +struct CutEditingTests { + private let duration = 60.0 + + private func makeAnalysis() -> MusicAnalysis { + let beats = Array(stride(from: 0.5, to: duration - 0.1, by: 0.5)) + let energy = [Double](repeating: 0.6, count: Int(duration)) + let intensity = [MusicIntensity](repeating: .medium, count: Int(duration)) + return MusicAnalysis(duration: duration, tempo: 120, beats: beats, energy: energy, intensity: intensity, energyHop: 1) + } + + /// 長さ60秒の窓を1つ持つ動画。`motion` は一定。 + private func window(_ id: UUID = UUID(), offset: Double = 0, length: Double = 60, motion: Double = 0.5) -> SourceMotionProfile { + SourceMotionProfile(videoID: id, offset: offset, duration: length, hop: 0.5, values: [Double](repeating: motion, count: Int(length / 0.5))) + } + + private func makePlan(pool: [SourceMotionProfile], seed: UInt64 = 1) throws -> CutPlan { + try CutPlanner().plan(analysis: makeAnalysis(), pool: pool, seed: seed) + } + + private func range(of cut: PlannedCut) -> Range { cut.sourceStart..<(cut.sourceStart + cut.duration) } + + @Test + func replacingACutKeepsItsSlotAndLeavesOtherCutsUntouched() throws { + let pool = (0..<5).map { _ in window() } + let plan = try makePlan(pool: pool) + let index = plan.cuts.count / 2 + + let edited = try CutPlanner().replaceCut(at: index, in: plan, analysis: makeAnalysis(), pool: pool, seed: 7) + + #expect(edited.cuts.count == plan.cuts.count) + #expect(edited.duration == plan.duration) + let before = plan.cuts[index], after = edited.cuts[index] + #expect(after.timelineStart == before.timelineStart) + #expect(after.duration == before.duration) + #expect(after.intensity == before.intensity) + // 元の区間とは重ならない別の位置(動画が変わるか、同じ動画なら別の場所)になる。 + #expect(after.videoID != before.videoID || !range(of: after).overlaps(range(of: before))) + for other in plan.cuts.indices where other != index { + #expect(edited.cuts[other] == plan.cuts[other]) + } + } + + @Test + func replacementAvoidsTheNeighboursVideoWhenOthersExist() throws { + let pool = (0..<5).map { _ in window() } + let plan = try makePlan(pool: pool) + + for index in [1, plan.cuts.count / 2, plan.cuts.count - 2] { + for seed in UInt64(1)...UInt64(5) { + let edited = try CutPlanner().replaceCut(at: index, in: plan, analysis: makeAnalysis(), pool: pool, seed: seed) + #expect(edited.cuts[index].videoID != plan.cuts[index - 1].videoID) + #expect(edited.cuts[index].videoID != plan.cuts[index + 1].videoID) + } + } + } + + @Test + func exclusionAndForcedVideoAreHonoured() throws { + let target = UUID() + let pool = [window(target), window(), window(), window()] + let plan = try makePlan(pool: pool) + let planner = CutPlanner() + let analysis = makeAnalysis() + + for index in plan.cuts.indices.prefix(20) { + let excluded = try planner.replaceCut(at: index, in: plan, analysis: analysis, pool: pool, seed: 3, excluding: [target]) + #expect(excluded.cuts[index].videoID != target) + + let forced = try planner.replaceCut(at: index, in: plan, analysis: analysis, pool: pool, seed: 3, forcing: target) + #expect(forced.cuts[index].videoID == target) + } + } + + @Test + func replacementStaysInsideTheAnalyzedWindows() throws { + let video = UUID() + let pool = [ + window(video, offset: 10, length: 15), + window(video, offset: 200, length: 15), + window(offset: 50, length: 15) + ] + let plan = try makePlan(pool: pool) + + for index in plan.cuts.indices.prefix(30) { + let edited = try CutPlanner().replaceCut(at: index, in: plan, analysis: makeAnalysis(), pool: pool, seed: 11) + let cut = edited.cuts[index] + #expect(pool.contains { window in + window.videoID == cut.videoID + && cut.sourceStart >= window.offset - 1e-9 + && cut.sourceStart + cut.duration <= window.offset + window.duration + 1e-9 + }) + } + } + + @Test + func isDeterministicAndVariesWithTheSeed() throws { + let pool = (0..<6).map { _ in window() } + let plan = try makePlan(pool: pool) + let planner = CutPlanner() + let analysis = makeAnalysis() + let index = 10 + + let first = try planner.replaceCut(at: index, in: plan, analysis: analysis, pool: pool, seed: 21) + let again = try planner.replaceCut(at: index, in: plan, analysis: analysis, pool: pool, seed: 21) + #expect(first == again) + + let results = try (1...12).map { seed in + try planner.replaceCut(at: index, in: plan, analysis: analysis, pool: pool, seed: UInt64(seed)).cuts[index] + } + #expect(Set(results.map { "\($0.videoID)-\($0.sourceStart)" }).count > 1) + } + + @Test + func replacingEveryUseOfAVideoRemovesItEverywhere() throws { + let unwanted = UUID() + let pool = [window(unwanted), window(), window(), window()] + let plan = try makePlan(pool: pool) + #expect(plan.cuts.contains { $0.videoID == unwanted }) + + let edited = try CutPlanner().replaceAllCuts(usingVideo: unwanted, in: plan, analysis: makeAnalysis(), pool: pool, seed: 5) + + #expect(!edited.cuts.contains { $0.videoID == unwanted }) + #expect(edited.cuts.map(\.timelineStart) == plan.cuts.map(\.timelineStart)) + #expect(edited.cuts.map(\.duration) == plan.cuts.map(\.duration)) + // 他の動画を使っていたカットはそのまま。 + for index in plan.cuts.indices where plan.cuts[index].videoID != unwanted { + #expect(edited.cuts[index] == plan.cuts[index]) + } + } + + @Test + func reportsAProblemInsteadOfCrashingWhenNothingCanBeUsed() throws { + let only = UUID() + let pool = [window(only)] + let plan = try makePlan(pool: pool) + let planner = CutPlanner() + let analysis = makeAnalysis() + + // 動画が1本だけでも、別の位置を選べる。 + let edited = try planner.replaceCut(at: 3, in: plan, analysis: analysis, pool: pool, seed: 1) + #expect(edited.cuts[3].videoID == only) + + // 候補をすべて除外すると、エラーになる。 + #expect(throws: CutPlannerError.emptyPool) { + try planner.replaceCut(at: 3, in: plan, analysis: analysis, pool: pool, seed: 1, excluding: [only]) + } + // 指定した動画に、カットの長さを満たす窓がなければエラー。 + let tooShort = window(UUID(), length: 0.2) + #expect(throws: CutPlannerError.noClipLongEnough) { + try planner.replaceCut(at: 3, in: plan, analysis: analysis, pool: pool + [tooShort], seed: 1, forcing: tooShort.videoID) + } + // 範囲外の番号は何も変えない。 + #expect(try planner.replaceCut(at: 9_999, in: plan, analysis: analysis, pool: pool, seed: 1) == plan) + } + + @Test + func findsTheCutAtAGivenTime() throws { + let plan = try makePlan(pool: [window(), window()]) + + #expect(plan.cutIndex(at: 0) == 0) + #expect(plan.cutIndex(at: -5) == 0) + #expect(plan.cutIndex(at: plan.duration + 100) == plan.cuts.count - 1) + for index in plan.cuts.indices { + let cut = plan.cuts[index] + #expect(plan.cutIndex(at: cut.timelineStart) == index) + #expect(plan.cutIndex(at: cut.timelineStart + cut.duration / 2) == index) + } + #expect(CutPlan(cuts: [], duration: 0).cutIndex(at: 1) == nil) + } +} + + +// MARK: - 書き出しの画質 + +/// 動きのある模様の動画(単色だとビットレートの差が出ないため)。 +private func makePatternVideo(at url: URL, duration: Double, width: Int = 640, height: Int = 360) async throws { + let framesPerSecond: Int32 = 30 + let writer = try AVAssetWriter(outputURL: url, fileType: .mp4) + let input = AVAssetWriterInput( + mediaType: .video, + outputSettings: [ + AVVideoCodecKey: AVVideoCodecType.h264, AVVideoWidthKey: width, AVVideoHeightKey: height, + AVVideoCompressionPropertiesKey: [AVVideoAverageBitRateKey: 6_000_000] + ] + ) + let adaptor = AVAssetWriterInputPixelBufferAdaptor( + assetWriterInput: input, + sourcePixelBufferAttributes: [ + kCVPixelBufferPixelFormatTypeKey as String: kCVPixelFormatType_32BGRA, + kCVPixelBufferWidthKey as String: width, kCVPixelBufferHeightKey as String: height + ] + ) + writer.add(input) + #expect(writer.startWriting()) + writer.startSession(atSourceTime: .zero) + for frame in 0.. standard && standard > compact) + #expect(MusicVideoExportQuality.high.videoBitRate(for: hd) < high) + // 縦向きでも画素数が同じなら同じビットレート。 + #expect(MusicVideoExportQuality.high.videoBitRate(for: .portraitFullHD) == high) + // 1080pの「高画質」は、実測した従来の書き出し(約10Mbps)とほぼ同じ。 + #expect(abs(Double(high) - 10_000_000) < 500_000) + #expect(MusicVideoExportQuality.compact.estimatedMegabytesPerMinute(for: full) < MusicVideoExportQuality.high.estimatedMegabytesPerMinute(for: full)) + } + + @Test + func lowerQualityMakesSmallerFilesThatStillPlayCorrectly() async throws { + let directory = try temporaryDirectory("export-quality") + defer { try? FileManager.default.removeItem(at: directory) } + let videoURL = directory.appendingPathComponent("pattern.mp4") + let musicURL = directory.appendingPathComponent("music.wav") + try await makePatternVideo(at: videoURL, duration: 8) + try writeSineWAV(to: musicURL, duration: 6) + + let video = UUID() + let plan = CutPlan( + cuts: (0..<6).map { index in + PlannedCut(videoID: video, sourceStart: Double(index), duration: 1, timelineStart: Double(index), intensity: .medium) + }, + duration: 6 + ) + let render = MusicVideoRenderSettings(width: 640, height: 360, framesPerSecond: 30) + let composer = MusicVideoComposer() + let composed = try await composer.makeComposition(plan: plan, sourceURLs: [video: videoURL], audioURL: musicURL, render: render) + + var sizes: [MusicVideoExportQuality: Int] = [:] + for quality in MusicVideoExportQuality.allCases { + let outputURL = directory.appendingPathComponent("out-\(quality.rawValue).mp4") + try await composer.export(composed, to: outputURL, quality: quality) + sizes[quality] = (try FileManager.default.attributesOfItem(atPath: outputURL.path)[.size] as? Int) ?? 0 + + // どの画質でも、画面サイズ・長さ・音声は変わらない。 + let asset = AVURLAsset(url: outputURL) + let track = try #require(try await asset.loadTracks(withMediaType: .video).first) + let size = try await track.load(.naturalSize) + #expect(Int(size.width) == 640 && Int(size.height) == 360) + #expect(abs(try await asset.load(.duration).seconds - 6) < 0.2) + #expect(try await asset.loadTracks(withMediaType: .audio).count == 1) + } + + let high = try #require(sizes[.high]), standard = try #require(sizes[.standard]), compact = try #require(sizes[.compact]) + #expect(high > standard, "高画質 \(high) 標準 \(standard)") + #expect(standard > compact, "標準 \(standard) 小さめ \(compact)") + } + + @Test + func cancellingAnExportLeavesNoFile() async throws { + let directory = try temporaryDirectory("export-cancel") + defer { try? FileManager.default.removeItem(at: directory) } + let videoURL = directory.appendingPathComponent("pattern.mp4") + let musicURL = directory.appendingPathComponent("music.wav") + try await makePatternVideo(at: videoURL, duration: 12) + try writeSineWAV(to: musicURL, duration: 10) + let video = UUID() + let plan = CutPlan( + cuts: (0..<10).map { PlannedCut(videoID: video, sourceStart: Double($0), duration: 1, timelineStart: Double($0), intensity: .medium) }, + duration: 10 + ) + let composer = MusicVideoComposer() + let composed = try await composer.makeComposition( + plan: plan, sourceURLs: [video: videoURL], audioURL: musicURL, + render: MusicVideoRenderSettings(width: 640, height: 360, framesPerSecond: 30) + ) + // 取り消すタイミングを変えて何度も試す(開始前・読み出し中・終わりぎわ)。 + for (attempt, delay) in [0, 5, 20, 50, 100, 150, 250, 400, 700].enumerated() { + let outputURL = directory.appendingPathComponent("cancelled-\(attempt).mp4") + let task = Task { try await composer.export(composed, to: outputURL, quality: .high) } + try await Task.sleep(for: .milliseconds(delay)) + task.cancel() + let result = await task.result + + switch result { + case .success: + // 取り消しより先に終わった場合は、完成したファイルがあればよい。 + #expect(FileManager.default.fileExists(atPath: outputURL.path), "試行\(attempt)") + case .failure(let error): + #expect(error is CancellationError, "試行\(attempt): \(error)") + #expect(!FileManager.default.fileExists(atPath: outputURL.path), "試行\(attempt)") + } + } + } + + @Test @MainActor + 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.hasSuffix(".mp4")) + #expect(!name.dropFirst(4).contains("/")) + } +}