| 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()) | |
| } | |