Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions ArkServer/Features/MusicVideo/Models/MusicVideoPlanStats.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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 から引いた値。
Expand Down Expand Up @@ -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: "・")
}
Expand Down
84 changes: 84 additions & 0 deletions ArkServer/Features/MusicVideo/Models/MusicVideoSyncMetrics.swift
Original file line number Diff line number Diff line change
@@ -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()
}
}
52 changes: 52 additions & 0 deletions ArkServer/Features/MusicVideo/Models/MusicVideoTuning.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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

Expand All @@ -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 {
/// 画面いっぱいに敷き詰める(はみ出す部分は切り落とす)。
Expand Down
Loading