diff --git a/ArkServer/Features/MusicVideo/Models/MusicVideoModels.swift b/ArkServer/Features/MusicVideo/Models/MusicVideoModels.swift index 4a6f1f7..c351f27 100644 --- a/ArkServer/Features/MusicVideo/Models/MusicVideoModels.swift +++ b/ArkServer/Features/MusicVideo/Models/MusicVideoModels.swift @@ -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) @@ -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 { @@ -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] { @@ -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) ?? [] + } +} diff --git a/ArkServer/Features/MusicVideo/Models/MusicVideoTuning.swift b/ArkServer/Features/MusicVideo/Models/MusicVideoTuning.swift index 2cfbf57..cab2dd0 100644 --- a/ArkServer/Features/MusicVideo/Models/MusicVideoTuning.swift +++ b/ArkServer/Features/MusicVideo/Models/MusicVideoTuning.swift @@ -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.. 0, !energy.isEmpty else { return result } let count = max(1, Int((length / energyHop).rounded(.up))) var newEnergy: [Double] = [] var newIntensity: [MusicIntensity] = [] @@ -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` のまま。範囲の開始を拍に合わせるときに使う。 diff --git a/ArkServer/Features/MusicVideo/Services/BeatAnalyzer.swift b/ArkServer/Features/MusicVideo/Services/BeatAnalyzer.swift index fa5b1ec..b25912a 100644 --- a/ArkServer/Features/MusicVideo/Services/BeatAnalyzer.swift +++ b/ArkServer/Features/MusicVideo/Services/BeatAnalyzer.swift @@ -141,7 +141,7 @@ nonisolated struct BeatAnalyzer: Sendable { onset: onset, framesPerSecond: framesPerSecond ) - return MusicAnalysis( + var analysis = MusicAnalysis( duration: duration, tempo: tempo, beats: beats, @@ -149,6 +149,24 @@ nonisolated struct BeatAnalyzer: Sendable { 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: - フレームごとの特徴 @@ -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) @@ -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)) diff --git a/ArkServer/Features/MusicVideo/Services/ClipPoolBuilder.swift b/ArkServer/Features/MusicVideo/Services/ClipPoolBuilder.swift index 720fdd1..3ac3b8c 100644 --- a/ArkServer/Features/MusicVideo/Services/ClipPoolBuilder.swift +++ b/ArkServer/Features/MusicVideo/Services/ClipPoolBuilder.swift @@ -22,6 +22,7 @@ nonisolated enum ClipPoolError: LocalizedError { } /// 解析前の(正規化していない)動きの時系列。キャッシュにはこの形で保存する。 +/// 「急に動いた瞬間」(衝撃)は、この動きの列から作れるので、保存しない。 nonisolated struct RawMotionWindow: Codable, Equatable, Sendable { let offset: Double let duration: Double @@ -39,7 +40,9 @@ nonisolated struct ClipPoolBuilder: Sendable { /// 1本の動画から調べる窓の最大数。 var maxWindowsPerVideo = 6 /// 動きを調べるときの1秒あたりの標本数。 - var analysisFramesPerSecond = 4.0 + /// 拍の間隔(120BPMで0.5秒)より十分細かくしないと、拍と動きの山を合わせられない。 + /// 動画の読み込み(復号)は、標本数に関わらず全フレームぶん行うので、細かくしても重さはあまり増えない。 + var analysisFramesPerSecond = 12.0 /// 同時に解析する動画の数。 var maxConcurrentAnalyses = 3 /// 解析する動画の最大本数。これを超えたらシードで無作為に選ぶ。 @@ -47,7 +50,7 @@ nonisolated struct ClipPoolBuilder: Sendable { /// キャッシュの保存先。nil ならキャッシュしない。 var cacheDirectory: URL? - private static let cacheVersion = 1 + private static let cacheVersion = 2 func build( sources: [ClipPoolSource], @@ -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.. 0 ? rises[index - 1] : 0 + let next = index + 1 < rises.count ? rises[index + 1] : 0 + return 0.5 * rises[index] + 0.25 * (previous + next) + } + } } diff --git a/ArkServer/Features/MusicVideo/Services/MusicStructureAnalyzer.swift b/ArkServer/Features/MusicVideo/Services/MusicStructureAnalyzer.swift new file mode 100644 index 0000000..44125b0 --- /dev/null +++ b/ArkServer/Features/MusicVideo/Services/MusicStructureAnalyzer.swift @@ -0,0 +1,198 @@ +// ArkServer/Features/MusicVideo/Services/MusicStructureAnalyzer.swift + +import Foundation + +/// 曲の拍の「強さ」「小節の頭」「構造の境目」と、細かい音の立ち上がりを求める。 +/// +/// 拍の位置(`BeatAnalyzer` が求める)だけでは、「どの拍で映像を大きく動かすか」が決められない。 +/// 小節の1拍目やサビの頭、拍ごとの強さが分かれば、映像の大きな動きを、曲の大きな音に当てられる。 +/// 配列だけを入出力にした純粋な計算なので、音声ファイルなしでテストできる。 +nonisolated enum MusicStructureAnalyzer { + struct Result: Sendable, Equatable { + var beatAccents: [Double] + var onsetEnvelope: [Double] + var onsetHop: Double + var beatsPerBar: Int + var downbeatPhase: Int? + var sectionBoundaries: [Double] + } + + /// 細かい onset の標本間隔(秒)。 + static let fineHop = 0.05 + + /// - Parameters: + /// - onset: フレームごとの onset の強さ(0 以上)。 + /// - framesPerSecond: `onset` の1秒あたりのフレーム数。 + /// - onsetOffset: フレーム番号 / framesPerSecond に足すと、実際の音の時刻になる秒数。 + /// - beats: 拍の時刻(秒、昇順)。 + /// - structureFeature: 曲の構造を見るための、盛り上がりの連続値(0〜1)。`featureHop` 秒ごと。短めの平滑化まで。 + static func analyze( + onset: [Double], + framesPerSecond: Double, + onsetOffset: Double, + beats: [Double], + structureFeature: [Double], + featureHop: Double, + duration: Double + ) -> Result { + let rawAccents = rawBeatAccents(onset: onset, framesPerSecond: framesPerSecond, onsetOffset: onsetOffset, beats: beats) + let (beatsPerBar, phase) = estimateMeter(rawAccents: rawAccents) + let sections = sectionBoundaries( + feature: structureFeature, + hop: featureHop, + beats: beats, + downbeats: phase.map { downbeatTimes(beats: beats, phase: $0, beatsPerBar: beatsPerBar) }, + duration: duration + ) + return Result( + beatAccents: normalizedAccents(rawAccents), + onsetEnvelope: fineOnsetEnvelope( + onset: onset, framesPerSecond: framesPerSecond, onsetOffset: onsetOffset, hop: fineHop, duration: duration + ), + onsetHop: fineHop, + beatsPerBar: beatsPerBar, + downbeatPhase: phase, + sectionBoundaries: sections + ) + } + + // MARK: - 細かい onset + + /// `hop` 秒ごとの、onset の強さ(その区間の最大値)。上位2%を 1 として規格化する。 + static func fineOnsetEnvelope( + onset: [Double], + framesPerSecond: Double, + onsetOffset: Double, + hop: Double, + duration: Double + ) -> [Double] { + guard !onset.isEmpty, hop > 0, duration > 0 else { return [] } + let blockCount = max(1, Int((duration / hop).rounded(.up))) + var values = [Double](repeating: 0, count: blockCount) + for block in 0.. peak { peak = onset[frame] } + values[block] = peak + } + let sorted = values.sorted() + let high = sorted[Int(Double(sorted.count - 1) * 0.98)] + guard high > 1e-9 else { return values.map { _ in 0 } } + return values.map { min(1, $0 / high) } + } + + // MARK: - 拍の強さ + + /// 拍ごとの、前後 40ms の onset の最大値(規格化していない)。 + static func rawBeatAccents(onset: [Double], framesPerSecond: Double, onsetOffset: Double, beats: [Double]) -> [Double] { + guard !onset.isEmpty else { return beats.map { _ in 0 } } + let radius = max(1, Int((0.04 * framesPerSecond).rounded())) + return beats.map { time in + let center = Int(((time - onsetOffset) * framesPerSecond).rounded()) + let lower = max(0, center - radius) + let upper = min(onset.count - 1, center + radius) + guard lower <= upper else { return 0 } + var peak = 0.0 + for frame in lower...upper where onset[frame] > peak { peak = onset[frame] } + return peak + } + } + + /// 下位10%を0、上位10%を1として規格化する。拍が少なすぎる・強さに差が無いときは、すべて 0.5。 + static func normalizedAccents(_ raw: [Double]) -> [Double] { + guard raw.count >= 4 else { return raw.map { _ in 0.5 } } + let sorted = raw.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 raw.map { _ in 0.5 } } + return raw.map { min(1, max(0, ($0 - low) / (high - low))) } + } + + // MARK: - 小節の頭 + + /// 拍の強さの周期から、拍子(3 か 4)と、小節の1拍目の位置(拍の添字を拍子で割った余り)を推定する。 + /// 周期の山がはっきりしないときは、拍子は 4、位置は nil。 + static func estimateMeter(rawAccents: [Double]) -> (beatsPerBar: Int, phase: Int?) { + guard rawAccents.count >= 12 else { return (4, nil) } + let four = periodicContrast(rawAccents, meter: 4) + let three = periodicContrast(rawAccents, meter: 3) + // 4拍子を基本にして、3拍子は、はっきり良いときだけ採る(3は4の約数でなく、取り違えると全体がずれるため)。 + let useThree = three.contrast > four.contrast * 1.5 && three.contrast >= 0.25 + let chosen = useThree ? three : four + let meter = useThree ? 3 : 4 + return (meter, chosen.contrast >= 0.1 ? chosen.phase : nil) + } + + /// 拍の強さを `meter` ごとに分けたとき、いちばん強い位置の、ほかの位置に対する際立ち。 + private static func periodicContrast(_ accents: [Double], meter: Int) -> (phase: Int, contrast: Double) { + var sums = [Double](repeating: 0, count: meter) + var counts = [Int](repeating: 0, count: meter) + for (index, value) in accents.enumerated() { + sums[index % meter] += value + counts[index % meter] += 1 + } + let means = (0.. 0 ? sums[$0] / Double(counts[$0]) : 0 } + guard let best = means.indices.max(by: { means[$0] < means[$1] }) else { return (0, 0) } + let others = means.indices.filter { $0 != best }.map { means[$0] } + let otherMean = others.reduce(0, +) / Double(max(1, others.count)) + let overall = means.reduce(0, +) / Double(meter) + return (best, (means[best] - otherMean) / (overall + 0.05)) + } + + static func downbeatTimes(beats: [Double], phase: Int, beatsPerBar: Int) -> [Double] { + beats.enumerated().compactMap { index, time in + ((index - phase) % beatsPerBar + beatsPerBar) % beatsPerBar == 0 ? time : nil + } + } + + // MARK: - 曲の構造の境目 + + /// 盛り上がりが大きく変わる時刻(サビ・ドロップ・静かな部分への切り替わり)。 + /// 前後 4 秒ずつの平均の差(novelty)が大きい所を、6 秒以上離して選び、近くの小節の頭(無ければ拍)に寄せる。 + static func sectionBoundaries( + feature: [Double], + hop: Double, + beats: [Double], + downbeats: [Double]?, + duration: Double + ) -> [Double] { + let window = Int((4.0 / hop).rounded()) + guard hop > 0, window >= 2, feature.count > window * 2 else { return [] } + + var prefix = [Double](repeating: 0, count: feature.count + 1) + for (index, value) in feature.enumerated() { prefix[index + 1] = prefix[index] + value } + func mean(_ lower: Int, _ upper: Int) -> Double { (prefix[upper] - prefix[lower]) / Double(upper - lower) } + + var novelty = [Double](repeating: 0, count: feature.count) + for index in window..<(feature.count - window) { + novelty[index] = abs(mean(index, index + window) - mean(index - window, index)) + } + + let nonZero = novelty.filter { $0 > 0 }.sorted() + let median = nonZero.isEmpty ? 0 : nonZero[nonZero.count / 2] + let threshold = max(0.2, median * 2) + + // 大きい順に採り、近すぎるものは捨てる。 + let minimumGap = Int((6.0 / hop).rounded()) + var chosen: [Int] = [] + for index in novelty.indices.sorted(by: { novelty[$0] > novelty[$1] }) { + guard novelty[index] >= threshold else { break } + guard chosen.allSatisfy({ abs($0 - index) >= minimumGap }) else { continue } + chosen.append(index) + } + + let snapTargets = (downbeats?.isEmpty == false) ? downbeats! : beats + return chosen + .map { Double($0) * hop } + .filter { $0 > 4 && $0 < duration - 4 } + .map { time in + guard let nearest = snapTargets.min(by: { abs($0 - time) < abs($1 - time) }), abs(nearest - time) <= 2.5 else { return time } + return nearest + } + .sorted() + } +} diff --git a/ArkServerTests/MusicStructureTests.swift b/ArkServerTests/MusicStructureTests.swift new file mode 100644 index 0000000..a93df11 --- /dev/null +++ b/ArkServerTests/MusicStructureTests.swift @@ -0,0 +1,238 @@ +// ArkServerTests/MusicStructureTests.swift + +import Foundation +import Testing +@testable import ArkServer + +/// 曲の拍の強さ・小節の頭・構造の境目・細かい onset。 +@Suite(.serialized) +struct MusicStructureTests { + // MARK: 部品の単体テスト(配列だけで確かめる) + + @Test + func meterAndDownbeatPhaseAreFoundFromTheAccentPattern() { + // 強・弱・中・弱 の繰り返し(4拍子)。 + let pattern = [1.0, 0.3, 0.5, 0.3] + let fourBeat = (0..<32).map { pattern[$0 % 4] } + #expect(MusicStructureAnalyzer.estimateMeter(rawAccents: fourBeat).beatsPerBar == 4) + #expect(MusicStructureAnalyzer.estimateMeter(rawAccents: fourBeat).phase == 0) + + // 先頭が2拍ぶんずれていれば、小節の頭は添字 2 の位置。 + let shifted = (0..<32).map { pattern[($0 + 2) % 4] } + #expect(MusicStructureAnalyzer.estimateMeter(rawAccents: shifted).phase == 2) + + // 3拍子(強・弱・弱)。 + let waltz = (0..<30).map { $0 % 3 == 1 ? 1.0 : 0.3 } + let meter = MusicStructureAnalyzer.estimateMeter(rawAccents: waltz) + #expect(meter.beatsPerBar == 3) + #expect(meter.phase == 1) + + // 強さに周期が無ければ、小節の頭は分からない(nil)。拍子は 4 のまま。 + let flat = [Double](repeating: 0.6, count: 32) + #expect(MusicStructureAnalyzer.estimateMeter(rawAccents: flat).phase == nil) + #expect(MusicStructureAnalyzer.estimateMeter(rawAccents: flat).beatsPerBar == 4) + + // 拍が少なすぎれば、判断しない。 + #expect(MusicStructureAnalyzer.estimateMeter(rawAccents: [1, 0.3, 0.5]).phase == nil) + } + + @Test + func accentsAreNormalizedAndFlatOnesStayNeutral() { + let normalized = MusicStructureAnalyzer.normalizedAccents([0.2, 0.2, 0.2, 0.2, 1.0, 1.0, 1.0, 1.0, 0.6, 0.6]) + #expect(normalized.allSatisfy { $0 >= 0 && $0 <= 1 }) + #expect(normalized[4] > normalized[0]) + #expect(MusicStructureAnalyzer.normalizedAccents([0.5, 0.5, 0.5, 0.5, 0.5]).allSatisfy { $0 == 0.5 }) + #expect(MusicStructureAnalyzer.normalizedAccents([1, 2]).allSatisfy { $0 == 0.5 }) // 少なすぎる + } + + @Test + func sectionBoundariesAreFoundWhereTheEnergyChanges() { + // 0.1秒ごと。0〜12秒は静か、12〜24秒は盛り上がり、24〜40秒は静か。 + let feature: [Double] = (0..<400).map { index in + let time = Double(index) * 0.1 + return (time >= 12 && time < 24) ? 0.9 : 0.3 + } + let beats = stride(from: 0.5, to: 40, by: 0.5).map { $0 } + let sections = MusicStructureAnalyzer.sectionBoundaries( + feature: feature, hop: 0.1, beats: beats, downbeats: nil, duration: 40 + ) + #expect(sections.count == 2) + #expect(abs(sections[0] - 12) <= 0.6) + #expect(abs(sections[1] - 24) <= 0.6) + // 拍に寄せている。 + #expect(sections.allSatisfy { time in beats.contains { abs($0 - time) < 1e-9 } }) + } + + @Test + func flatMusicHasNoSectionBoundaries() { + let feature = [Double](repeating: 0.5, count: 400) + let sections = MusicStructureAnalyzer.sectionBoundaries(feature: feature, hop: 0.1, beats: [], downbeats: nil, duration: 40) + #expect(sections.isEmpty) + } + + @Test + func sectionBoundariesSnapToDownbeatsWhenKnown() { + let feature: [Double] = (0..<400).map { Double($0) * 0.1 >= 20 ? 0.9 : 0.3 } + let beats = stride(from: 0.5, to: 40, by: 0.5).map { $0 } + // 小節の頭(4拍ごと=2秒おき)は 0.5, 2.5, 4.5 …。境目はそのどれかに寄る。 + let downbeats = stride(from: 0.5, to: 40, by: 2.0).map { $0 } + let sections = MusicStructureAnalyzer.sectionBoundaries(feature: feature, hop: 0.1, beats: beats, downbeats: downbeats, duration: 40) + #expect(sections.count == 1) + #expect(downbeats.contains { abs($0 - sections[0]) < 1e-9 }) + } + + // MARK: 合成した音での確認 + + /// 120BPM(0.5秒ごと)のクリック。`amplitudes[i % amplitudes.count]` が i 番目の強さ。 + private func accentedClicks( + duration: Double, + amplitudes: [Float], + first: Double = 0.5 + ) -> (samples: [Float], clicks: [(time: Double, amplitude: Float)]) { + var clicks: [(Double, Float)] = [] + var index = 0 + var time = first + while time < duration - 0.1 { + clicks.append((time, amplitudes[index % amplitudes.count])) + index += 1 + time += 0.5 + } + return (clickTrack(duration: duration, clicks: clicks), clicks.map { (time: $0.0, amplitude: $0.1) }) + } + + /// 解析した拍のうち、`predicate` に合う強さのクリックの近く(±40ms)にあるものの添字。 + private func beatIndices( + in analysis: MusicAnalysis, + clicks: [(time: Double, amplitude: Float)], + where predicate: (Float) -> Bool + ) -> [Int] { + analysis.beats.indices.filter { index in + guard let nearest = clicks.min(by: { abs($0.time - analysis.beats[index]) < abs($1.time - analysis.beats[index]) }), + abs(nearest.time - analysis.beats[index]) < 0.04 else { return false } + return predicate(nearest.amplitude) + } + } + + @Test + func strongBeatsGetHigherAccentsAndTheBarStartIsFound() { + // 4拍に1回だけ強いクリック(小節の頭)。 + let (samples, clicks) = accentedClicks(duration: 40, amplitudes: [1.0, 0.35, 0.5, 0.35]) + let analysis = BeatAnalyzer().analyze(samples: samples, sampleRate: testSampleRate) + + #expect(analysis.beatAccents.count == analysis.beats.count) + #expect(analysis.beatsPerBar == 4) + + let strong = beatIndices(in: analysis, clicks: clicks) { $0 >= 0.99 } + let weak = beatIndices(in: analysis, clicks: clicks) { $0 <= 0.4 } + #expect(strong.count >= 6 && weak.count >= 12) + + // 強い拍の強さは、弱い拍よりはっきり大きい。 + let strongMean = strong.map { analysis.accent(atBeat: $0) }.reduce(0, +) / Double(strong.count) + let weakMean = weak.map { analysis.accent(atBeat: $0) }.reduce(0, +) / Double(weak.count) + #expect(strongMean > weakMean + 0.3, "強い \(strongMean) 弱い \(weakMean)") + + // 小節の頭は、強いクリックの位置。強い拍の9割以上が「小節の頭」、弱い拍の9割以上が「頭ではない」。 + #expect(analysis.downbeatPhase != nil) + let strongAsDownbeat = strong.filter { analysis.isDownbeat(beatIndex: $0) == true }.count + let weakAsOffbeat = weak.filter { analysis.isDownbeat(beatIndex: $0) == false }.count + #expect(Double(strongAsDownbeat) / Double(strong.count) >= 0.9) + #expect(Double(weakAsOffbeat) / Double(weak.count) >= 0.9) + } + + @Test + func theBarStartFollowsAShiftedAccentPattern() { + // 強いクリックが 2 拍目から始まる(最初の拍は弱い)。 + let (samples, clicks) = accentedClicks(duration: 40, amplitudes: [0.35, 1.0, 0.35, 0.5]) + let analysis = BeatAnalyzer().analyze(samples: samples, sampleRate: testSampleRate) + let strong = beatIndices(in: analysis, clicks: clicks) { $0 >= 0.99 } + #expect(strong.count >= 6) + #expect(Double(strong.filter { analysis.isDownbeat(beatIndex: $0) == true }.count) / Double(strong.count) >= 0.9) + } + + @Test + func fineOnsetEnvelopePeaksAtTheClicks() { + let (samples, clicks) = accentedClicks(duration: 20, amplitudes: [1.0, 0.6]) + let analysis = BeatAnalyzer().analyze(samples: samples, sampleRate: testSampleRate) + #expect(!analysis.onsetEnvelope.isEmpty) + #expect(analysis.onsetHop == MusicStructureAnalyzer.fineHop) + #expect(analysis.onsetEnvelope.allSatisfy { $0 >= 0 && $0 <= 1 }) + + // クリックの近く(±50ms)は高く、クリックとクリックの真ん中は低い。 + var nearValues: [Double] = [] + var midValues: [Double] = [] + for index in 2..<(clicks.count - 2) { + let click = clicks[index].time + nearValues.append(stride(from: click - 0.05, through: click + 0.05, by: 0.025).map { analysis.onset(at: $0) }.max() ?? 0) + midValues.append(analysis.onset(at: click + 0.25)) + } + let nearMean = nearValues.reduce(0, +) / Double(nearValues.count) + let midMean = midValues.reduce(0, +) / Double(midValues.count) + #expect(nearMean > 0.4, "クリックの近く \(nearMean)") + #expect(midMean < 0.15, "クリックの間 \(midMean)") + } + + @Test + func aLoudSectionInTheMiddleIsDetectedAsTwoBoundaries() { + // 0〜14秒は弱く、14〜28秒は強く、28〜42秒は弱い。 + var clicks: [(time: Double, amplitude: Float)] = [] + var time = 0.5 + while time < 41.9 { + clicks.append((time, (time >= 14 && time < 28) ? 1.0 : 0.25)) + time += 0.5 + } + let samples = clickTrack(duration: 42, clicks: clicks) + let analysis = BeatAnalyzer().analyze(samples: samples, sampleRate: testSampleRate) + + #expect(analysis.sectionBoundaries.count >= 2, "境目 \(analysis.sectionBoundaries)") + func nearest(_ target: Double) -> Double { + analysis.sectionBoundaries.map { abs($0 - target) }.min() ?? .infinity + } + #expect(nearest(14) <= 2.0, "14秒の近く \(analysis.sectionBoundaries)") + #expect(nearest(28) <= 2.0, "28秒の近く \(analysis.sectionBoundaries)") + } + + // MARK: 切り出しと互換 + + @Test + func trimmingKeepsAccentsTheBarStartAndSections() { + var analysis = MusicAnalysis( + duration: 40, tempo: 120, + beats: Array(stride(from: 0.5, to: 39.9, by: 0.5)), + energy: [Double](repeating: 0.5, count: 400), + intensity: [MusicIntensity](repeating: .medium, count: 400), + energyHop: 0.1 + ) + analysis.beatsPerBar = 4 + analysis.downbeatPhase = 1 // 拍の添字 1, 5, 9, … が小節の頭 + analysis.beatAccents = (0..