-
-
Notifications
You must be signed in to change notification settings - Fork 47
Expand file tree
/
Copy pathuseScrollAndAnimation.ts
More file actions
487 lines (425 loc) · 20.1 KB
/
Copy pathuseScrollAndAnimation.ts
File metadata and controls
487 lines (425 loc) · 20.1 KB
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
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
import { useCallback, useEffect, useRef } from 'react';
import { unstable_batchedUpdates } from 'react-dom';
import { AnalysisResult } from '@/services/chord-analysis/chordRecognitionService';
import { YouTubePlayer } from '@/types/youtube';
import { useIsPitchShiftEnabled, useIsPitchShiftReady } from '@/stores/uiStore';
import { youtubeMasterClock } from '@/services/audio/youtubeMasterClock';
import {
resolveBeatAtTime,
findDownbeatIndexAtTime,
INITIAL_HYSTERESIS_STATE,
STABILITY_THRESHOLD,
type HysteresisState,
} from '@/utils/beatResolver';
/**
* DIAGNOSTIC TAG for logs emitted from the beat-grid animation loop. Paired
* with `[pitch-diag/service]` and `[pitch-diag/hook]`, these three streams
* let us reconstruct whether "animation frozen at current beat" is caused
* by the rAF seeing a stuck `rawTime` (service-side freeze) or the rAF
* correctly reading a live time but the resolver deciding not to emit a
* new beat index. We throttle to ~1 Hz because the rAF loop runs at 20 fps
* and we don't want to flood the console.
*/
const _ANIM_DIAG_TAG = '[pitch-diag/anim]';
// Define ChordGridData type based on the analyze page implementation
export interface ChordGridData {
chords: string[];
beats: (number | null)[];
hasPadding: boolean;
paddingCount: number;
shiftCount: number;
totalPaddingCount: number;
originalAudioMapping?: Array<{
timestamp: number;
chord: string;
visualIndex: number;
}>;
animationMapping?: Array<{
timestamp: number;
visualIndex: number;
chord: string;
}>;
}
export interface ScrollAndAnimationDependencies {
// Audio and playback state
youtubePlayer: YouTubePlayer | null; // YouTube player for timing
isPlaying: boolean;
currentTime: number;
playbackRate: number;
analysisResults: AnalysisResult | null;
// Beat tracking state
currentBeatIndex: number;
currentBeatIndexRef: React.MutableRefObject<number>;
setCurrentBeatIndex: (index: number) => void;
setCurrentDownbeatIndex: (index: number) => void;
setCurrentTime: (time: number) => void;
// UI state
isFollowModeEnabled: boolean;
// Animation data
chordGridData: ChordGridData | null;
globalSpeedAdjustment: number | null;
setGlobalSpeedAdjustment: (adjustment: number | null) => void;
lastClickInfo: {
visualIndex: number;
timestamp: number;
clickTime: number;
} | null;
}
export interface ScrollAndAnimationHelpers {
scrollToCurrentBeat: () => void;
}
/**
* Custom hook for scroll and animation functions
* Extracted from analyze page component - maintains ZERO logic changes
*/
export const useScrollAndAnimation = (deps: ScrollAndAnimationDependencies): ScrollAndAnimationHelpers => {
const {
youtubePlayer,
isPlaying,
currentTime,
playbackRate: _playbackRate,
analysisResults,
currentBeatIndex,
currentBeatIndexRef,
setCurrentBeatIndex,
setCurrentDownbeatIndex,
setCurrentTime,
isFollowModeEnabled,
chordGridData,
globalSpeedAdjustment,
setGlobalSpeedAdjustment,
lastClickInfo,
} = deps;
const isPitchShiftEnabled = useIsPitchShiftEnabled();
const isPitchShiftReady = useIsPitchShiftReady();
const isPitchShiftTimeAuthorityActive = isPitchShiftEnabled && isPitchShiftReady;
const currentTimeRef = useRef(currentTime);
// LIVE-CLOCK SOURCE: always read the current singleton on every rAF tick.
// We must NOT cache the service in a useRef, because React StrictMode
// double-mount (or pitch-shift toggle cleanup) resets the singleton and
// creates a fresh instance — a stale ref would read from the disposed
// instance forever (currentTime=0, isPlaying=false).
useEffect(() => {
currentTimeRef.current = currentTime;
}, [currentTime]);
// ANTI-JITTER: Hysteresis-based beat tracking to prevent oscillation
// The full cascade (padding lookup, BPM virtual estimation, audio-mapping
// binary search, stability gating, dwell/rewind handling) now lives in the
// pure `resolveBeatAtTime` utility. This hook only owns the rAF scheduling,
// the React state writes, and the hysteresis bookkeeping ref.
const hysteresisStateRef = useRef<HysteresisState>(INITIAL_HYSTERESIS_STATE);
// PERFORMANCE P1-D: Page Visibility API — pause rAF computation when tab is hidden
const isTabVisibleRef = useRef(true);
useEffect(() => {
const handleVisibility = () => {
isTabVisibleRef.current = document.visibilityState === 'visible';
};
document.addEventListener('visibilitychange', handleVisibility);
return () => document.removeEventListener('visibilitychange', handleVisibility);
}, []);
// PERFORMANCE P3-H: Time-delta tracking to skip redundant computation
const lastComputedTimeRef = useRef(0);
// PERFORMANCE FIX #3: Auto-scroll optimization
// Track last scroll time and beat index to reduce scroll frequency
const lastScrollTimeRef = useRef(0);
const lastScrolledBeatIndexRef = useRef(-1);
// Track last scrolled measure to trigger scrolls only on measure boundaries (downbeats)
const lastScrolledMeasureIndexRef = useRef(-1);
// JITTER GUARDS: `hysteresisStateRef` above tracks last emitted beat,
// last emit time, and previous frame time for dwell/rewind checks.
// ANTI-JITTER: Centralized state update function to prevent multiple conflicting updates
const updateBeatIndexSafely = useCallback((
newBeatIndex: number,
options?: {
downbeatIndex?: number;
emitTime?: number;
}
) => {
const beatChanged = currentBeatIndexRef.current !== newBeatIndex;
if (!beatChanged && typeof options?.downbeatIndex !== 'number') {
return;
}
unstable_batchedUpdates(() => {
if (beatChanged) {
currentBeatIndexRef.current = newBeatIndex;
setCurrentBeatIndex(newBeatIndex);
hysteresisStateRef.current = {
...hysteresisStateRef.current,
lastEmittedBeat: newBeatIndex,
lastEmitTime: typeof options?.emitTime === 'number'
? options.emitTime
: hysteresisStateRef.current.lastEmitTime,
};
}
if (typeof options?.downbeatIndex === 'number') {
setCurrentDownbeatIndex(options.downbeatIndex);
}
});
}, [setCurrentBeatIndex, currentBeatIndexRef, setCurrentDownbeatIndex]);
// PERFORMANCE FIX #3: Optimized auto-scrolling with reduced frequency
const scrollToCurrentBeat = useCallback(() => {
if (!isFollowModeEnabled || currentBeatIndex === -1) return;
// Measure-boundary gating: only scroll when entering a new measure (downbeat)
const beatTime = (typeof chordGridData?.beats?.[currentBeatIndex] === 'number')
? (chordGridData!.beats![currentBeatIndex] as number)
: null;
if (beatTime === null) return;
const measureIndex = findDownbeatIndexAtTime(beatTime, analysisResults?.downbeats);
if (measureIndex === -1) return;
const downbeats = analysisResults?.downbeats || [];
const downbeatTime = downbeats[measureIndex];
const DOWNBEAT_TOLERANCE = 0.12; // 120ms tolerance
const isAtDownbeat = Math.abs(beatTime - downbeatTime) <= DOWNBEAT_TOLERANCE;
// Only scroll exactly at downbeat and only once per measure
if (!isAtDownbeat || measureIndex === lastScrolledMeasureIndexRef.current) {
return;
}
const now = Date.now();
// Preserve throttle: max 5 scrolls/second
if (now - lastScrollTimeRef.current < 200) {
return;
}
// Keep position-based debouncing as an extra guard
const beatIndexDelta = Math.abs(currentBeatIndex - lastScrolledBeatIndexRef.current);
if (beatIndexDelta === 0) {
return; // Same beat, no need to scroll
}
if (beatIndexDelta <= 2 && now - lastScrollTimeRef.current < 400) {
return;
}
const beatElement = document.getElementById(`chord-${currentBeatIndex}`);
if (beatElement) {
// Find nearest scrollable container (fallback to window viewport)
const getNearestScrollContainer = (el: HTMLElement | null): HTMLElement | null => {
let node: HTMLElement | null = el?.parentElement || null;
while (node) {
const style = window.getComputedStyle(node);
const overflowY = style.overflowY;
const hasScrollableY = (overflowY === 'auto' || overflowY === 'scroll') && node.scrollHeight > node.clientHeight;
if (hasScrollableY) return node;
node = node.parentElement;
}
return null;
};
const containerEl = getNearestScrollContainer(beatElement);
const elementRect = beatElement.getBoundingClientRect();
if (containerEl) {
const containerRect = containerEl.getBoundingClientRect();
const containerHeight = containerRect.height;
const containerCenter = containerRect.top + containerHeight / 2;
const elementCenter = elementRect.top + elementRect.height / 2;
const deltaFromCenter = elementCenter - containerCenter;
// Viewport boundary check relative to the scroll container
const isOutsideViewport = elementRect.bottom < containerRect.top || elementRect.top > containerRect.bottom;
// Comfort zone scaled by container size: 20% of container height, clamped to [24, 80] px
const comfortZone = Math.min(80, Math.max(24, containerHeight * 0.2));
const isOutsideComfortZone = Math.abs(deltaFromCenter) > comfortZone;
if (!isOutsideViewport && !isOutsideComfortZone) {
return; // Element is visible and reasonably centered within container, skip scroll
}
} else {
// Fallback: window viewport logic
const viewportHeight = window.innerHeight;
const viewportCenter = viewportHeight / 2;
const elementCenter = elementRect.top + elementRect.height / 2;
const delta = elementCenter - viewportCenter;
const isOutsideViewport = elementRect.bottom < 0 || elementRect.top > viewportHeight;
const isOutsideComfortZone = Math.abs(delta) > 80;
if (!isOutsideViewport && !isOutsideComfortZone) {
return;
}
}
// OPTIMIZATION: Single RAF; set measure + beat tracking and choose scroll behavior
requestAnimationFrame(() => {
lastScrollTimeRef.current = Date.now();
lastScrolledBeatIndexRef.current = currentBeatIndex;
lastScrolledMeasureIndexRef.current = measureIndex;
const isMobile = typeof window !== 'undefined' && ((window.innerWidth <= 768) || (/Mobi|Android/i.test(navigator.userAgent)));
beatElement.scrollIntoView({
behavior: isMobile ? 'auto' : 'smooth',
block: 'center',
inline: 'nearest'
});
});
}
}, [currentBeatIndex, isFollowModeEnabled, chordGridData, analysisResults]);
// Auto-scroll when current beat changes
useEffect(() => {
scrollToCurrentBeat();
}, [currentBeatIndex, scrollToCurrentBeat, isFollowModeEnabled]); // Include isFollowModeEnabled dependency
// PERFORMANCE OPTIMIZATION: RequestAnimationFrame with frame skipping
const rafRef = useRef<number | undefined>(undefined);
const frameCounterRef = useRef<number>(0);
const FRAME_SKIP = 2; // Run every 3rd frame (60fps / 3 = 20fps)
// PERFORMANCE OPTIMIZATION: Debounce state updates to reduce re-renders
const lastStateUpdateTimeRef = useRef<number>(0);
const STATE_UPDATE_INTERVAL = 50; // Update at most every 50ms (20fps) instead of 60fps
// PERFORMANCE OPTIMIZATION: Throttle currentTime writes to store to reduce re-renders
const lastTimeUpdateRef = useRef<number>(0);
// DIAGNOSTIC: throttle log counter for the rAF loop. Set at most once per
// ~1000 ms of wall-clock time. Outside the effect so successive effect runs
// keep rate-limiting correctly across re-renders.
const TIME_UPDATE_INTERVAL = 100; // Keep visual/audio consumers fresher to reduce residual interpolation snaps
const resetAnimationTrackingState = useCallback((timestamp: number, visualIndex: number = -1) => {
const shouldSeedBeat = visualIndex >= 0;
currentTimeRef.current = timestamp;
lastComputedTimeRef.current = Number.NEGATIVE_INFINITY;
lastStateUpdateTimeRef.current = 0;
hysteresisStateRef.current = {
lastStableBeat: shouldSeedBeat ? visualIndex : -1,
beatStabilityCounter: shouldSeedBeat ? STABILITY_THRESHOLD : 0,
lastEmittedBeat: shouldSeedBeat ? visualIndex : -1,
lastEmitTime: timestamp,
prevTime: timestamp,
};
}, []);
useEffect(() => {
if (!lastClickInfo) {
return;
}
// Manual beat jumps must also reset the animation hook's internal rewind
// guards. Otherwise a backward seek can inherit the prior forward-only
// state and appear frozen until playback catches back up.
resetAnimationTrackingState(lastClickInfo.timestamp, lastClickInfo.visualIndex);
}, [lastClickInfo, resetAnimationTrackingState]);
// Update current time and check for current beat
useEffect(() => {
// CRITICAL FIX: Only set up animation loop when playing
// This prevents unnecessary CPU usage when paused
if (!analysisResults || !isPlaying) {
return;
}
// UNIFIED CLOCK: the master clock always returns a usable position once
// it's been anchored (cold-start is handled inside the master by a
// `onYoutubeProgress` or `onUserSeek`). We therefore no longer need to
// require `youtubePlayer.getCurrentTime` as a precondition for the rAF
// to run — the master is the single source of truth regardless of
// whether pitch shift is active.
lastComputedTimeRef.current = Number.NEGATIVE_INFINITY;
// PERFORMANCE OPTIMIZATION: Use RequestAnimationFrame with frame skipping
// This provides 20fps updates (every 3rd frame) to match state update throttle
const updateBeatTracking = () => {
// CRITICAL FIX: Check current playing state dynamically
// If paused, stop the loop immediately (don't schedule next frame)
if (!isPlaying) {
return; // Stop the loop when paused
}
// PERFORMANCE FIX #1: Frame skipping to reduce CPU usage
// Increment frame counter and skip frames that don't match our target rate
frameCounterRef.current++;
if (frameCounterRef.current % (FRAME_SKIP + 1) !== 0) {
// Skip this frame, but schedule next one to maintain loop
rafRef.current = requestAnimationFrame(updateBeatTracking);
return;
}
// PERFORMANCE P1-D: Skip expensive beat tracking computation when tab is hidden
// The rAF loop continues to run but skips all CPU-intensive work
if (!isTabVisibleRef.current) {
rafRef.current = requestAnimationFrame(updateBeatTracking);
return;
}
// UNIFIED CLOCK: the beat grid reads from the YouTube master clock on
// EVERY rAF tick, regardless of whether pitch shift is active. The
// master extrapolates `performance.now() × rate` between YouTube
// progress samples, so the grid always animates smoothly even when
// YT's onProgress fires infrequently. When pitch shift is active the
// GrainPlayer is a slave that re-anchors to this same master in
// `usePitchShiftAudio`'s 40 ms slave loop — so the grid, the video,
// and the pitch-shifted audio are all locked to ONE time source.
const rawTime = youtubeMasterClock.getLivePosition();
const time = rawTime;
// NOTE: The previous implementation extrapolated a "virtual click time"
// from Date.now() and `playbackRate` to paper over player seek latency
// after a beat click. That extrapolation was a third, independent place
// where `playbackRate` was applied to time advancement and was a known
// source of desync when the slider changed. With the unified clock
// (GrainPlayer master on pitch-shift, YouTube master otherwise) the
// click handler seeds `currentTime` synchronously before the next rAF,
// so the raw clock is always good enough.
const REWIND_RESET_THRESHOLD_SECONDS = 0.2;
if (time + REWIND_RESET_THRESHOLD_SECONDS < hysteresisStateRef.current.prevTime) {
// Native YouTube replay/scrub actions can jump backward without going
// through the beat-grid click path. Reset the forward-only guards so
// the animation can immediately re-lock to the new timeline position.
resetAnimationTrackingState(time);
}
// PERFORMANCE P3-H: Skip computation if player time hasn't meaningfully changed
// This avoids redundant binary searches and state updates on near-identical frames
if (Math.abs(time - lastComputedTimeRef.current) < 0.01) {
rafRef.current = requestAnimationFrame(updateBeatTracking);
return;
}
lastComputedTimeRef.current = time;
const stamp = Date.now();
// UNIFIED CLOCK: publish the master clock's live position to React
// state every TIME_UPDATE_INTERVAL ms regardless of whether pitch
// shift is active. Previously this publish was gated on
// `!isPitchShiftTimeAuthorityActive` because the GrainPlayer's
// time-update callback owned the publish in pitch-shift mode; with
// the master as single source of truth the gate is no longer needed
// and a uniform rate here eliminates the divergence between the two
// modes that users could feel when toggling pitch shift.
if (stamp - lastTimeUpdateRef.current >= TIME_UPDATE_INTERVAL) {
setCurrentTime(time);
lastTimeUpdateRef.current = stamp;
}
// DEBUG: Log animation interval execution every 5 seconds
// if (Math.floor(time) % 5 === 0 && Math.floor(time * 10) % 10 === 0) {
// console.log(`🔄 ANIMATION INTERVAL: time=${time.toFixed(3)}s, isPlaying=${isPlaying}, chordGridData exists=${!!chordGridData}, currentBeatIndex=${currentBeatIndexRef.current}, manualOverride=${manualBeatIndexOverride}`);
// }
// Delegate the full beat-resolution cascade to the pure utility.
// The utility returns the next hysteresis state and (optionally) a
// new global speed adjustment; this hook is responsible only for
// React state writes, the rAF schedule, and time bookkeeping.
if (chordGridData && chordGridData.chords.length > 0) {
const result = resolveBeatAtTime({
time,
chordGridData,
analysisResults,
hysteresisState: hysteresisStateRef.current,
globalSpeedAdjustment,
});
hysteresisStateRef.current = result.nextHysteresisState;
if (result.nextGlobalSpeedAdjustment !== globalSpeedAdjustment) {
setGlobalSpeedAdjustment(result.nextGlobalSpeedAdjustment);
}
if (!result.shouldSkipEmit) {
const now = Date.now();
const shouldUpdate =
(now - lastStateUpdateTimeRef.current >= STATE_UPDATE_INTERVAL) ||
(currentBeatIndexRef.current !== result.beatIndex);
if (shouldUpdate) {
updateBeatIndexSafely(result.beatIndex, {
downbeatIndex: result.downbeatIndex,
emitTime: time,
});
lastStateUpdateTimeRef.current = now;
}
}
}
// PERFORMANCE OPTIMIZATION: Schedule next frame for smooth 60fps updates
// Only schedule if still playing (checked at start of next frame)
hysteresisStateRef.current = {
...hysteresisStateRef.current,
prevTime: time,
};
rafRef.current = requestAnimationFrame(updateBeatTracking);
};
// Start the animation loop only when playing
rafRef.current = requestAnimationFrame(updateBeatTracking);
return () => {
if (rafRef.current) {
cancelAnimationFrame(rafRef.current);
rafRef.current = undefined;
}
// Reset frame counter when effect cleanup runs
frameCounterRef.current = 0;
};
// CRITICAL FIX: Include isPlaying to ensure animation starts/stops when playback changes
// The effect will restart the loop when isPlaying becomes true
// and cleanup will stop it when isPlaying becomes false
}, [isPlaying, analysisResults, youtubePlayer, chordGridData, globalSpeedAdjustment, lastClickInfo, currentBeatIndexRef, setCurrentBeatIndex, setCurrentDownbeatIndex, setGlobalSpeedAdjustment, setCurrentTime, updateBeatIndexSafely, isPitchShiftTimeAuthorityActive, resetAnimationTrackingState]); // Updated to use centralized beat updates
return {
scrollToCurrentBeat,
};
};