arduino-audio-tools
Loading...
Searching...
No Matches
FrequencyDetectorAutoCorrelation Class Reference

Detects frequency using autocorrelation on audio samples. More...

#include <FrequencyDetectorAutoCorrelation.h>

Inheritance diagram for FrequencyDetectorAutoCorrelation:
AudioStream BaseStream AudioInfoSupport AudioInfoSource BaseStream AudioInfoSupport AudioInfoSource Stream Stream Stream Stream Print Print Print Print Print Print Print Print

Public Member Functions

 FrequencyDetectorAutoCorrelation ()=default
 Default constructor. The buffer size is auto-derived from the AudioInfo passed to begin() unless setBufferSize() is called first.
 FrequencyDetectorAutoCorrelation (int bufferSize)
 Construct with buffer size.
 FrequencyDetectorAutoCorrelation (int bufferSize, Print &out)
 Construct with buffer size and output stream.
 FrequencyDetectorAutoCorrelation (int bufferSize, Stream &in)
 Construct with buffer size and input stream.
virtual void addNotifyAudioChange (AudioInfoSupport &bi)
 Adds target to be notified about audio changes.
virtual void addNotifyAudioChange (AudioInfoSupport &bi)
 Adds target to be notified about audio changes.
virtual AudioInfo audioInfo () override
 provides the actual input AudioInfo
virtual AudioInfo audioInfo () override
 provides the actual input AudioInfo
virtual AudioInfo audioInfoOut ()
virtual AudioInfo audioInfoOut ()
int available () override
 Returns the number of bytes available for reading.
int availableForWrite () override
 Returns the number of bytes available for writing.
bool begin ()
 Initialize internal buffers based on audio info.
bool begin (AudioInfo info)
 Initialize with audio configuration.
virtual void clearNotifyAudioChange ()
 Deletes all change notify subscriptions.
virtual void clearNotifyAudioChange ()
 Deletes all change notify subscriptions.
float confidence (int channel)
 Returns a tonality/periodicity confidence for the given channel, in the range 0.0 (no periodic structure - noise-like) to 1.0 (strongly periodic - tone/voiced/music-like). This is the normalized autocorrelation peak (peak correlation at the detected lag, divided by the signal energy at lag 0) and can be used to distinguish genuine tonal audio from broadband noise that merely happens to be loud.
AudioInfo defaultConfig ()
 Returns a default AudioInfo configuration.
virtual void end ()
virtual void end ()
virtual void flush () override
virtual void flush () override
float frequency (int channel)
 Returns the last detected frequency for the given channel.
bool isNotifyActive ()
 Checks if the automatic AudioInfo update is active.
bool isNotifyActive ()
 Checks if the automatic AudioInfo update is active.
bool isTonal (int channel, float threshold=0.3f)
 Convenience check: is the given channel currently tonal (periodic) rather than noise-like, based on confidence().
virtual operator bool ()
virtual operator bool ()
size_t readBytes (uint8_t *data, size_t len) override
 Reads bytes from the input stream and processes them for frequency detection.
virtual size_t readSilence (uint8_t *buffer, size_t length)
 Source to generate silence: just sets the buffer to 0.
virtual size_t readSilence (uint8_t *buffer, size_t length)
 Source to generate silence: just sets the buffer to 0.
virtual bool removeNotifyAudioChange (AudioInfoSupport &bi)
 Removes a target in order not to be notified about audio changes.
virtual bool removeNotifyAudioChange (AudioInfoSupport &bi)
 Removes a target in order not to be notified about audio changes.
virtual void setAudioInfo (AudioInfo newInfo) override
 Defines the input AudioInfo.
virtual void setAudioInfo (AudioInfo newInfo) override
 Defines the input AudioInfo.
void setBufferSize (int bufferSize)
 Sets the analysis buffer size explicitly (in samples). If not called, begin() derives a size that covers the lowest detectable frequency (50Hz) for the configured sample rate.
void setFrequencyCallback (void(*callback)(int channel, float freq))
 Sets a callback function to be called when a new frequency is detected.
void setNotifyActive (bool flag)
 Deactivate/Reactivate automatic AudioInfo updates: (default is active).
void setNotifyActive (bool flag)
 Deactivate/Reactivate automatic AudioInfo updates: (default is active).
void setWriteBufferSize (int size)
void setWriteBufferSize (int size)
virtual size_t write (uint8_t ch) override
virtual size_t write (const uint8_t *data, size_t len) override
 Writes bytes to the output stream and processes them for frequency detection.
virtual void writeSilence (size_t len)
 Writes len bytes of silence (=0).
virtual void writeSilence (size_t len)
 Writes len bytes of silence (=0).

Protected Member Functions

template<class T>
void detect (T *samples, size_t len)
 Detects frequency for all channels using autocorrelation.
template<class T>
float detectFrequencyForChannel (int ch, T *samples, size_t len, float &confidenceOut)
 Performs autocorrelation to estimate frequency for a single channel.
virtual int not_supported (int out, const char *msg="")
virtual int not_supported (int out, const char *msg="")
void notifyAudioChange (AudioInfo info)
void notifyAudioChange (AudioInfo info)
void refillReadBuffer ()
 Refill small read buffer (e.g. 8 bytes) to avoid single byte reads when calling read().
void refillReadBuffer ()
 Refill small read buffer (e.g. 8 bytes) to avoid single byte reads when calling read().

Protected Attributes

int _timeout = 10
SingleBuffer< uint8_t > buffer
 Buffer for incoming audio data.
int buffer_size = 0
 Buffer size in samples.
Vector< float > conf
 Stores tonality confidence (0-1) for each channel.
Vector< float > freq
 Stores detected frequency for each channel.
void(* freq_callback )(int channel, float freq)
 Frequency callback function.
AudioInfo info
bool is_notify_active = true
Vector< AudioInfoSupport * > notify_vector
Stream * p_in = nullptr
 Input stream pointer.
Print * p_out = nullptr
 Output stream pointer.
RingBuffer< uint8_t > tmp_in {0}
RingBuffer< uint8_t > tmp_out {0}
int write_buffer_size = 8

Detailed Description

Detects frequency using autocorrelation on audio samples.

This class analyzes audio data to estimate the dominant frequency by applying the autocorrelation method. It supports multiple audio channels and different sample formats (16, 24, 32 bits).

Usage:

  • Feed audio data via write() or readBytes().
  • Call frequency(channel) to get the detected frequency for a channel.
  • Optionally, set a callback to be notified when a new frequency is detected.

Based on: https://github.com/akellyirl/AutoCorr_Freq_detect

Constructor & Destructor Documentation

◆ FrequencyDetectorAutoCorrelation() [1/4]

FrequencyDetectorAutoCorrelation ( )
default

Default constructor. The buffer size is auto-derived from the AudioInfo passed to begin() unless setBufferSize() is called first.

◆ FrequencyDetectorAutoCorrelation() [2/4]

FrequencyDetectorAutoCorrelation ( int bufferSize)
inline

Construct with buffer size.

Parameters
bufferSizeNumber of samples to buffer for analysis.

◆ FrequencyDetectorAutoCorrelation() [3/4]

FrequencyDetectorAutoCorrelation ( int bufferSize,
Print & out )
inline

Construct with buffer size and output stream.

Parameters
bufferSizeNumber of samples to buffer for analysis.
outOutput stream for writing audio data.

◆ FrequencyDetectorAutoCorrelation() [4/4]

FrequencyDetectorAutoCorrelation ( int bufferSize,
Stream & in )
inline

Construct with buffer size and input stream.

Parameters
bufferSizeNumber of samples to buffer for analysis.
inInput stream for reading audio data.

Member Function Documentation

◆ addNotifyAudioChange() [1/2]

virtual void addNotifyAudioChange ( AudioInfoSupport & bi)
inlinevirtualinherited

Adds target to be notified about audio changes.

Reimplemented in CodecNOP, CodecNOP, EncodedAudioOutput, and EncodedAudioStream.

◆ addNotifyAudioChange() [2/2]

virtual void addNotifyAudioChange ( AudioInfoSupport & bi)
inlinevirtualinherited

Adds target to be notified about audio changes.

Reimplemented in CodecNOP, CodecNOP, EncodedAudioOutput, and EncodedAudioStream.

◆ audioInfo() [1/2]

◆ audioInfo() [2/2]

◆ audioInfoOut() [1/2]

◆ audioInfoOut() [2/2]

◆ available()

int available ( )
inlineoverridevirtual

Returns the number of bytes available for reading.

Reimplemented from BaseStream.

◆ availableForWrite()

int availableForWrite ( )
inlineoverridevirtual

Returns the number of bytes available for writing.

Reimplemented from BaseStream.

◆ begin() [1/2]

bool begin ( )
inlinevirtual

Initialize internal buffers based on audio info.

Returns
true if initialization succeeded.

Reimplemented from BaseStream.

◆ begin() [2/2]

bool begin ( AudioInfo info)
inline

Initialize with audio configuration.

Parameters
infoAudioInfo structure describing the audio format.
Returns
true if initialization succeeded.

◆ clearNotifyAudioChange() [1/2]

virtual void clearNotifyAudioChange ( )
inlinevirtualinherited

◆ clearNotifyAudioChange() [2/2]

virtual void clearNotifyAudioChange ( )
inlinevirtualinherited

◆ confidence()

float confidence ( int channel)
inline

Returns a tonality/periodicity confidence for the given channel, in the range 0.0 (no periodic structure - noise-like) to 1.0 (strongly periodic - tone/voiced/music-like). This is the normalized autocorrelation peak (peak correlation at the detected lag, divided by the signal energy at lag 0) and can be used to distinguish genuine tonal audio from broadband noise that merely happens to be loud.

Parameters
channelChannel index.
Returns
Confidence in [0.0, 1.0], or 0 for an invalid channel.

◆ defaultConfig()

AudioInfo defaultConfig ( )
inline

Returns a default AudioInfo configuration.

◆ detect()

template<class T>
void detect ( T * samples,
size_t len )
inlineprotected

Detects frequency for all channels using autocorrelation.

Template Parameters
TSample type (int16_t, int24_t, int32_t)
Parameters
samplesPointer to audio samples.
lenNumber of samples.

◆ detectFrequencyForChannel()

template<class T>
float detectFrequencyForChannel ( int ch,
T * samples,
size_t len,
float & confidenceOut )
inlineprotected

Performs autocorrelation to estimate frequency for a single channel.

Template Parameters
TSample type.
Parameters
chChannel index.
samplesPointer to audio samples.
lenNumber of samples.
confidenceOutSet to the normalized autocorrelation peak (0.0-1.0): how periodic/tonal the block is, independent of its loudness. Values near 0 indicate noise-like (non-periodic) content; values near 1 indicate a strong tone/voiced/harmonic signal.
Returns
Detected frequency in Hz.

◆ end() [1/2]

virtual void end ( )
inlinevirtualinherited

Reimplemented in A2DPStream, AbstractURLStream, AdapterAudioOutputToAudioStream, AdaptiveResamplingStream, AnalogAudioStream, AdapterAudioOutputToAudioStream, AudioStreamWrapper, AudioStreamWrapper, CallbackStream, CallbackStream, CatStream, CatStream, DynamicMemoryStream, DynamicMemoryStream, EncodedAudioStream, FilteredStream< T, TF >, FilteredStream< T, TF >, FilteredStream< int16_t, int16_t >, GeneratedSoundStream< T >, GeneratedSoundStream< T >, GeneratedSoundStream< int16_t >, InputMerge< T >, InputMerge< T >, InputMixer< T, SumT >, InputMixer< T, SumT >, MemoryStream, MemoryStream, QueueStream< T >, QueueStream< T >, QueueStream< uint8_t >, ReformatBaseStream, TimerCallbackAudioStream, TimerCallbackAudioStream, AudioBLEClient, AudioBLEClient, AudioBLEServer, AudioBLEServer, AudioBLEStream, AudioEffectStream, AudioEffectStreamT< T >, AudioFFTBase, AudioKitStream, AudioLoRa, AudioMP34DT05, AudioStreamWrapper, AutomaticGainControlStream, BufferedTaskStream, CallbackStream, CatStream, ChannelFormatConverterStream, DynamicMemoryStream, EncodedAudioStream, Equalizer3BandsPerChannelT< T >, Equalizer3BandsPerChannelT< float >, Equalizer3BandsT< T >, Equalizer3BandsT< float >, EqualizerNBands< SampleT, AccT, NUM_TAPS, NUM_BANDS >, ESPNowStream, FaustStream< DSP >, FileLoopT< FileType >, FileLoopT< File >, FilteredStream< T, TF >, FormatConverterStream, GeneratedSoundStream< T >, GoertzelStream, HLSStreamT< URLStream >, HLSStreamT< URLStreamESP32 >, HttpRequest, I2SCodecStream, I2SStream, ICYStreamT< T >, ICYStreamT< URLStream >, ICYStreamT< URLStreamESP32 >, InputMerge< T >, InputMixer< T, SumT >, MemoryStream, MiniAudioStream, MozziStream, NRF24Stream, NumberFormatConverterStream, Pipeline, Pipeline::ModifyingStreamAdapter, PortAudioStream, PureDataStream, QueueStream< T >, ReformatBaseStream, SPDIFOutput, SPIAudioSlave, StdioStream, SupportedRatesStream, TimerCallbackAudioStream, URLStream, URLStreamBufferedT< T >, URLStreamBufferedT< ICYStream >, URLStreamBufferedT< ICYStreamESP32 >, URLStreamBufferedT< URLStream >, URLStreamBufferedT< URLStreamESP32 >, URLStreamESP32, USBAudioDeviceBase, USBAudioHostBase, VolumeStream, VS1053Stream, and WM8960Stream.

◆ end() [2/2]

virtual void end ( )
inlinevirtualinherited

Reimplemented in A2DPStream, AbstractURLStream, AdapterAudioOutputToAudioStream, AdaptiveResamplingStream, AnalogAudioStream, AdapterAudioOutputToAudioStream, AudioStreamWrapper, AudioStreamWrapper, CallbackStream, CallbackStream, CatStream, CatStream, DynamicMemoryStream, DynamicMemoryStream, EncodedAudioStream, FilteredStream< T, TF >, FilteredStream< T, TF >, FilteredStream< int16_t, int16_t >, GeneratedSoundStream< T >, GeneratedSoundStream< T >, GeneratedSoundStream< int16_t >, InputMerge< T >, InputMerge< T >, InputMixer< T, SumT >, InputMixer< T, SumT >, MemoryStream, MemoryStream, QueueStream< T >, QueueStream< T >, QueueStream< uint8_t >, ReformatBaseStream, TimerCallbackAudioStream, TimerCallbackAudioStream, AudioBLEClient, AudioBLEClient, AudioBLEServer, AudioBLEServer, AudioBLEStream, AudioEffectStream, AudioEffectStreamT< T >, AudioFFTBase, AudioKitStream, AudioLoRa, AudioMP34DT05, AudioStreamWrapper, AutomaticGainControlStream, BufferedTaskStream, CallbackStream, CatStream, ChannelFormatConverterStream, DynamicMemoryStream, EncodedAudioStream, Equalizer3BandsPerChannelT< T >, Equalizer3BandsPerChannelT< float >, Equalizer3BandsT< T >, Equalizer3BandsT< float >, EqualizerNBands< SampleT, AccT, NUM_TAPS, NUM_BANDS >, ESPNowStream, FaustStream< DSP >, FileLoopT< FileType >, FileLoopT< File >, FilteredStream< T, TF >, FormatConverterStream, GeneratedSoundStream< T >, GoertzelStream, HLSStreamT< URLStream >, HLSStreamT< URLStreamESP32 >, HttpRequest, I2SCodecStream, I2SStream, ICYStreamT< T >, ICYStreamT< URLStream >, ICYStreamT< URLStreamESP32 >, InputMerge< T >, InputMixer< T, SumT >, MemoryStream, MiniAudioStream, MozziStream, NRF24Stream, NumberFormatConverterStream, Pipeline, Pipeline::ModifyingStreamAdapter, PortAudioStream, PureDataStream, QueueStream< T >, ReformatBaseStream, SPDIFOutput, SPIAudioSlave, StdioStream, SupportedRatesStream, TimerCallbackAudioStream, URLStream, URLStreamBufferedT< T >, URLStreamBufferedT< ICYStream >, URLStreamBufferedT< ICYStreamESP32 >, URLStreamBufferedT< URLStream >, URLStreamBufferedT< URLStreamESP32 >, URLStreamESP32, USBAudioDeviceBase, USBAudioHostBase, VolumeStream, VS1053Stream, and WM8960Stream.

◆ flush() [1/2]

◆ flush() [2/2]

◆ frequency()

float frequency ( int channel)
inline

Returns the last detected frequency for the given channel.

Parameters
channelChannel index.
Returns
Detected frequency in Hz, or 0 if invalid channel.

◆ isNotifyActive() [1/2]

bool isNotifyActive ( )
inlineinherited

Checks if the automatic AudioInfo update is active.

◆ isNotifyActive() [2/2]

bool isNotifyActive ( )
inlineinherited

Checks if the automatic AudioInfo update is active.

◆ isTonal()

bool isTonal ( int channel,
float threshold = 0.3f )
inline

Convenience check: is the given channel currently tonal (periodic) rather than noise-like, based on confidence().

Parameters
channelChannel index.
thresholdMinimum confidence to be considered tonal (default 0.3).

◆ not_supported() [1/2]

virtual int not_supported ( int out,
const char * msg = "" )
inlineprotectedvirtualinherited

◆ not_supported() [2/2]

virtual int not_supported ( int out,
const char * msg = "" )
inlineprotectedvirtualinherited

◆ notifyAudioChange() [1/2]

void notifyAudioChange ( AudioInfo info)
inlineprotectedinherited

◆ notifyAudioChange() [2/2]

void notifyAudioChange ( AudioInfo info)
inlineprotectedinherited

◆ operator bool() [1/2]

◆ operator bool() [2/2]

◆ readBytes()

size_t readBytes ( uint8_t * data,
size_t len )
inlineoverridevirtual

Reads bytes from the input stream and processes them for frequency detection.

Parameters
dataBuffer to store read bytes.
lenNumber of bytes to read.
Returns
Number of bytes actually read.

Reimplemented from AudioStream.

◆ readSilence() [1/2]

virtual size_t readSilence ( uint8_t * buffer,
size_t length )
inlinevirtualinherited

Source to generate silence: just sets the buffer to 0.

◆ readSilence() [2/2]

virtual size_t readSilence ( uint8_t * buffer,
size_t length )
inlinevirtualinherited

Source to generate silence: just sets the buffer to 0.

◆ refillReadBuffer() [1/2]

void refillReadBuffer ( )
inlineprotectedinherited

Refill small read buffer (e.g. 8 bytes) to avoid single byte reads when calling read().

◆ refillReadBuffer() [2/2]

void refillReadBuffer ( )
inlineprotectedinherited

Refill small read buffer (e.g. 8 bytes) to avoid single byte reads when calling read().

◆ removeNotifyAudioChange() [1/2]

virtual bool removeNotifyAudioChange ( AudioInfoSupport & bi)
inlinevirtualinherited

Removes a target in order not to be notified about audio changes.

◆ removeNotifyAudioChange() [2/2]

virtual bool removeNotifyAudioChange ( AudioInfoSupport & bi)
inlinevirtualinherited

Removes a target in order not to be notified about audio changes.

◆ setAudioInfo() [1/2]

◆ setAudioInfo() [2/2]

◆ setBufferSize()

void setBufferSize ( int bufferSize)
inline

Sets the analysis buffer size explicitly (in samples). If not called, begin() derives a size that covers the lowest detectable frequency (50Hz) for the configured sample rate.

◆ setFrequencyCallback()

void setFrequencyCallback ( void(* callback )(int channel, float freq))
inline

Sets a callback function to be called when a new frequency is detected.

Parameters
callbackFunction pointer: void callback(int channel, float freq)

◆ setNotifyActive() [1/2]

void setNotifyActive ( bool flag)
inlineinherited

Deactivate/Reactivate automatic AudioInfo updates: (default is active).

◆ setNotifyActive() [2/2]

void setNotifyActive ( bool flag)
inlineinherited

Deactivate/Reactivate automatic AudioInfo updates: (default is active).

◆ setWriteBufferSize() [1/2]

void setWriteBufferSize ( int size)
inlineinherited

◆ setWriteBufferSize() [2/2]

void setWriteBufferSize ( int size)
inlineinherited

◆ write() [1/2]

◆ write() [2/2]

virtual size_t write ( const uint8_t * data,
size_t len )
inlineoverridevirtual

Writes bytes to the output stream and processes them for frequency detection.

Parameters
dataBuffer containing audio data.
lenNumber of bytes to write.
Returns
Number of bytes actually written.

Reimplemented from AudioStream.

◆ writeSilence() [1/2]

virtual void writeSilence ( size_t len)
inlinevirtualinherited

Writes len bytes of silence (=0).

◆ writeSilence() [2/2]

virtual void writeSilence ( size_t len)
inlinevirtualinherited

Writes len bytes of silence (=0).

Member Data Documentation

◆ _timeout

int _timeout = 10
protectedinherited

◆ buffer

SingleBuffer<uint8_t> buffer
protected

Buffer for incoming audio data.

◆ buffer_size

int buffer_size = 0
protected

Buffer size in samples.

◆ conf

Vector<float> conf
protected

Stores tonality confidence (0-1) for each channel.

◆ freq

Vector<float> freq
protected

Stores detected frequency for each channel.

◆ freq_callback

void(* freq_callback) (int channel, float freq)
protected

Frequency callback function.

◆ info

AudioInfo info
protectedinherited

◆ is_notify_active

bool is_notify_active = true
protectedinherited

◆ notify_vector

Vector< AudioInfoSupport * > notify_vector
protectedinherited

◆ p_in

Stream* p_in = nullptr
protected

Input stream pointer.

◆ p_out

Print* p_out = nullptr
protected

Output stream pointer.

◆ tmp_in

RingBuffer< uint8_t > tmp_in {0}
protectedinherited

◆ tmp_out

RingBuffer< uint8_t > tmp_out {0}
protectedinherited

◆ write_buffer_size

int write_buffer_size = 8
protectedinherited

The documentation for this class was generated from the following file: