Skip to content

Commit

Permalink
fix: refactor and add perf monitor
Browse files Browse the repository at this point in the history
  • Loading branch information
triyanox committed Jul 26, 2024
1 parent 28d5701 commit a74e917
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 6 deletions.
21 changes: 15 additions & 6 deletions lib/hooks.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { useCallback, useEffect, useReducer, useRef, useState } from 'react';
import { nanoid } from 'nanoid';
import { synthReducer } from '@/lib/reducers';
import useAudioContext, { AudioContextOptions } from '@/lib/audio-context';
import { synthReducer } from '@/lib/reducers';
import { nanoid } from 'nanoid';
import { useCallback, useEffect, useReducer, useRef, useState } from 'react';

export const useAudioSetup = () => {
const [opts] = useState<AudioContextOptions>({
Expand Down Expand Up @@ -167,6 +167,8 @@ export const usePluginManagement = (
pluginOrder: string[],
) => {
const pluginNodesRef = useRef<Map<string, AudioNode>>(new Map());
const previousPluginsRef = useRef(plugins);
const previousPluginOrderRef = useRef(pluginOrder);

const reconnectPluginChain = useCallback(() => {
if (
Expand Down Expand Up @@ -207,12 +209,19 @@ export const usePluginManagement = (
}, [audioContext, plugins, pluginOrder, effectsChainInputRef, masterGainRef]);

useEffect(() => {
reconnectPluginChain();
const pluginsChanged = plugins !== previousPluginsRef.current;
const orderChanged = pluginOrder !== previousPluginOrderRef.current;

if (pluginsChanged || orderChanged) {
reconnectPluginChain();
previousPluginsRef.current = plugins;
previousPluginOrderRef.current = pluginOrder;
}

return () => {
// eslint-disable-next-line react-hooks/exhaustive-deps
pluginNodesRef.current.forEach((node) => node.disconnect());
};
}, [reconnectPluginChain]);
}, [plugins, pluginOrder, reconnectPluginChain]);

return { reconnectPluginChain };
};
Expand Down
35 changes: 35 additions & 0 deletions lib/perf-monitor.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import React, { useEffect, useState } from 'react';

const PerformanceMonitor: React.FC = () => {
const [fps, setFps] = useState(0);

useEffect(() => {
let frameCount = 0;
let lastTime = performance.now();

const updateFps = () => {
const now = performance.now();
frameCount++;

if (now - lastTime > 1000) {
setFps(Math.round((frameCount * 1000) / (now - lastTime)));
frameCount = 0;
lastTime = now;
}

requestAnimationFrame(updateFps);
};

const animationId = requestAnimationFrame(updateFps);

return () => cancelAnimationFrame(animationId);
}, []);

return (
<div className="fixed top-0 right-0 bg-black text-white p-2 text-sm">
FPS {fps}
</div>
);
};

export default PerformanceMonitor;

0 comments on commit a74e917

Please sign in to comment.