Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Logarithmic binning of multiband track volumes #940

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/lemon-dancers-work.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@livekit/components-react": patch
---

Logarithmic binning of multiband track volumes
10 changes: 9 additions & 1 deletion packages/react/src/components/participant/AudioVisualizer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,15 @@ export const AudioVisualizer: (
const barCount = 7;
const trackReference = useEnsureTrackRef(trackRef);

const volumes = useMultibandTrackVolume(trackReference, { bands: 7, loPass: 300 });
const volumes = useMultibandTrackVolume(trackReference, {
bands: 7,
loPass: 60,
hiPass: 1800,
analyserOptions: {
minDecibels: -60,
maxDecibels: -20,
},
});

return (
<svg
Expand Down
68 changes: 58 additions & 10 deletions packages/react/src/hooks/useTrackVolume.ts
Original file line number Diff line number Diff line change
Expand Up @@ -113,11 +113,13 @@ export function useMultibandTrackVolume(
? trackOrTrackReference
: <LocalAudioTrack | RemoteAudioTrack | undefined>trackOrTrackReference?.publication?.track;
const [frequencyBands, setFrequencyBands] = React.useState<Array<number>>([]);
options.analyserOptions = { ...multibandDefaults.analyserOptions, ...options.analyserOptions };
const opts = { ...multibandDefaults, ...options };
React.useEffect(() => {
if (!track || !track?.mediaStream) {
return;
}

const { analyser, cleanup } = createAudioAnalyser(track, opts.analyserOptions);

const bufferLength = analyser.frequencyBinCount;
Expand All @@ -132,16 +134,14 @@ export function useMultibandTrackVolume(
frequencies = frequencies.slice(options.loPass, options.hiPass);

const normalizedFrequencies = normalizeFrequencies(frequencies);
const chunkSize = Math.ceil(normalizedFrequencies.length / opts.bands);
const chunks: Array<number> = [];
for (let i = 0; i < opts.bands; i++) {
const summedVolumes = normalizedFrequencies
.slice(i * chunkSize, (i + 1) * chunkSize)
.reduce((acc, val) => (acc += val), 0);
chunks.push(summedVolumes / chunkSize);
}

setFrequencyBands(chunks);
const binVolumes = fftToLogBins(
normalizedFrequencies,
analyser.context.sampleRate,
opts.bands,
opts.analyserOptions.fftSize!,
);

setFrequencyBands(binVolumes);
};

const interval = setInterval(updateVolume, opts.updateInterval);
Expand All @@ -154,3 +154,51 @@ export function useMultibandTrackVolume(

return frequencyBands;
}

function calculateLogBinEdges(minFreq: number, maxFreq: number, numBins: number): number[] {
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

probably worth looking at Bark Scale also (https://en.wikipedia.org/wiki/Bark_scale) as it maps psychoacoustics.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

oh, nice! might be even better!

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Mel Scale - https://en.wikipedia.org/wiki/Mel_scale may be better.

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

One is pitch and the other is loudness scale.

const logBinEdges: number[] = [];
const logMinFreq = Math.log(minFreq);
const logMaxFreq = Math.log(maxFreq);
const binWidth = (logMaxFreq - logMinFreq) / numBins;

for (let i = 0; i <= numBins; i++) {
logBinEdges.push(Math.exp(logMinFreq + i * binWidth));
}

return logBinEdges;
}

function fftToLogBins(
rawFFTValues: Float32Array,
sampleRate: number,
numBins: number,
fftSize: number,
): number[] {
const deltaF = sampleRate / fftSize;

// Define the min and max frequencies of interest
const minFreq = deltaF; // Starting from the first FFT bin frequency
const maxFreq = sampleRate / 2; // Nyquist frequency

const logBinEdges = calculateLogBinEdges(minFreq, maxFreq, numBins);
const logBinValues = new Array(numBins).fill(0);

for (let i = 0; i < numBins; i++) {
const startFreq = logBinEdges[i];
const endFreq = logBinEdges[i + 1];

const startBin = Math.ceil(startFreq / deltaF);
const endBin = Math.floor(endFreq / deltaF);

if (startBin >= rawFFTValues.length) {
break;
}

for (let j = startBin; j <= endBin && j < rawFFTValues.length; j++) {
logBinValues[i] += rawFFTValues[j];
}
logBinValues[i] /= endBin - startBin + 1;
}

return logBinValues;
}
Loading