All files / jianpu-renderer/core/layout MultiVoiceAligner.ts

0% Statements 0/378
0% Branches 0/1
0% Functions 0/1
0% Lines 0/378

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     
/**
 * 多声部对齐器
 * 
 * @description 确保多声部在相同时间点垂直对齐
 * 
 * 核心功能:
 * 1. 收集所有声部的时间戳
 * 2. 为相同时间戳的音符分配统一的X坐标
 * 3. 处理边界情况(单声部、休止符、不同时值)
 * 
 * 对齐原则:
 * - 相同时间戳的音符必须垂直对齐(X坐标相同)
 * - 取所有声部中该时间戳音符的最大X坐标作为统一坐标
 * - 如果某声部在该时间戳没有音符,不影响其他声部
 */

import { JianpuMeasure } from '../../models/JianpuMeasure';
import { JianpuNote } from '../../models/JianpuNote';

// ==================== 类型定义 ====================

/** 时间戳到音符的映射 */
export interface TimestampNoteMap {
  /** 时间戳(以四分音符为单位) */
  timestamp: number;
  /** 该时间戳的所有音符 */
  notes: NoteWithVoice[];
  /** 统一的X坐标 */
  alignedX: number;
}

/** 带声部信息的音符 */
export interface NoteWithVoice {
  /** 音符对象 */
  note: JianpuNote;
  /** 声部索引 */
  voiceIndex: number;
}

/** 对齐结果 */
export interface AlignmentResult {
  /** 小节索引 */
  measureIndex: number;
  /** 声部数量 */
  voiceCount: number;
  /** 时间戳数量 */
  timestampCount: number;
  /** 对齐的音符数量 */
  alignedNoteCount: number;
  /** 时间戳映射 */
  timestampMap: TimestampNoteMap[];
}

/** 对齐配置 */
export interface AlignmentConfig {
  /** 时间戳精度(用于比较浮点数,默认0.001) */
  timestampPrecision: number;
  /** 是否包含休止符(默认true) */
  includeRests: boolean;
  /** 对齐策略(max取最大X,min取最小X,avg取平均) */
  alignmentStrategy: 'max' | 'min' | 'avg';
}

// ==================== 主类 ====================

/**
 * 多声部对齐器
 */
export class MultiVoiceAligner {
  /** 配置 */
  private config: AlignmentConfig;

  /**
   * 构造函数
   * @param config 对齐配置
   */
  constructor(config: Partial<AlignmentConfig> = {}) {
    this.config = {
      timestampPrecision: config.timestampPrecision ?? 0.001,
      includeRests: config.includeRests ?? true,
      alignmentStrategy: config.alignmentStrategy ?? 'max',
    };
  }

  /**
   * 对齐单个小节的多声部音符
   * 
   * @param measure 小节对象
   * @returns 对齐结果
   */
  alignVoices(measure: JianpuMeasure): AlignmentResult {
    const result: AlignmentResult = {
      measureIndex: measure.index,
      voiceCount: measure.voices.length,
      timestampCount: 0,
      alignedNoteCount: 0,
      timestampMap: [],
    };

    // 单声部不需要对齐
    if (measure.voices.length <= 1) {
      return result;
    }

    // 1. 收集所有时间戳
    const timestampMap = this.collectTimestamps(measure);
    result.timestampCount = timestampMap.size;

    // 2. 对齐每个时间戳的音符
    for (const [timestamp, notes] of timestampMap) {
      // 只有当多个声部在同一时间戳有音符时才需要对齐
      if (notes.length > 1) {
        const alignedX = this.calculateAlignedX(notes);
        
        // 更新所有音符的X坐标
        for (const { note } of notes) {
          note.x = alignedX;
        }
        
        result.alignedNoteCount += notes.length;
        result.timestampMap.push({
          timestamp,
          notes,
          alignedX,
        });
      }
    }

    return result;
  }

  /**
   * 对齐多个小节
   * 
   * @param measures 小节数组
   * @returns 对齐结果数组
   */
  alignMeasures(measures: JianpuMeasure[]): AlignmentResult[] {
    return measures.map(measure => this.alignVoices(measure));
  }

  /**
   * 收集小节内所有声部的时间戳
   * 
   * @param measure 小节对象
   * @returns 时间戳到音符的映射
   */
  private collectTimestamps(measure: JianpuMeasure): Map<number, NoteWithVoice[]> {
    const timestampMap = new Map<number, NoteWithVoice[]>();
    const { timestampPrecision, includeRests } = this.config;

    for (let voiceIndex = 0; voiceIndex < measure.voices.length; voiceIndex++) {
      const voice = measure.voices[voiceIndex];
      
      for (const note of voice) {
        // 可选:跳过休止符
        if (!includeRests && note.isRest) {
          continue;
        }

        // 使用精度处理的时间戳作为键
        const normalizedTimestamp = this.normalizeTimestamp(note.timestamp);
        
        if (!timestampMap.has(normalizedTimestamp)) {
          timestampMap.set(normalizedTimestamp, []);
        }
        
        timestampMap.get(normalizedTimestamp)!.push({
          note,
          voiceIndex,
        });
      }
    }

    return timestampMap;
  }

  /**
   * 标准化时间戳(处理浮点数精度问题)
   * 
   * @param timestamp 原始时间戳
   * @returns 标准化后的时间戳
   */
  private normalizeTimestamp(timestamp: number): number {
    const { timestampPrecision } = this.config;
    // 将时间戳四舍五入到指定精度
    const factor = 1 / timestampPrecision;
    return Math.round(timestamp * factor) / factor;
  }

  /**
   * 计算统一的X坐标
   * 
   * @param notes 相同时间戳的所有音符
   * @returns 统一的X坐标
   */
  private calculateAlignedX(notes: NoteWithVoice[]): number {
    const { alignmentStrategy } = this.config;
    const xValues = notes.map(({ note }) => note.x);

    switch (alignmentStrategy) {
      case 'max':
        return Math.max(...xValues);
      case 'min':
        return Math.min(...xValues);
      case 'avg':
        return xValues.reduce((sum, x) => sum + x, 0) / xValues.length;
      default:
        return Math.max(...xValues);
    }
  }

  /**
   * 检查小节是否需要对齐
   * 
   * @param measure 小节对象
   * @returns 是否需要对齐
   */
  needsAlignment(measure: JianpuMeasure): boolean {
    // 单声部不需要对齐
    if (measure.voices.length <= 1) {
      return false;
    }

    // 检查是否有多个声部在同一时间戳有音符
    const timestampMap = this.collectTimestamps(measure);
    
    for (const notes of timestampMap.values()) {
      if (notes.length > 1) {
        return true;
      }
    }

    return false;
  }

  /**
   * 获取小节内所有唯一时间戳(已排序)
   * 
   * @param measure 小节对象
   * @returns 排序后的时间戳数组
   */
  getUniqueTimestamps(measure: JianpuMeasure): number[] {
    const timestampMap = this.collectTimestamps(measure);
    return Array.from(timestampMap.keys()).sort((a, b) => a - b);
  }

  /**
   * 获取指定时间戳的所有音符
   * 
   * @param measure 小节对象
   * @param timestamp 时间戳
   * @returns 音符数组
   */
  getNotesAtTimestamp(measure: JianpuMeasure, timestamp: number): NoteWithVoice[] {
    const normalizedTimestamp = this.normalizeTimestamp(timestamp);
    const timestampMap = this.collectTimestamps(measure);
    return timestampMap.get(normalizedTimestamp) ?? [];
  }

  /**
   * 验证对齐结果
   * 
   * @param measure 小节对象
   * @returns 是否所有相同时间戳的音符X坐标相同
   */
  validateAlignment(measure: JianpuMeasure): boolean {
    const timestampMap = this.collectTimestamps(measure);
    
    for (const notes of timestampMap.values()) {
      if (notes.length > 1) {
        const firstX = notes[0].note.x;
        for (let i = 1; i < notes.length; i++) {
          if (Math.abs(notes[i].note.x - firstX) > this.config.timestampPrecision) {
            return false;
          }
        }
      }
    }

    return true;
  }

  /**
   * 获取当前配置
   */
  getConfig(): AlignmentConfig {
    return { ...this.config };
  }

  /**
   * 更新配置
   */
  updateConfig(config: Partial<AlignmentConfig>): void {
    Object.assign(this.config, config);
  }
}

// ==================== 工厂函数 ====================

/**
 * 创建多声部对齐器
 */
export function createMultiVoiceAligner(config?: Partial<AlignmentConfig>): MultiVoiceAligner {
  return new MultiVoiceAligner(config);
}

// ==================== 工具函数 ====================

/**
 * 快速对齐单个小节
 * 
 * @param measure 小节对象
 * @returns 是否进行了对齐
 */
export function alignMeasureVoices(measure: JianpuMeasure): boolean {
  const aligner = new MultiVoiceAligner();
  const result = aligner.alignVoices(measure);
  return result.alignedNoteCount > 0;
}

/**
 * 快速对齐多个小节
 * 
 * @param measures 小节数组
 * @returns 对齐的小节数量
 */
export function alignAllMeasureVoices(measures: JianpuMeasure[]): number {
  const aligner = new MultiVoiceAligner();
  let alignedCount = 0;
  
  for (const measure of measures) {
    const result = aligner.alignVoices(measure);
    if (result.alignedNoteCount > 0) {
      alignedCount++;
    }
  }
  
  return alignedCount;
}

/**
 * 检查音符是否在同一时间点
 * 
 * @param note1 音符1
 * @param note2 音符2
 * @param precision 精度(默认0.001)
 * @returns 是否在同一时间点
 */
export function areNotesAtSameTime(
  note1: JianpuNote, 
  note2: JianpuNote, 
  precision: number = 0.001
): boolean {
  return Math.abs(note1.timestamp - note2.timestamp) <= precision;
}

/**
 * 获取声部统计信息
 * 
 * @param measure 小节对象
 * @returns 声部统计
 */
export function getVoiceStats(measure: JianpuMeasure): {
  voiceCount: number;
  noteCountPerVoice: number[];
  hasMultiVoice: boolean;
  maxNotesInVoice: number;
} {
  const noteCountPerVoice = measure.voices.map(voice => voice.length);
  
  return {
    voiceCount: measure.voices.length,
    noteCountPerVoice,
    hasMultiVoice: measure.voices.length > 1 && noteCountPerVoice.filter(c => c > 0).length > 1,
    maxNotesInVoice: Math.max(...noteCountPerVoice, 0),
  };
}