File size: 1,144 Bytes
00a912e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { roomRepo } from '../repositories/roomRepository.js'

/** 估算房间当前播放位置 */
export function estimateCurrentTimeAt(roomId: string, serverTime: number): number {
  const room = roomRepo.get(roomId)
  if (!room) return 0

  const { playState } = room
  if (!playState.isPlaying) return playState.currentTime

  // Clamp elapsed to 0 — serverTimestamp can be a future scheduleTime
  // (set in playTrackInRoom/seekTrack), so Date.now() - serverTimestamp
  // may be negative before the scheduled execution moment.
  const elapsed = Math.max(0, (serverTime - playState.serverTimestamp) / 1000)
  const estimated = playState.currentTime + elapsed

  // Clamp to track duration so mid-song joiners don't receive a position
  // beyond the song length when the conductor hasn't reported end-of-track.
  const duration = room.currentTrack?.duration
  if (duration && duration > 0) {
    return Math.min(estimated, duration)
  }
  return estimated
}

/** Estimate the room position at the current server time. */
export function estimateCurrentTime(roomId: string): number {
  return estimateCurrentTimeAt(roomId, Date.now())
}