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
75 changes: 71 additions & 4 deletions ArkServer/Features/MusicVideo/Models/MusicVideoModels.swift
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,40 @@ nonisolated struct MusicAnalysis: Codable, Equatable, Sendable {
/// `energy` / `intensity` の標本間隔(秒)。
var energyHop: Double

// 以下は、動きを曲に細かく合わせるための解析結果。解析していない(古いデータ・テスト用の簡易な解析)ときは、
// 空か nil のままにして、使う側は「情報なし」として扱う。

/// 拍ごとの強さ(0〜1)。`beats` と同じ並び。
var beatAccents: [Double] = []
/// 1小節の拍の数(3 か 4)。
var beatsPerBar: Int = 4
/// 小節の1拍目にあたる拍の、`beats` の添字を `beatsPerBar` で割った余り。分からなければ nil。
var downbeatPhase: Int?
/// 音の立ち上がり(onset)の細かい強さ(0〜1)。`onsetHop` 秒ごと。拍より細かい位置の合わせ込みに使う。
var onsetEnvelope: [Double] = []
/// `onsetEnvelope` の標本間隔(秒)。
var onsetHop: Double = 0.05
/// 曲の構造が変わる時刻(秒、昇順)。サビやドロップの頭。
var sectionBoundaries: [Double] = []

/// `index` 番目の拍の強さ。情報が無ければ中間の 0.5。
func accent(atBeat index: Int) -> Double {
beatAccents.indices.contains(index) ? beatAccents[index] : 0.5
}

/// `index` 番目の拍が、小節の1拍目か。小節の頭が分からないときは nil。
func isDownbeat(beatIndex index: Int) -> Bool? {
guard let downbeatPhase, beatsPerBar > 0 else { return nil }
return ((index - downbeatPhase) % beatsPerBar + beatsPerBar) % beatsPerBar == 0
}

/// `time` 秒を含む区間の onset の強さ。情報が無ければ 0。
func onset(at time: Double) -> Double {
guard !onsetEnvelope.isEmpty, onsetHop > 0 else { return 0 }
let index = Int((time / onsetHop).rounded(.down))
return onsetEnvelope.indices.contains(index) ? onsetEnvelope[index] : 0
}

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)
Expand All @@ -176,20 +210,29 @@ nonisolated struct SourceMotionProfile: Codable, Equatable, Sendable {
let hop: Double
/// 動きの大きさ(0〜1)。
let values: [Double]
/// 「急に動いた瞬間」の強さ(0〜1)。`values` と同じ間隔。動きが急に増えた所(動作の始まり・衝撃・画面の切り替わり)が高い。
/// 曲の大きな音(拍・アクセント)に、映像の大きな動きを重ねるために使う。調べていないときは空。
let impacts: [Double]
/// 区間の平均を O(1) で求めるための累積和。保存はせず、読み込み時に作り直す。
private let prefixSums: [Double]
let prefixSums: [Double]
/// `impacts` の2乗の累積和。位置ごとの類似度の分母を O(1) で求めるために使う。保存はしない。
let impactSquarePrefix: [Double]

init(videoID: UUID, offset: Double = 0, duration: Double, hop: Double, values: [Double]) {
init(videoID: UUID, offset: Double = 0, duration: Double, hop: Double, values: [Double], impacts: [Double] = []) {
self.videoID = videoID
self.offset = offset
self.duration = duration
self.hop = hop
self.values = values
// 長さが合わない衝撃の列は、使わない(位置がずれるより、情報なしにする)。
let aligned = impacts.count == values.count ? impacts : []
self.impacts = aligned
self.prefixSums = Self.makePrefixSums(values)
self.impactSquarePrefix = Self.makePrefixSums(aligned.map { $0 * $0 })
}

private enum CodingKeys: String, CodingKey {
case videoID, offset, duration, hop, values
case videoID, offset, duration, hop, values, impacts
}

init(from decoder: Decoder) throws {
Expand All @@ -199,7 +242,8 @@ nonisolated struct SourceMotionProfile: Codable, Equatable, Sendable {
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)
let impacts = try container.decodeIfPresent([Double].self, forKey: .impacts) ?? []
self.init(videoID: videoID, offset: offset, duration: duration, hop: hop, values: values, impacts: impacts)
}

private static func makePrefixSums(_ values: [Double]) -> [Double] {
Expand Down Expand Up @@ -292,3 +336,26 @@ nonisolated struct SeededGenerator: RandomNumberGenerator, Sendable {
return z ^ (z >> 31)
}
}

extension MusicAnalysis {
private enum CodingKeys: String, CodingKey {
case duration, tempo, beats, energy, intensity, energyHop
case beatAccents, beatsPerBar, downbeatPhase, onsetEnvelope, onsetHop, sectionBoundaries
}

init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
duration = try container.decode(Double.self, forKey: .duration)
tempo = try container.decode(Double.self, forKey: .tempo)
beats = try container.decode([Double].self, forKey: .beats)
energy = try container.decode([Double].self, forKey: .energy)
intensity = try container.decode([MusicIntensity].self, forKey: .intensity)
energyHop = try container.decode(Double.self, forKey: .energyHop)
beatAccents = try container.decodeIfPresent([Double].self, forKey: .beatAccents) ?? []
beatsPerBar = try container.decodeIfPresent(Int.self, forKey: .beatsPerBar) ?? 4
downbeatPhase = try container.decodeIfPresent(Int.self, forKey: .downbeatPhase)
onsetEnvelope = try container.decodeIfPresent([Double].self, forKey: .onsetEnvelope) ?? []
onsetHop = try container.decodeIfPresent(Double.self, forKey: .onsetHop) ?? 0.05
sectionBoundaries = try container.decodeIfPresent([Double].self, forKey: .sectionBoundaries) ?? []
}
}
39 changes: 28 additions & 11 deletions ArkServer/Features/MusicVideo/Models/MusicVideoTuning.swift
Original file line number Diff line number Diff line change
Expand Up @@ -257,10 +257,32 @@ extension MusicAnalysis {
let length = end - start
guard length > 0 else { return self }

let newBeats = beats.filter { $0 >= start && $0 < end }.map { $0 - start }
guard energyHop > 0, !energy.isEmpty else {
return MusicAnalysis(duration: length, tempo: tempo, beats: newBeats, energy: energy, intensity: intensity, energyHop: energyHop)
// 拍: 範囲に入るものだけを、0 秒を先頭にずらして残す。強さ・小節の頭も、残した拍に合わせる。
let keptIndices = beats.indices.filter { beats[$0] >= start && beats[$0] < end }
let newBeats = keptIndices.map { beats[$0] - start }
let firstKept = keptIndices.first ?? 0
var result = MusicAnalysis(duration: length, tempo: tempo, beats: newBeats, energy: energy, intensity: intensity, energyHop: energyHop)
result.beatsPerBar = beatsPerBar
if beatAccents.count == beats.count {
result.beatAccents = keptIndices.map { beatAccents[$0] }
}
if let downbeatPhase, beatsPerBar > 0 {
result.downbeatPhase = ((downbeatPhase - firstKept) % beatsPerBar + beatsPerBar) % beatsPerBar
}
result.sectionBoundaries = sectionBoundaries.filter { $0 > start && $0 < end }.map { $0 - start }

// onset の細かい強さ: 範囲の先頭の位置から切り出す。
if !onsetEnvelope.isEmpty, onsetHop > 0 {
let first = Int((start / onsetHop).rounded(.down))
let count = Int((length / onsetHop).rounded(.up))
result.onsetHop = onsetHop
result.onsetEnvelope = (0..<count).map { offset in
onsetEnvelope.indices.contains(first + offset) ? onsetEnvelope[first + offset] : 0
}
}

// 盛り上がり: 範囲に合わせて切り出す。
guard energyHop > 0, !energy.isEmpty else { return result }
let count = max(1, Int((length / energyHop).rounded(.up)))
var newEnergy: [Double] = []
var newIntensity: [MusicIntensity] = []
Expand All @@ -271,14 +293,9 @@ extension MusicAnalysis {
newEnergy.append(energy(at: sourceTime))
newIntensity.append(intensity(at: sourceTime))
}
return MusicAnalysis(
duration: length,
tempo: tempo,
beats: newBeats,
energy: newEnergy,
intensity: newIntensity,
energyHop: energyHop
)
result.energy = newEnergy
result.intensity = newIntensity
return result
}

/// `time` に最も近い拍の時刻。拍が無ければ `time` のまま。範囲の開始を拍に合わせるときに使う。
Expand Down
44 changes: 41 additions & 3 deletions ArkServer/Features/MusicVideo/Services/BeatAnalyzer.swift
Original file line number Diff line number Diff line change
Expand Up @@ -141,14 +141,32 @@ nonisolated struct BeatAnalyzer: Sendable {
onset: onset,
framesPerSecond: framesPerSecond
)
return MusicAnalysis(
var analysis = MusicAnalysis(
duration: duration,
tempo: tempo,
beats: beats,
energy: energy,
intensity: intensity,
energyHop: energyHop
)

// 映像の動きを曲に細かく合わせるための情報: 拍の強さ・小節の頭・構造の境目・細かい onset。
let structure = MusicStructureAnalyzer.analyze(
onset: onset,
framesPerSecond: framesPerSecond,
onsetOffset: onsetOffset,
beats: beats,
structureFeature: makeStructureFeature(loudness: features.loudness, onset: onset, framesPerSecond: framesPerSecond),
featureHop: energyHop,
duration: duration
)
analysis.beatAccents = structure.beatAccents
analysis.beatsPerBar = structure.beatsPerBar
analysis.downbeatPhase = structure.downbeatPhase
analysis.onsetEnvelope = structure.onsetEnvelope
analysis.onsetHop = structure.onsetHop
analysis.sectionBoundaries = structure.sectionBoundaries
return analysis
}

// MARK: - フレームごとの特徴
Expand Down Expand Up @@ -355,11 +373,12 @@ nonisolated struct BeatAnalyzer: Sendable {

// MARK: - 盛り上がり

private func makeEnergyAndIntensity(
/// 音量と onset を、`energyHop` 秒ごとの平均にまとめる。
private func blockAverages(
loudness: [Double],
onset: [Double],
framesPerSecond: Double
) -> (energy: [Double], intensity: [MusicIntensity]) {
) -> (loud: [Double], onset: [Double]) {
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)
Expand All @@ -373,6 +392,25 @@ nonisolated struct BeatAnalyzer: Sendable {
onsetBlocks[block] = onsetRange.reduce(0) { $0 + onset[$1] } / Double(onsetRange.count)
}
}
return (loudBlocks, onsetBlocks)
}

/// 曲の構造(サビ・ドロップなど)を見るための盛り上がり。`makeEnergyAndIntensity` より短い(0.4秒前後)平滑化にして、
/// 変わり目の位置がぼやけないようにする。
private func makeStructureFeature(loudness: [Double], onset: [Double], framesPerSecond: Double) -> [Double] {
let (loudBlocks, onsetBlocks) = blockAverages(loudness: loudness, onset: onset, framesPerSecond: framesPerSecond)
let radius = max(1, Int(0.4 / energyHop))
let loud = normalizedByPercentiles(movingAverage(loudBlocks, radius: radius))
let rhythmic = normalizedByPercentiles(movingAverage(onsetBlocks, radius: radius))
return normalizedByPercentiles(zip(loud, rhythmic).map { 0.6 * $0 + 0.4 * $1 })
}

private func makeEnergyAndIntensity(
loudness: [Double],
onset: [Double],
framesPerSecond: Double
) -> (energy: [Double], intensity: [MusicIntensity]) {
let (loudBlocks, onsetBlocks) = blockAverages(loudness: loudness, onset: onset, framesPerSecond: framesPerSecond)

// 1.5秒前後で平滑化して、短い揺れで段階が変わらないようにする。
let smoothingRadius = max(1, Int(1.5 / energyHop))
Expand Down
42 changes: 36 additions & 6 deletions ArkServer/Features/MusicVideo/Services/ClipPoolBuilder.swift
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ nonisolated enum ClipPoolError: LocalizedError {
}

/// 解析前の(正規化していない)動きの時系列。キャッシュにはこの形で保存する。
/// 「急に動いた瞬間」(衝撃)は、この動きの列から作れるので、保存しない。
nonisolated struct RawMotionWindow: Codable, Equatable, Sendable {
let offset: Double
let duration: Double
Expand All @@ -39,15 +40,17 @@ nonisolated struct ClipPoolBuilder: Sendable {
/// 1本の動画から調べる窓の最大数。
var maxWindowsPerVideo = 6
/// 動きを調べるときの1秒あたりの標本数。
var analysisFramesPerSecond = 4.0
/// 拍の間隔(120BPMで0.5秒)より十分細かくしないと、拍と動きの山を合わせられない。
/// 動画の読み込み(復号)は、標本数に関わらず全フレームぶん行うので、細かくしても重さはあまり増えない。
var analysisFramesPerSecond = 12.0
/// 同時に解析する動画の数。
var maxConcurrentAnalyses = 3
/// 解析する動画の最大本数。これを超えたらシードで無作為に選ぶ。
var maxVideos = 40
/// キャッシュの保存先。nil ならキャッシュしない。
var cacheDirectory: URL?

private static let cacheVersion = 1
private static let cacheVersion = 2

func build(
sources: [ClipPoolSource],
Expand Down Expand Up @@ -240,24 +243,51 @@ nonisolated struct ClipPoolBuilder: Sendable {
let high = allValues[Int(Double(allValues.count - 1) * 0.95)]
let range = high - low

// 「急に動いた瞬間」も、素材全体で揃えて規格化する(上位1%を1とする)。
let rawImpactsByWindow = analyzed.map { entry in entry.windows.map { Self.rawImpacts(from: $0.values) } }
let allImpacts = rawImpactsByWindow.flatMap { $0.flatMap { $0 } }.sorted()
let impactScale = allImpacts.isEmpty ? 0 : allImpacts[Int(Double(allImpacts.count - 1) * 0.99)]

var profiles: [SourceMotionProfile] = []
for (source, windows) in analyzed {
for window in windows {
for (sourceIndex, entry) in analyzed.enumerated() {
for (windowIndex, window) in entry.windows.enumerated() {
let values: [Double] = window.values.map { value in
guard range > 1e-9 else { return 0.5 }
return min(1, max(0, (value - low) / range))
}
let impacts: [Double] = rawImpactsByWindow[sourceIndex][windowIndex].map { value in
impactScale > 1e-9 ? min(1, value / impactScale) : 0
}
profiles.append(
SourceMotionProfile(
videoID: source.videoID,
videoID: entry.source.videoID,
offset: window.offset,
duration: window.duration,
hop: window.hop,
values: values
values: values,
impacts: impacts
)
)
}
}
return profiles
}

/// 動きの列から、「急に動いた瞬間」の強さ(規格化前)を求める。
/// その位置の動きが、直前の3つの平均より増えた分(増えなければ 0)。増えた位置が分かるよう、
/// 前後に少しにじませる(隣の標本に半分ずつ)。
static func rawImpacts(from values: [Double]) -> [Double] {
guard !values.isEmpty else { return [] }
var rises = [Double](repeating: 0, count: values.count)
for index in 1..<max(1, values.count) {
let lower = max(0, index - 3)
let baseline = values[lower..<index].reduce(0, +) / Double(index - lower)
rises[index] = max(0, values[index] - baseline)
}
return rises.indices.map { index in
let previous = index > 0 ? rises[index - 1] : 0
let next = index + 1 < rises.count ? rises[index + 1] : 0
return 0.5 * rises[index] + 0.25 * (previous + next)
}
}
}
Loading