diff --git a/ArkServer/Features/MusicVideo/Models/MusicVideoPlanStats.swift b/ArkServer/Features/MusicVideo/Models/MusicVideoPlanStats.swift index 8915f3e..9909bf6 100644 --- a/ArkServer/Features/MusicVideo/Models/MusicVideoPlanStats.swift +++ b/ArkServer/Features/MusicVideo/Models/MusicVideoPlanStats.swift @@ -14,6 +14,10 @@ nonisolated struct MusicVideoPlanStats: Equatable, Sendable { var poolVideoCount: Int /// 映像の動きが、曲の盛り上がりにどれだけ合っているか(0〜1)。調べられないときは nil。 var motionMatch: Double? + /// 曲の強い拍に、映像の「急に動いた瞬間」が重なっている割合(0〜1)。調べられないときは nil。 + var hitAlignment: Double? + /// 曲の盛り上がりと映像の動きの強さの相関(-1〜1)。調べられないときは nil。 + var energyCorrelation: Double? init(plan: CutPlan, pool: [SourceMotionProfile], analysis: MusicAnalysis?) { let durations = plan.cuts.map(\.duration) @@ -24,6 +28,11 @@ nonisolated struct MusicVideoPlanStats: Equatable, Sendable { usedVideoCount = Set(plan.cuts.map(\.videoID)).count poolVideoCount = Set(pool.map(\.videoID)).count motionMatch = analysis.flatMap { Self.motionMatch(plan: plan, pool: pool, analysis: $0) } + if let analysis { + let sync = MusicVideoSyncMetrics(plan: plan, analysis: analysis, pool: pool) + hitAlignment = sync.hitAlignment + energyCorrelation = sync.energyCorrelation + } } /// 各カットの素材の動きと、狙った動きとの差の平均を、1 から引いた値。 @@ -77,6 +86,10 @@ nonisolated struct MusicVideoChangeSummary: Equatable, Sendable { abs(oldMatch - newMatch) >= 0.01 { parts.append("動きの一致 \(Self.percent(oldMatch)) → \(Self.percent(newMatch))") } + if let oldHit = before.hitAlignment, let newHit = after.hitAlignment, + abs(oldHit - newHit) >= 0.01 { + parts.append("拍の一致 \(Self.percent(oldHit)) → \(Self.percent(newHit))") + } if parts.isEmpty { return "「\(title)」を変えました.数値の上では大きな違いはありません." } return "「\(title)」を変えました:" + parts.joined(separator: "・") } diff --git a/ArkServer/Features/MusicVideo/Models/MusicVideoSyncMetrics.swift b/ArkServer/Features/MusicVideo/Models/MusicVideoSyncMetrics.swift new file mode 100644 index 0000000..697b173 --- /dev/null +++ b/ArkServer/Features/MusicVideo/Models/MusicVideoSyncMetrics.swift @@ -0,0 +1,84 @@ +// ArkServer/Features/MusicVideo/Models/MusicVideoSyncMetrics.swift + +import Foundation + +/// 曲と映像の動きが、どれだけ合っているかを表す数値。 +/// +/// カット割り(`CutPlan`)の各カットを素材の時刻にたどり、「そのとき映像で何が起きているか」を曲の時刻に並べ直して測る。 +/// 調整項目の効果を、体感ではなく数値で見られるようにするためと、合わせ込みの改良を測るために使う。 +nonisolated struct MusicVideoSyncMetrics: Equatable, Sendable { + /// 強い拍(拍の強さ 0.6 以上)の前後 0.09 秒に、映像の「急に動いた瞬間」がある度合い(0〜1の平均)。 + /// 1 に近いほど、曲の強い音と映像の大きな動きが同じ瞬間に起きている。調べられないときは nil。 + var hitAlignment: Double? + /// 曲の盛り上がりと、映像の動きの強さの相関(-1〜1)。1 に近いほど、盛り上がる所で映像も激しく動く。調べられないときは nil。 + var energyCorrelation: Double? + /// `hitAlignment` に使った強い拍の数。 + var strongBeatCount: Int + + /// 強い拍とみなす拍の強さ。 + static let strongAccent = 0.6 + /// 拍と衝撃が「同じ瞬間」とみなす時間のずれ(秒)。映像の標本間隔(約0.083秒)に合わせた値。 + static let hitTolerance = 0.09 + + init(plan: CutPlan, analysis: MusicAnalysis, pool: [SourceMotionProfile]) { + var windows: [UUID: [SourceMotionProfile]] = [:] + for profile in pool { windows[profile.videoID, default: []].append(profile) } + + /// 時刻 `time`(曲の時刻=映像の時刻)に映されている素材の、(窓, 窓の中の位置の秒数)。 + func footage(at time: Double) -> (profile: SourceMotionProfile, seconds: Double)? { + guard let cutIndex = plan.cutIndex(at: time) else { return nil } + let cut = plan.cuts[cutIndex] + let sourceTime = cut.sourceStart + (time - cut.timelineStart) + guard let profile = windows[cut.videoID]?.first(where: { + sourceTime >= $0.offset - 1e-6 && sourceTime <= $0.offset + $0.duration + 1e-6 + }) else { return nil } + return (profile, sourceTime - profile.offset) + } + + // 拍と衝撃の一致。 + var strongBeats = analysis.beats.indices.filter { analysis.accent(atBeat: $0) >= Self.strongAccent } + if analysis.beatAccents.isEmpty { strongBeats = Array(analysis.beats.indices) } + var alignments: [Double] = [] + for index in strongBeats { + guard let (profile, seconds) = footage(at: analysis.beats[index]), !profile.impacts.isEmpty, profile.hop > 0 else { continue } + let first = max(0, Int(((seconds - Self.hitTolerance) / profile.hop).rounded(.down))) + let last = min(profile.impacts.count - 1, Int(((seconds + Self.hitTolerance) / profile.hop).rounded(.up))) + guard first <= last else { continue } + alignments.append(profile.impacts[first...last].max() ?? 0) + } + strongBeatCount = alignments.count + hitAlignment = alignments.isEmpty ? nil : alignments.reduce(0, +) / Double(alignments.count) + + // 盛り上がりと動きの強さの相関(0.25 秒ごとに標本を取る)。 + var music: [Double] = [] + var video: [Double] = [] + var time = 0.0 + while time < plan.duration { + if let (profile, seconds) = footage(at: time), profile.hop > 0, !profile.values.isEmpty { + let index = min(profile.values.count - 1, max(0, Int(seconds / profile.hop))) + music.append(analysis.energy(at: time)) + video.append(profile.values[index]) + } + time += 0.25 + } + energyCorrelation = Self.pearson(music, video) + } + + /// ピアソンの相関係数。標本が少ない・どちらかが一定のときは nil。 + static func pearson(_ x: [Double], _ y: [Double]) -> Double? { + guard x.count == y.count, x.count >= 8 else { return nil } + let n = Double(x.count) + let meanX = x.reduce(0, +) / n + let meanY = y.reduce(0, +) / n + var covariance = 0.0 + var varianceX = 0.0 + var varianceY = 0.0 + for (a, b) in zip(x, y) { + covariance += (a - meanX) * (b - meanY) + varianceX += (a - meanX) * (a - meanX) + varianceY += (b - meanY) * (b - meanY) + } + guard varianceX > 1e-12, varianceY > 1e-12 else { return nil } + return covariance / (varianceX * varianceY).squareRoot() + } +} diff --git a/ArkServer/Features/MusicVideo/Models/MusicVideoTuning.swift b/ArkServer/Features/MusicVideo/Models/MusicVideoTuning.swift index cab2dd0..2fcf554 100644 --- a/ArkServer/Features/MusicVideo/Models/MusicVideoTuning.swift +++ b/ArkServer/Features/MusicVideo/Models/MusicVideoTuning.swift @@ -42,6 +42,38 @@ nonisolated enum MotionMatching: String, Codable, CaseIterable, Hashable, Sendab } } +/// 曲の拍(強い拍・小節の頭・曲の変わり目)に、映像の大きな動き(動作の始まり・衝撃)を重ねる強さ。 +nonisolated enum HitSync: String, Codable, CaseIterable, Hashable, Sendable { + case off + case standard + case strong + + var displayName: String { + switch self { + case .off: return "合わせない" + case .standard: return "標準" + case .strong: return "強い" + } + } + + /// 拍と衝撃の一致を、採点でどれだけ重くみるか。 + var weight: Double { + switch self { + case .off: return 0 + case .standard: return 1.5 + case .strong: return 3 + } + } + + var summary: String { + switch self { + case .off: return "拍の位置は気にせず、動きの強さだけで素材を選びます." + case .standard: return "曲の強い拍に、映像の大きな動き(動き出し・衝撃)が重なる素材を、優先して選びます." + case .strong: return "曲の強い拍・小節の頭・曲の変わり目に、映像の大きな動きを重ねることを最優先にします.素材が偏ることがあります." + } + } +} + /// 同じ動画を、どれだけ避けるか(どれだけいろいろな動画を使うか)。 nonisolated enum VideoVariety: String, Codable, CaseIterable, Hashable, Sendable { case wide @@ -121,6 +153,8 @@ nonisolated struct MusicVideoCutTuning: Codable, Equatable, Sendable { /// これより長いカットは作らない(秒)。nil なら制限しない。 var maximumCutDuration: Double? var motionMatching: MotionMatching = .standard + /// 曲の拍に、映像の大きな動きを重ねる強さ。 + var hitSync: HitSync = .strong var variety: VideoVariety = .standard var alignment: CutAlignment = .bar @@ -140,6 +174,24 @@ nonisolated struct MusicVideoCutTuning: Codable, Equatable, Sendable { } } +extension MusicVideoCutTuning { + private enum CodingKeys: String, CodingKey { + case minimumCutDuration, maximumCutDuration, motionMatching, hitSync, variety, alignment + } + + /// 項目が足りない古い保存データでも、読めた分は使い、残りは既定値にする。 + init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + let defaults = MusicVideoCutTuning() + minimumCutDuration = try container.decodeIfPresent(Double.self, forKey: .minimumCutDuration) ?? defaults.minimumCutDuration + maximumCutDuration = try container.decodeIfPresent(Double.self, forKey: .maximumCutDuration) + motionMatching = try container.decodeIfPresent(MotionMatching.self, forKey: .motionMatching) ?? defaults.motionMatching + hitSync = try container.decodeIfPresent(HitSync.self, forKey: .hitSync) ?? defaults.hitSync + variety = try container.decodeIfPresent(VideoVariety.self, forKey: .variety) ?? defaults.variety + alignment = try container.decodeIfPresent(CutAlignment.self, forKey: .alignment) ?? defaults.alignment + } +} + /// 画面に素材をどう収めるか。 nonisolated enum MusicVideoFitMode: String, Codable, CaseIterable, Hashable, Sendable { /// 画面いっぱいに敷き詰める(はみ出す部分は切り落とす)。 diff --git a/ArkServer/Features/MusicVideo/Services/CutPlanner.swift b/ArkServer/Features/MusicVideo/Services/CutPlanner.swift index 5f892e2..faf43b5 100644 --- a/ArkServer/Features/MusicVideo/Services/CutPlanner.swift +++ b/ArkServer/Features/MusicVideo/Services/CutPlanner.swift @@ -1,9 +1,18 @@ // ArkServer/Features/MusicVideo/Services/CutPlanner.swift +import Accelerate import Foundation /// 曲の拍と盛り上がりから、カット割りと素材の区間を決める純粋ロジック。 /// 同じ入力と同じシードなら、必ず同じ結果になる。 +/// +/// 素材の選び方(`pickClip`)は、候補をランダムに数十回試すのではなく、すべての素材のすべての位置を採点して、いちばん良いものを選ぶ。 +/// 採点は次の3つを足したもの。 +/// 1. 動きの強さの一致: カットの間の映像の平均の動きが、曲の盛り上がりに合っているか。 +/// 2. 拍と衝撃の一致: 曲の拍(音の立ち上がり)の山と、映像の「急に動いた瞬間」の山が、同じ時刻に重なるか。 +/// 重なりは、カットの中の時間変化の類似度(コサイン類似度)で測る。 +/// 3. カットの頭の一致: カットは拍の上で切り替わるので、その瞬間に映像が動き出しているか(曲の頭の強さに応じて)。 +/// 全位置の採点は、Accelerate でまとめて行うので、素材が数百の窓あっても遅くならない。 nonisolated struct CutPlanner: Sendable { var style: MusicVideoCutStyle = .standard /// これより短いカットは作らない(拍が速すぎる曲では切り替えの間隔を倍にする)。 @@ -17,8 +26,8 @@ nonisolated struct CutPlanner: Sendable { var variety: VideoVariety = .standard /// 切り替えの位置を、小節の頭にそろえるか。 var alignment: CutAlignment = .bar - /// 1カットごとに試す素材候補の数。多いほど動きの一致度が上がる。 - var candidateAttemptsPerCut = 40 + /// 曲の拍(強い拍・小節の頭・曲の変わり目)に、映像の大きな動きを重ねる強さ。 + var hitSync: HitSync = .strong init() {} @@ -29,6 +38,7 @@ nonisolated struct CutPlanner: Sendable { motionMatching = tuning.motionMatching variety = tuning.variety alignment = tuning.alignment + hitSync = tuning.hitSync } func plan( @@ -39,8 +49,11 @@ nonisolated struct CutPlanner: Sendable { guard !analysis.beats.isEmpty else { throw CutPlannerError.noBeats } guard !pool.isEmpty else { throw CutPlannerError.emptyPool } - var generator = SeededGenerator(seed: seed) + let noise = NoiseSource(seed: seed) let grid = makeGrid(analysis: analysis) + // 格子の添字 i(1以上)は、拍の添字 i - 1 + beatOffset にあたる(先頭付近の短い拍は格子から除いてある)。 + let beatOffset = analysis.beats.firstIndex { $0 > 0.05 } ?? 0 + let barPhase = analysis.downbeatPhase ?? 0 var cuts: [PlannedCut] = [] var usage: [UUID: Int] = [:] var usedRanges: [UUID: [Range]] = [:] @@ -49,7 +62,9 @@ nonisolated struct CutPlanner: Sendable { 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 step = nextStep(from: index, intensity: intensity, grid: grid, beatNumberOffset: beatOffset - barPhase) + // 曲の構造が変わる所(サビ・ドロップ)に、カットの境目を合わせる。 + step = sectionAlignedStep(index: index, step: step, grid: grid, boundaries: analysis.sectionBoundaries) var end = grid[min(grid.count - 1, index + step)] // 素材が足りないときは、拍の位置を保ったままカットを短くする。 @@ -69,16 +84,25 @@ nonisolated struct CutPlanner: Sendable { let length = end - start guard length > 0 else { break } + let signal = MusicCutSignal( + analysis: analysis, + start: start, + length: length, + accentAtStart: accentAtStart(analysis: analysis, gridIndex: index, beatOffset: beatOffset, start: start) + ) let target = Self.targetMotion(intensity: intensity, start: start, length: length, analysis: analysis) + + (signal.isSectionStart ? 0.1 : 0) guard let choice = pickClip( length: length, - target: target, + target: min(1, target), pool: pool, avoidVideoIDs: cuts.last.map { [$0.videoID] } ?? [], usage: usage, usedRanges: usedRanges, forbidden: nil, - generator: &generator + music: signal, + noise: noise, + cutKey: UInt64(cuts.count) ) else { throw CutPlannerError.noClipLongEnough } @@ -127,7 +151,8 @@ nonisolated struct CutPlanner: Sendable { /// 現在位置から次のカット境界までの拍数。 /// 長いカット(2拍以上)は小節の頭に揃える(`alignment` が `.bar` のとき)。 - private func nextStep(from index: Int, intensity: MusicIntensity, grid: [Double]) -> Int { + /// - Parameter beatNumberOffset: 格子の添字 - 1 に足すと、「小節の1拍目から数えた拍の番号」になる値。 + private func nextStep(from index: Int, intensity: MusicIntensity, grid: [Double], beatNumberOffset: Int) -> Int { let beatInterval = averageInterval(grid: grid, around: index) let beats = effectiveBeats(for: intensity, beatInterval: beatInterval) let remainingSteps = max(1, grid.count - 1 - index) @@ -139,8 +164,9 @@ nonisolated struct CutPlanner: Sendable { let introGap = grid[1] - grid[0] step = introGap >= minimumCutDuration ? 1 : beats + 1 } else if beats >= 2, alignment == .bar { - // 以降は、小節(beats 拍)の頭に境界を揃える。拍の番号は格子の番号 - 1。 - let remainder = (index - 1) % beats + // 以降は、小節(beats 拍)の頭に境界を揃える。 + let beatNumber = index - 1 + beatNumberOffset + let remainder = ((beatNumber % beats) + beats) % beats if remainder != 0 { let toBoundary = beats - remainder step = toBoundary >= max(1, beats / 2) ? toBoundary : toBoundary + beats @@ -162,12 +188,35 @@ nonisolated struct CutPlanner: Sendable { return step } - /// カットが狙う動きの大きさ(0〜1)。段階ごとの目安と、その時点の連続的な盛り上がりの平均。 - static func targetMotion(intensity: MusicIntensity, start: Double, length: Double, analysis: MusicAnalysis) -> Double { - let midpoint: Double = start + length / 2 - let levelTarget: Double = intensity.targetMotion - let energyTarget: Double = analysis.energy(at: midpoint) - return (levelTarget + energyTarget) / 2 + /// カットの途中に曲の構造の境目(サビ・ドロップ)があれば、そこでカットを区切るよう拍の数を縮める。 + /// 境目が最短のカットより手前にあるときや、近い拍が無いときは、そのまま。 + private func sectionAlignedStep(index: Int, step: Int, grid: [Double], boundaries: [Double]) -> Int { + guard !boundaries.isEmpty, step > 1 else { return step } + let start = grid[index] + let end = grid[min(grid.count - 1, index + step)] + guard let boundary = boundaries.first(where: { $0 > start + minimumCutDuration && $0 < end - 0.05 }) else { return step } + + var bestStep = step + var bestDistance = Double.infinity + for candidate in 1..= minimumCutDuration - 1e-9 else { return step } + return bestStep + } + + /// カットの頭にあたる拍の強さ(0〜1)。小節の頭は強めに、曲の構造の境目は最大にする。 + private func accentAtStart(analysis: MusicAnalysis, gridIndex: Int, beatOffset: Int, start: Double) -> Double { + if analysis.sectionBoundaries.contains(where: { abs($0 - start) < 0.03 }) { return 1 } + guard gridIndex >= 1 else { return 0.5 } + let beatIndex = gridIndex - 1 + beatOffset + var accent = analysis.accent(atBeat: beatIndex) + if analysis.isDownbeat(beatIndex: beatIndex) == true { accent = max(accent, 0.8) } + return accent } private func averageInterval(grid: [Double], around index: Int) -> Double { @@ -178,13 +227,25 @@ nonisolated struct CutPlanner: Sendable { return (grid[upper] - grid[lower]) / Double(upper - lower) } + /// カットが狙う動きの大きさ(0〜1)。段階ごとの目安と、その時点の連続的な盛り上がりの平均。 + static func targetMotion(intensity: MusicIntensity, start: Double, length: Double, analysis: MusicAnalysis) -> Double { + let midpoint: Double = start + length / 2 + let levelTarget: Double = intensity.targetMotion + let energyTarget: Double = analysis.energy(at: midpoint) + return (levelTarget + energyTarget) / 2 + } + // MARK: - 素材の選択 - private struct ClipChoice { + struct ClipChoice { let videoID: UUID let start: Double } + /// 1つのカットを、素材のすべての位置の中から、いちばん点の高いものに決める。 + /// - Parameters: + /// - music: このカットの間の曲の拍・音の立ち上がり。nil(または情報なし)なら、動きの強さの一致だけで選ぶ。 + /// - cutKey: カットごとに乱数の使い方を変えるための値(同じ種でも、別のカットは別の揺らぎになる)。 private func pickClip( length: Double, target: Double, @@ -193,48 +254,169 @@ nonisolated struct CutPlanner: Sendable { usage: [UUID: Int], usedRanges: [UUID: [Range]], forbidden: (videoID: UUID, range: Range)?, - generator: inout SeededGenerator + music: MusicCutSignal?, + noise: NoiseSource, + cutKey: UInt64 ) -> ClipChoice? { - let feasible = pool.filter { $0.duration >= length } + let feasible = pool.filter { $0.duration >= length && $0.hop > 0 && !$0.values.isEmpty } 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 + func search(honoringForbidden: Bool) -> ClipChoice? { + var pulseCache: [Int: [Double]] = [:] + var best: (score: Double, videoID: UUID, start: Double)? + for (profileIndex, profile) in feasible.enumerated() { + let scored = bestPosition( + in: profile, + length: length, + target: target, + music: music, + pulseCache: &pulseCache, + penalty: Self.scalarPenalty( + for: profile, + hasAlternative: hasAlternative, + avoidVideoIDs: avoidVideoIDs, + usage: usage, + variety: variety + ), + usedRanges: usedRanges[profile.videoID] ?? [], + overlapPenalty: variety.overlapPenalty, + forbidden: honoringForbidden && forbidden?.videoID == profile.videoID ? forbidden?.range : nil, + noise: noise, + noiseKey: cutKey &* 7_919 &+ UInt64(profileIndex) + ) + guard let scored else { continue } + if best == nil || scored.score > best!.score { + best = (scored.score, profile.videoID, scored.start) } + } + return best.map { ClipChoice(videoID: $0.videoID, start: $0.start) } + } - var score = -motionMatching.weight * abs(motion - target) - if hasAlternative, avoidVideoIDs.contains(profile.videoID) { score -= variety.avoidLastPenalty } - score -= variety.usagePenalty * Double(usage[profile.videoID] ?? 0) - if (usedRanges[profile.videoID] ?? []).contains(where: { $0.overlaps(range) }) { score -= variety.overlapPenalty } - score += 0.05 * Double.random(in: 0...1, using: &generator) + // 禁止された区間を避けられる候補が見つからないときだけ、禁止なしでもう一度探す。 + return search(honoringForbidden: true) ?? search(honoringForbidden: false) + } + + /// 動画の使われ方による減点(位置に依らず、その動画に一律)。 + private static func scalarPenalty( + for profile: SourceMotionProfile, + hasAlternative: Bool, + avoidVideoIDs: Set, + usage: [UUID: Int], + variety: VideoVariety + ) -> Double { + var penalty = variety.usagePenalty * Double(usage[profile.videoID] ?? 0) + if hasAlternative, avoidVideoIDs.contains(profile.videoID) { penalty += variety.avoidLastPenalty } + return penalty + } + + /// 1つの窓の中で、いちばん点の高い開始位置とその点。使える位置が無ければ nil。 + private func bestPosition( + in profile: SourceMotionProfile, + length: Double, + target: Double, + music: MusicCutSignal?, + pulseCache: inout [Int: [Double]], + penalty: Double, + usedRanges: [Range], + overlapPenalty: Double, + forbidden: Range?, + noise: NoiseSource, + noiseKey: UInt64 + ) -> (score: Double, start: Double)? { + let hop = profile.hop + let n = max(1, Int((length / hop - 1e-9).rounded(.up))) + let lastIndexByLength = Int(((profile.duration - length) / hop + 1e-9).rounded(.down)) + let positions = min(profile.values.count - n + 1, lastIndexByLength + 1) + guard positions >= 1, profile.prefixSums.count >= n + positions else { return nil } + + // 1. 動きの強さの一致: 平均の動きと狙いの差。 + var scores = [Double](repeating: 0, count: positions) + if motionMatching.weight > 0 { + let sums = vDSP.subtract(profile.prefixSums[n..<(n + positions)], profile.prefixSums[0.. best!.score { - best = (ClipChoice(videoID: profile.videoID, start: start), score) + // 2・3. 拍と衝撃の一致、カットの頭の一致。 + if hitSync.weight > 0, let music, music.hasHitInformation, profile.impacts.count == profile.values.count { + let key = Int((hop * 1_000_000).rounded()) + let pulses: [Double] + if let cached = pulseCache[key] { + pulses = cached + } else { + pulses = music.pulses(hop: hop, count: n) + pulseCache[key] = pulses + } + let pulseNorm = vDSP.sum(vDSP.multiply(pulses, pulses)).squareRoot() + if pulseNorm > 1e-9 { + // 時刻をそろえた類似度: Σ 曲の山 × 映像の衝撃 / (|曲の山| × |映像の衝撃|)。 + let numerator = Self.correlate(profile.impacts, kernel: pulses, positions: positions) + let energy = vDSP.subtract(profile.impactSquarePrefix[n..<(n + positions)], profile.impactSquarePrefix[0..= 2, positions + 1 <= profile.impacts.count { + startHit = vDSP.maximum(profile.impacts[0..) -> Range? { + let first = Int(((range.lowerBound - length - profile.offset) / hop + 1e-9).rounded(.down)) + 1 + let last = Int(((range.upperBound - profile.offset) / hop - 1e-9).rounded(.up)) - 1 + let lower = max(0, first) + let upper = min(positions - 1, last) + return lower <= upper ? lower..<(upper + 1) : nil + } + for range in usedRanges { + if let indices = overlappingIndices(range) { + for index in indices { scores[index] -= overlapPenalty } + } + } + if let forbidden, let indices = overlappingIndices(forbidden) { + for index in indices { scores[index] = -1e9 } + } + + var bestIndex: vDSP_Length = 0 + var bestScore = 0.0 + vDSP_maxviD(scores, 1, &bestScore, &bestIndex, vDSP_Length(positions)) + guard bestScore > -1e8 else { return nil } + return (bestScore, profile.offset + Double(bestIndex) * hop) + } + + /// `signal` の各位置 i から長さ `kernel.count` の窓と `kernel` の内積(相互相関)を、`positions` 個の i について求める。 + static func correlate(_ signal: [Double], kernel: [Double], positions: Int) -> [Double] { + guard positions > 0, !kernel.isEmpty, signal.count >= positions + kernel.count - 1 else { + return [Double](repeating: 0, count: max(0, positions)) + } + var result = [Double](repeating: 0, count: positions) + signal.withUnsafeBufferPointer { signalBuffer in + kernel.withUnsafeBufferPointer { kernelBuffer in + vDSP_convD( + signalBuffer.baseAddress!, 1, + kernelBuffer.baseAddress!, 1, + &result, 1, + vDSP_Length(positions), + vDSP_Length(kernel.count) + ) + } + } + return result } // MARK: - カット単位の差し替え @@ -279,9 +461,15 @@ nonisolated struct CutPlanner: Sendable { length: original.duration, analysis: analysis ) + let signal = MusicCutSignal( + analysis: analysis, + start: original.timelineStart, + length: original.duration, + accentAtStart: accentAtCutStart(of: original, analysis: analysis) + ) // カットの番号ごとに乱数を変える(同じ種でも、別のカットは別の選び方になる)。 - var generator = SeededGenerator(seed: seed &+ UInt64(index) &* 0x9E37_79B9_7F4A_7C15) + let noise = NoiseSource(seed: seed &+ UInt64(index) &* 0x9E37_79B9_7F4A_7C15) guard let choice = pickClip( length: original.duration, target: target, @@ -290,7 +478,9 @@ nonisolated struct CutPlanner: Sendable { usage: usage, usedRanges: usedRanges, forbidden: (original.videoID, original.sourceStart..<(original.sourceStart + original.duration)), - generator: &generator + music: signal, + noise: noise, + cutKey: UInt64(index) ) else { throw CutPlannerError.noClipLongEnough } @@ -306,6 +496,17 @@ nonisolated struct CutPlanner: Sendable { return CutPlan(cuts: cuts, duration: plan.duration) } + /// 既にあるカットの頭にあたる拍の強さ。頭に近い拍(30ms以内)が無ければ 0.5。 + private func accentAtCutStart(of cut: PlannedCut, analysis: MusicAnalysis) -> Double { + if analysis.sectionBoundaries.contains(where: { abs($0 - cut.timelineStart) < 0.03 }) { return 1 } + guard let beatIndex = analysis.beats.indices.min(by: { + abs(analysis.beats[$0] - cut.timelineStart) < abs(analysis.beats[$1] - cut.timelineStart) + }), abs(analysis.beats[beatIndex] - cut.timelineStart) < 0.03 else { return 0.5 } + var accent = analysis.accent(atBeat: beatIndex) + if analysis.isDownbeat(beatIndex: beatIndex) == true { accent = max(accent, 0.8) } + return accent + } + /// `videoID` の動画を使っているカットを、すべて別の動画に選び直す。 func replaceAllCuts( usingVideo videoID: UUID, @@ -329,3 +530,69 @@ nonisolated struct CutPlanner: Sendable { return result } } + +// MARK: - 曲のカット1つぶんの信号 + +/// 1つのカットの間(開始 `start` から `length` 秒)の、曲の音の立ち上がり。 +nonisolated struct MusicCutSignal: Sendable { + let analysis: MusicAnalysis + let start: Double + let length: Double + /// カットの頭の拍の強さ(0〜1)。 + let accentAtStart: Double + + /// 音の立ち上がりの情報があるか。無い(簡易な解析)ときは、拍と衝撃の一致は使えない。 + var hasHitInformation: Bool { !analysis.onsetEnvelope.isEmpty && analysis.onsetHop > 0 } + + /// 曲の構造の境目(サビ・ドロップ)の頭にあたるカットか。 + var isSectionStart: Bool { analysis.sectionBoundaries.contains { abs($0 - start) < 0.03 } } + + /// カットの間の音の立ち上がりの最大(0〜1)。大きい音があるカットほど、映像の衝撃を重ねる価値が大きい。 + var strength: Double { + guard hasHitInformation else { return 0 } + let first = max(0, Int((start / analysis.onsetHop).rounded(.down))) + let last = min(analysis.onsetEnvelope.count - 1, Int(((start + length) / analysis.onsetHop).rounded(.up))) + guard first <= last else { return 0 } + return min(1, analysis.onsetEnvelope[first...last].max() ?? 0) + } + + /// 映像の標本間隔 `hop` 秒ごとの、音の立ち上がりの強さ(`count` 個)。前後に少しにじませる。 + func pulses(hop: Double, count: Int) -> [Double] { + guard hasHitInformation, hop > 0, count > 0 else { return [Double](repeating: 0, count: max(0, count)) } + var peaks = [Double](repeating: 0, count: count) + for bucket in 0.. 0 ? peaks[index - 1] : 0 + let next = index + 1 < peaks.count ? peaks[index + 1] : 0 + return 0.5 * peaks[index] + 0.25 * (previous + next) + } + } +} + +// MARK: - 揺らぎ(同じ種なら同じ結果) + +/// 素材選びの同点を崩すための、種から作る擬似乱数の列。 +/// 候補の数だけ乱数を作ると重いので、一度だけ作った列を、カットごとに違う位置から読む。 +nonisolated struct NoiseSource: Sendable { + private let values: [Double] + + init(seed: UInt64) { + var generator = SeededGenerator(seed: seed) + values = (0..<8_192).map { _ in Double.random(in: 0..<1, using: &generator) } + } + + /// `key` ごとに違う位置から読んだ、0〜1 の値 `count` 個。 + func slice(count: Int, key: UInt64) -> [Double] { + guard count > 0 else { return [] } + let start = Int(truncatingIfNeeded: (key &* 0x9E37_79B9_7F4A_7C15) >> 40) % values.count + if start + count <= values.count { return Array(values[start..<(start + count)]) } + return (0.. MusicAnalysis { + let beats = stride(from: 0.5, to: duration - 0.1, by: 0.5).map { $0 } + var analysis = MusicAnalysis( + duration: duration, tempo: 120, beats: beats, + energy: [Double](repeating: energy, count: Int(duration * 10)), + intensity: [MusicIntensity](repeating: intensity, count: Int(duration * 10)), + energyHop: 0.1 + ) + analysis.beatAccents = beats.indices.map { $0 % 4 == 0 ? 1.0 : ($0 % 2 == 0 ? 0.65 : 0.3) } + analysis.downbeatPhase = 0 + var envelope = [Double](repeating: 0, count: Int(duration / 0.05) + 2) + for (index, time) in beats.enumerated() { + envelope[Int((time / 0.05).rounded())] = analysis.beatAccents[index] + } + analysis.onsetEnvelope = envelope + analysis.onsetHop = 0.05 + return analysis + } + + /// 動きの強さは一定(0.5)で、0.5秒ごとに「衝撃」が起きる素材。衝撃の位相(最初の衝撃の時刻)だけが違う。 + /// 動きの強さでは区別できないので、選び方の差は、衝撃を拍に重ねたかどうかだけで決まる。 + private func periodicImpactProfile( + _ id: UUID = UUID(), + phase: Double, + period: Double = 0.5, + duration: Double = 60, + motion: Double = 0.5, + spread: Bool = true + ) -> SourceMotionProfile { + let hop = Self.videoHop + let count = Int(duration / hop) + var impacts = [Double](repeating: 0, count: count) + var time = phase + while time < duration - hop { + let index = Int((time / hop).rounded()) + if index < count { impacts[index] = 1 } + if spread { + if index > 0 { impacts[index - 1] = max(impacts[index - 1], 0.5) } + if index + 1 < count { impacts[index + 1] = max(impacts[index + 1], 0.5) } + } + time += period + } + return SourceMotionProfile( + videoID: id, duration: duration, hop: hop, + values: [Double](repeating: motion, count: count), impacts: impacts + ) + } + + /// 位相を 1/12 秒ずつずらした6本。 + private func phasedPool() -> [SourceMotionProfile] { + (0..<6).map { periodicImpactProfile(phase: Double($0) * Self.videoHop) } + } + + /// 衝撃が1秒に1回・1標本だけの、まばらな素材。位相を 1/6 秒ずつずらした6本。 + /// 衝撃の間が空いているので、位置が偶然に決まると、強い拍に衝撃が重なる確率は2割ほどしかない(合わせ込みの差が出やすい)。 + private func sparsePhasedPool() -> [SourceMotionProfile] { + (0..<6).map { periodicImpactProfile(phase: Double($0) * 2 * Self.videoHop, period: 1.0, spread: false) } + } + + private func planner(hitSync: HitSync, motion: MotionMatching = .standard, style: MusicVideoCutStyle = .standard) -> CutPlanner { + var tuning = MusicVideoCutTuning() + tuning.hitSync = hitSync + tuning.motionMatching = motion + return CutPlanner(style: style, tuning: tuning) + } + + private func averageHitAlignment( + _ planner: CutPlanner, + analysis: MusicAnalysis, + pool: [SourceMotionProfile], + seeds: ClosedRange = 1...4 + ) throws -> Double { + var total = 0.0 + for seed in seeds { + let plan = try planner.plan(analysis: analysis, pool: pool, seed: seed) + let metrics = MusicVideoSyncMetrics(plan: plan, analysis: analysis, pool: pool) + total += try #require(metrics.hitAlignment, "seed \(seed)") + } + return total / Double(seeds.count) + } + + // MARK: 拍と衝撃の一致 + + @Test + func hitSyncPutsTheVideoImpactsOnTheStrongBeats() throws { + let analysis = syntheticAnalysis() + let pool = sparsePhasedPool() + + let off = try averageHitAlignment(planner(hitSync: .off), analysis: analysis, pool: pool) + let standard = try averageHitAlignment(planner(hitSync: .standard), analysis: analysis, pool: pool) + let strong = try averageHitAlignment(planner(hitSync: .strong), analysis: analysis, pool: pool) + print("INFO hitAlignment off=\(off) standard=\(standard) strong=\(strong)") + + // 合わせない場合は、衝撃の位置が偶然に決まる(強い拍に重なるのは2割ほど)。 + #expect(off < 0.5, "合わせない \(off)") + // 合わせると、ほぼすべての強い拍に、衝撃が重なる。 + #expect(standard >= 0.9, "標準 \(standard)") + #expect(strong >= 0.9, "強い \(strong)") + #expect(strong > off + 0.4, "強い \(strong) 合わせない \(off)") + } + + @Test + func theImpactsLandOnTheCutStartsToo() throws { + // カットは拍の上で切り替わる。その瞬間(頭)に、映像の衝撃が来ているか。 + let analysis = syntheticAnalysis() + let pool = phasedPool() + let plan = try planner(hitSync: .strong).plan(analysis: analysis, pool: pool, seed: 3) + + var aligned = 0 + var counted = 0 + for cut in plan.cuts.dropFirst() where cut.timelineStart > 1 { + guard let profile = pool.first(where: { $0.videoID == cut.videoID }) else { continue } + let index = Int((cut.sourceStart / profile.hop).rounded()) + let nearStart = (max(0, index - 1)...min(profile.impacts.count - 1, index + 1)).map { profile.impacts[$0] }.max() ?? 0 + counted += 1 + if nearStart >= 0.99 { aligned += 1 } + } + #expect(counted >= 20) + #expect(Double(aligned) / Double(counted) >= 0.9, "頭に衝撃が来たカット \(aligned)/\(counted)") + } + + @Test + func hitSyncDoesNotOverrideAClearMotionLevelMismatch() throws { + // 動きの強さが大きく違う素材(0.05)に、拍の合った衝撃があっても、盛り上がり(0.9)の曲には、動きの大きな素材(0.9)を選ぶ。 + let analysis = syntheticAnalysis(intensity: .intense, energy: 0.9) + let quietAligned = (0..<3).map { _ in periodicImpactProfile(phase: 0, motion: 0.05) } + let busyOffbeat = (0..<3).map { _ in periodicImpactProfile(phase: 0.25, motion: 0.9) } + let pool = quietAligned + busyOffbeat + let busyIDs = Set(busyOffbeat.map(\.videoID)) + + let plan = try planner(hitSync: .standard, motion: .strong).plan(analysis: analysis, pool: pool, seed: 1) + let busyCuts = plan.cuts.filter { busyIDs.contains($0.videoID) }.count + #expect(Double(busyCuts) / Double(plan.cuts.count) >= 0.9, "動きの大きい素材のカット \(busyCuts)/\(plan.cuts.count)") + } + + @Test + func withoutOnsetInformationThePlannerFallsBackToTheMotionLevel() throws { + // 簡易な解析(onset の細かい情報なし)では、拍と衝撃の一致は使わず、動きの強さだけで選ぶ(以前と同じ動作)。 + var analysis = syntheticAnalysis(intensity: .intense, energy: 0.9) + analysis.onsetEnvelope = [] + let calm = (0..<3).map { _ in periodicImpactProfile(phase: 0, motion: 0.1) } + let busy = (0..<3).map { _ in periodicImpactProfile(phase: 0.25, motion: 0.9) } + let busyIDs = Set(busy.map(\.videoID)) + + let plan = try planner(hitSync: .strong, motion: .strong).plan(analysis: analysis, pool: calm + busy, seed: 2) + let busyCuts = plan.cuts.filter { busyIDs.contains($0.videoID) }.count + #expect(Double(busyCuts) / Double(plan.cuts.count) >= 0.95) + } + + @Test + func hitSyncKeepsThePlanDeterministicPerSeedButVariedAcrossSeeds() throws { + let analysis = syntheticAnalysis() + let pool = phasedPool() + let strong = planner(hitSync: .strong) + let first = try strong.plan(analysis: analysis, pool: pool, seed: 7) + let again = try strong.plan(analysis: analysis, pool: pool, seed: 7) + let other = try strong.plan(analysis: analysis, pool: pool, seed: 8) + #expect(first == again) + #expect(first != other) // 同点の候補が多いので、種が違えば、別のカット割りになる + } + + @Test + func replacingACutKeepsTheImpactAlignment() throws { + let analysis = syntheticAnalysis() + let pool = phasedPool() + let strong = planner(hitSync: .strong) + let plan = try strong.plan(analysis: analysis, pool: pool, seed: 5) + + var current = plan + for index in [3, 7, 11, 15] { + current = try strong.replaceCut(at: index, in: current, analysis: analysis, pool: pool, seed: 21) + } + let metrics = MusicVideoSyncMetrics(plan: current, analysis: analysis, pool: pool) + #expect((metrics.hitAlignment ?? 0) >= 0.9) + // 差し替えても、カットの枠は同じ。 + #expect(current.cuts.map(\.timelineStart) == plan.cuts.map(\.timelineStart)) + } + + // MARK: 動きの強さの相関 + + @Test + func motionLevelMatchingFollowsTheMusicEnergy() throws { + // 前半は静か(0.1)、後半は盛り上がり(0.9)の曲。素材は動きの少ないものと大きいものが半々。 + var analysis = syntheticAnalysis(duration: 40) + analysis.energy = (0..<400).map { $0 < 200 ? 0.1 : 0.9 } + analysis.intensity = (0..<400).map { $0 < 200 ? .calm : .intense } + let calmVideos = (0..<4).map { _ in periodicImpactProfile(phase: 0, motion: 0.1) } + let busyVideos = (0..<4).map { _ in periodicImpactProfile(phase: 0, motion: 0.9) } + let pool = calmVideos + busyVideos + + func correlation(_ planner: CutPlanner) throws -> Double { + var total = 0.0 + for seed in 1...3 as ClosedRange { + let plan = try planner.plan(analysis: analysis, pool: pool, seed: seed) + total += try #require(MusicVideoSyncMetrics(plan: plan, analysis: analysis, pool: pool).energyCorrelation) + } + return total / 3 + } + let strong = try correlation(planner(hitSync: .off, motion: .strong)) + let off = try correlation(planner(hitSync: .off, motion: .off)) + #expect(strong >= 0.9, "動きを強く合わせる \(strong)") + #expect(strong > off + 0.3, "強く合わせる \(strong) 合わせない \(off)") + } + + // MARK: 曲の構造・小節の頭に合わせたカットの位置 + + @Test + func cutsBreakAtTheSectionBoundariesOfTheSong() throws { + // 控えめ(静かな所は8拍=4秒)のとき、4秒の格子に載らない 11 秒と 22 秒に、曲の構造の境目がある。 + var withSections = syntheticAnalysis(duration: 40, intensity: .calm, energy: 0.1) + withSections.sectionBoundaries = [11, 22] + var without = withSections + without.sectionBoundaries = [] + let pool = phasedPool() + let relaxed = planner(hitSync: .off, style: .relaxed) + + func starts(_ analysis: MusicAnalysis) throws -> [Double] { + try relaxed.plan(analysis: analysis, pool: pool, seed: 1).cuts.map(\.timelineStart) + } + let withStarts = try starts(withSections) + let withoutStarts = try starts(without) + #expect(withStarts.contains { abs($0 - 11) < 1e-9 }, "境目 11 秒でカットが替わる \(withStarts.prefix(8))") + #expect(withStarts.contains { abs($0 - 22) < 1e-9 }, "境目 22 秒でカットが替わる") + #expect(!withoutStarts.contains { abs($0 - 11) < 1e-9 }, "境目が無ければ、11 秒は格子の外") + } + + @Test + func barAlignedCutsFollowTheDetectedBarStart() throws { + // 静かな所は4拍(=1小節)ごと。小節の頭が拍の添字 0 のとき、2 のときで、カットの位置が変わる。 + func startsOnBeat(phase: Int) throws -> [Int] { + var analysis = syntheticAnalysis(duration: 40, intensity: .calm, energy: 0.1) + analysis.downbeatPhase = phase + let plan = try planner(hitSync: .off).plan(analysis: analysis, pool: phasedPool(), seed: 1) + // 最初の導入部のカットを除き、各カットの頭の拍の添字(拍は 0.5 秒ごと、添字 0 が 0.5 秒)。 + return plan.cuts.dropFirst().map { Int(($0.timelineStart / 0.5).rounded()) - 1 } + } + let zero = try startsOnBeat(phase: 0) + let two = try startsOnBeat(phase: 2) + + #expect(zero.dropFirst().allSatisfy { $0 % 4 == 0 }, "小節の頭が 0: \(zero.prefix(6))") + #expect(two.dropFirst().allSatisfy { $0 % 4 == 2 }, "小節の頭が 2: \(two.prefix(6))") + #expect(zero != two) + } + + // MARK: 部品 + + @Test + func correlationMatchesANaiveCalculation() { + var generator = SeededGenerator(seed: 4) + let signal = (0..<120).map { _ in Double.random(in: 0..<1, using: &generator) } + let kernel = (0..<9).map { _ in Double.random(in: 0..<1, using: &generator) } + let positions = signal.count - kernel.count + 1 + + let fast = CutPlanner.correlate(signal, kernel: kernel, positions: positions) + #expect(fast.count == positions) + for index in 0.. 0.4 }) // 急に動く素材には、はっきり出る + #expect(busyProfile.impacts.allSatisfy { $0 >= 0 && $0 <= 1 }) + } + + @Test + func profilesWithoutImpactsStillDecodeAndMismatchedImpactsAreIgnored() throws { + let id = UUID() + let legacy = #"{"videoID":"\#(id.uuidString)","offset":3,"duration":10,"hop":0.25,"values":[0.1,0.2,0.3]}"# + let decoded = try JSONDecoder().decode(SourceMotionProfile.self, from: Data(legacy.utf8)) + #expect(decoded.values == [0.1, 0.2, 0.3]) + #expect(decoded.impacts.isEmpty) + + // 長さが合わない衝撃は、位置がずれるので使わない。 + let mismatched = SourceMotionProfile(videoID: id, duration: 1, hop: 0.25, values: [0, 0, 0, 0], impacts: [1, 0]) + #expect(mismatched.impacts.isEmpty) + + // 保存→読み込みで、衝撃も残る。 + let original = SourceMotionProfile(videoID: id, duration: 1, hop: 0.25, values: [0, 0.5, 0, 0], impacts: [0, 1, 0, 0]) + let restored = try JSONDecoder().decode(SourceMotionProfile.self, from: JSONEncoder().encode(original)) + #expect(restored == original) + } + + @Test + func syncMetricsFollowTheFootageOntoTheTimeline() { + // 素材 A の 10 秒目に、衝撃が1つ。カットは、曲の 2 秒から 4 秒に、素材の 9 秒から 11 秒を置く。 + // 曲の 3 秒(強い拍)に映る素材の時刻は 10 秒で、衝撃と一致する。曲の 2 秒(強い拍)に映るのは 9 秒で、衝撃は無い。 + let id = UUID() + let hop = 0.25 + var impacts = [Double](repeating: 0, count: 80) + impacts[40] = 1 // 10 秒 + let profile = SourceMotionProfile(videoID: id, duration: 20, hop: hop, values: [Double](repeating: 0.5, count: 80), impacts: impacts) + let plan = CutPlan( + cuts: [PlannedCut(videoID: id, sourceStart: 9, duration: 2, timelineStart: 2, intensity: .medium)], + duration: 4 + ) + var analysis = MusicAnalysis( + duration: 4, tempo: 60, beats: [2.0, 3.0], energy: [0.5], intensity: [.medium], energyHop: 4 + ) + analysis.beatAccents = [1.0, 1.0] + + let metrics = MusicVideoSyncMetrics(plan: plan, analysis: analysis, pool: [profile]) + #expect(metrics.strongBeatCount == 2) + #expect(metrics.hitAlignment == 0.5) // 2つの強い拍のうち、1つだけ衝撃が重なる + + // 弱い拍は数えない。 + analysis.beatAccents = [0.2, 1.0] + let weakFirst = MusicVideoSyncMetrics(plan: plan, analysis: analysis, pool: [profile]) + #expect(weakFirst.strongBeatCount == 1) + #expect(weakFirst.hitAlignment == 1.0) + + // 衝撃の情報が無い素材では、調べられない(nil)。 + let blind = SourceMotionProfile(videoID: id, duration: 20, hop: hop, values: [Double](repeating: 0.5, count: 80)) + #expect(MusicVideoSyncMetrics(plan: plan, analysis: analysis, pool: [blind]).hitAlignment == nil) + } + + @Test + func pearsonCorrelationHandlesTheEdgeCases() { + let x = (0..<20).map(Double.init) + #expect(abs((MusicVideoSyncMetrics.pearson(x, x) ?? 0) - 1) < 1e-9) + #expect(abs((MusicVideoSyncMetrics.pearson(x, x.map { -$0 }) ?? 0) + 1) < 1e-9) + #expect(MusicVideoSyncMetrics.pearson(x, [Double](repeating: 1, count: 20)) == nil) // 一定 + #expect(MusicVideoSyncMetrics.pearson([1, 2, 3], [1, 2, 3]) == nil) // 標本が少ない + } + + @Test + func oldCutTuningWithoutHitSyncDecodesWithTheDefault() throws { + let legacy = #"{"minimumCutDuration":1,"motionMatching":"strong","variety":"wide","alignment":"free"}"# + let decoded = try JSONDecoder().decode(MusicVideoCutTuning.self, from: Data(legacy.utf8)) + #expect(decoded.minimumCutDuration == 1) + #expect(decoded.motionMatching == .strong) + #expect(decoded.variety == .wide) + #expect(decoded.alignment == .free) + #expect(decoded.hitSync == .strong) // 無い項目は既定値(いちばん強く合わせる) + #expect(decoded.maximumCutDuration == nil) + } + + // MARK: 速さ + + @Test + func planningAFullSongFromAHugePoolStaysFast() throws { + // 4分13秒・129BPM、素材は 66 本 × 6 窓(15 秒、1秒に12回)。拍ごとに素材のすべての位置を採点しても、数秒で終わる。 + let duration = 253.0 + let interval = 60.0 / 129 + let beats = stride(from: interval, to: duration - 0.1, by: interval).map { $0 } + var analysis = MusicAnalysis( + duration: duration, tempo: 129, beats: beats, + energy: (0..<2530).map { 0.5 + 0.4 * sin(Double($0) / 80) }, + intensity: [MusicIntensity](repeating: .medium, count: 2530), energyHop: 0.1 + ) + analysis.beatAccents = beats.indices.map { $0 % 4 == 0 ? 1.0 : 0.4 } + var envelope = [Double](repeating: 0, count: Int(duration / 0.05) + 2) + for (index, time) in beats.enumerated() { envelope[Int((time / 0.05).rounded())] = analysis.beatAccents[index] } + analysis.onsetEnvelope = envelope + + var generator = SeededGenerator(seed: 11) + let hop = Self.videoHop + let pool: [SourceMotionProfile] = (0..<(66 * 6)).map { index in + let count = Int(15 / hop) + let values = (0.. 0.9 ? 1.0 : 0.0 } + return SourceMotionProfile(videoID: UUID(), offset: Double(index % 6) * 20, duration: 15, hop: hop, values: values, impacts: impacts) + } + + let started = Date() + let plan = try planner(hitSync: .strong, motion: .strong, style: .energetic).plan(analysis: analysis, pool: pool, seed: 1) + let elapsed = Date().timeIntervalSince(started) + + #expect(plan.cuts.count > 100) + #expect(elapsed < 30, "かかった時間 \(elapsed) 秒(カット \(plan.cuts.count))") + print("INFO planning time \(String(format: "%.2f", elapsed)) s for \(plan.cuts.count) cuts from \(pool.count) windows") + } +} diff --git a/ArkServerTests/MusicVideoTuningTests.swift b/ArkServerTests/MusicVideoTuningTests.swift index 7bb71d3..64e6f65 100644 --- a/ArkServerTests/MusicVideoTuningTests.swift +++ b/ArkServerTests/MusicVideoTuningTests.swift @@ -346,6 +346,28 @@ struct MusicVideoPlanStatsTests { ) #expect(same.text.contains("大きな違いはありません")) } + + @Test + func changeSummaryReportsTheBeatAlignment() { + func stats(hit: Double?) -> MusicVideoPlanStats { + var result = MusicVideoPlanStats( + plan: CutPlan(cuts: [plannedCut(UUID(), from: 0, at: 0, length: 1)], duration: 1), + pool: [], + analysis: nil + ) + result.hitAlignment = hit + return result + } + + let improved = MusicVideoChangeSummary(title: "拍への合わせ込み", before: stats(hit: 0.44), after: stats(hit: 1.0)) + #expect(improved.text == "「拍への合わせ込み」を変えました:拍の一致 44% → 100%") + + // 片方でも調べられなければ、比べない。小さな差も出さない。 + let unknown = MusicVideoChangeSummary(title: "拍への合わせ込み", before: stats(hit: nil), after: stats(hit: 1.0)) + #expect(unknown.text.contains("大きな違いはありません")) + let tiny = MusicVideoChangeSummary(title: "拍への合わせ込み", before: stats(hit: 0.800), after: stats(hit: 0.805)) + #expect(tiny.text.contains("大きな違いはありません")) + } } // MARK: - 保存