arduino-audio-tools
All Classes Namespaces Files Functions Variables Typedefs Enumerations Friends Macros Modules Pages
Public Member Functions | Protected Member Functions | Protected Attributes | List of all members
GoertzelStream Class Reference

AudioStream implementation that processes audio data through Goertzel algorithm. This class acts as a passthrough filter that can detect specific frequencies in the audio stream. More...

#include <GoerzelStream.h>

Inheritance diagram for GoertzelStream:
AudioStream BaseStream AudioInfoSupport AudioInfoSource Stream Print

Public Member Functions

virtual void addNotifyAudioChange (AudioInfoSupport &bi)
 Adds target to be notified about audio changes.
 
virtual AudioInfo audioInfo () override
 provides the actual input AudioInfo
 
virtual AudioInfo audioInfoOut ()
 
virtual int available () override
 
virtual int availableForWrite () override
 
bool begin ()
 Initialize detectors for all channels.
 
bool begin (const GoertzelConfig &config)
 Initialize with GoertzelConfig.
 
virtual void clearNotifyAudioChange ()
 Deletes all change notify subscriptions.
 
virtual void end ()
 
virtual void flush () override
 
const GoertzelConfiggetConfig () const
 Get the current configuration.
 
float getCurrentMagnitude (int channel=0)
 Get the current magnitude for frequency detection.
 
bool isFrequencyDetected (int channel=0)
 Check if frequency is currently detected.
 
bool isNotifyActive ()
 Checks if the automatic AudioInfo update is active.
 
virtual operator bool ()
 
size_t readBytes (uint8_t *data, size_t len) override
 Read data from input stream and process it.
 
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.
 
void setAudioInfo (AudioInfo info) override
 Set audio format and initialize detector array.
 
void setChannelDetectionCallback (void(*callback)(int channel, float frequency, float magnitude, void *ref))
 Set detection callback function for channel-aware frequency detection.
 
void setNotifyActive (bool flag)
 Deactivate/Reactivate automatic AudioInfo updates: (default is active)
 
void setOutput (Print &out)
 Defines/Changes the output target.
 
void setReference (void *ref)
 Set reference pointer for callback context.
 
void setStream (Stream &in)
 Defines/Changes the input & output.
 
void setWriteBufferSize (int size)
 
size_t write (const uint8_t *data, size_t len) override
 Process audio data and pass it through.
 
virtual size_t write (uint8_t ch) override
 
virtual void writeSilence (size_t len)
 Writes len bytes of silence (=0).
 

Protected Member Functions

void checkDetection (int channel)
 Helper method to check detection and call callback.
 
float clip (float value)
 Clip audio values to prevent overflow.
 
virtual int not_supported (int out, const char *msg="")
 
void notifyAudioChange (AudioInfo info)
 
void processSamples (const uint8_t *data, size_t data_len)
 Generic sample processing method for both write and readBytes.
 
template<typename T >
void processSamplesOfType (const uint8_t *data, size_t data_len, int channels)
 Template helper to process samples of a specific type.
 
void refillReadBuffer ()
 

Protected Attributes

int _timeout = 10
 
void(* channel_detection_callback )(int channel, float frequency, float magnitude, void *ref) = nullptr
 User callback for detection events.
 
Vector< GoertzelDetectordetectors
 One detector per audio channel.
 
AudioInfo info
 
bool is_notify_active = true
 
Vector< AudioInfoSupport * > notify_vector
 
Printp_print = nullptr
 Output stream for writing audio data.
 
Streamp_stream = nullptr
 Input stream for reading audio data.
 
void * ref = this
 User-defined reference for callback context.
 
GoertzelConfig single_config
 Current algorithm configuration.
 
RingBuffer< uint8_t > tmp_in {0}
 
RingBuffer< uint8_t > tmp_out {0}
 
int write_buffer_size = MAX_SINGLE_CHARS
 

Detailed Description

AudioStream implementation that processes audio data through Goertzel algorithm. This class acts as a passthrough filter that can detect specific frequencies in the audio stream.

Supports multiple channels with independent frequency detection per channel. The number of detectors is determined by the channels field in GoertzelConfig.

Supports multiple sample formats:

Use this class in combination with a MultiStream to detect multiple frequencies.

Author
pschatzmann

Member Function Documentation

◆ addNotifyAudioChange()

virtual void addNotifyAudioChange ( AudioInfoSupport bi)
inlinevirtualinherited

◆ audioInfo()

virtual AudioInfo audioInfo ( )
inlineoverridevirtualinherited

◆ audioInfoOut()

virtual AudioInfo audioInfoOut ( )
inlinevirtualinherited

◆ available()

virtual int available ( )
inlineoverridevirtualinherited

◆ availableForWrite()

virtual int availableForWrite ( )
inlineoverridevirtualinherited

◆ begin() [1/2]

bool begin ( )
inlinevirtual

Initialize detectors for all channels.

Creates and configures individual Goertzel detectors for each audio channel. Each detector will independently analyze its channel for the target frequency.

Returns
true if at least one channel is configured, false otherwise

Reimplemented from BaseStream.

◆ begin() [2/2]

bool begin ( const GoertzelConfig config)
inline

Initialize with GoertzelConfig.

Sets up the stream with specific Goertzel algorithm parameters. This method configures the audio format and detection parameters in one call.

Parameters
configConfiguration object containing all parameters
Returns
true if initialization successful, false otherwise

◆ checkDetection()

void checkDetection ( int  channel)
inlineprotected

Helper method to check detection and call callback.

Examines the magnitude from a detector and triggers the user callback if the magnitude exceeds the configured threshold. This method is called after each complete block is processed.

Parameters
channelChannel index that completed a detection block

◆ clip()

float clip ( float  value)
inlineprotected

Clip audio values to prevent overflow.

Ensures that normalized audio samples stay within the valid range of [-1.0, 1.0] to prevent algorithm instability.

Parameters
valueInput audio sample value
Returns
Clipped value in range [-1.0, 1.0]

◆ end()

virtual void end ( )
inlinevirtualinherited

◆ flush()

virtual void flush ( )
inlineoverridevirtualinherited

Reimplemented from Print.

Reimplemented in ResampleStream, BufferedTaskStream, and BufferedStream.

◆ getConfig()

const GoertzelConfig & getConfig ( ) const
inline

Get the current configuration.

Returns a reference to the current Goertzel configuration, including audio format, detection parameters, and processing settings.

Returns
Reference to the current GoertzelConfig

◆ getCurrentMagnitude()

float getCurrentMagnitude ( int  channel = 0)
inline

Get the current magnitude for frequency detection.

Returns the most recent magnitude calculation for the specified channel. The magnitude represents the strength of the target frequency in the last processed block of samples.

Parameters
channelChannel index (0-based, default: 0 for mono)
Returns
Magnitude value (0.0 if channel invalid or no detection)

◆ isFrequencyDetected()

bool isFrequencyDetected ( int  channel = 0)
inline

Check if frequency is currently detected.

Compares the current magnitude against the configured threshold to determine if the target frequency is present on the specified channel.

Parameters
channelChannel index (0-based, default: 0 for mono)
Returns
true if frequency detected above threshold, false otherwise

◆ operator bool()

virtual operator bool ( )
inlinevirtualinherited

Reimplemented in A2DPStream, I2SStream, MemoryStream, and Pipeline.

◆ processSamples()

void processSamples ( const uint8_t *  data,
size_t  data_len 
)
inlineprotected

Generic sample processing method for both write and readBytes.

This method serves as the central dispatcher for audio sample processing. It examines the configured sample format and routes the data to the appropriate type-specific processing method. This approach eliminates code duplication between write() and readBytes() methods.

Supported formats:

  • 8-bit: Unsigned samples (0-255)
  • 16-bit: Signed samples (-32768 to 32767)
  • 24-bit: Signed samples in 3-byte packed format
  • 32-bit: Signed samples (-2^31 to 2^31-1)
Parameters
dataRaw audio data buffer
data_lenLength of data buffer in bytes

◆ processSamplesOfType()

template<typename T >
void processSamplesOfType ( const uint8_t *  data,
size_t  data_len,
int  channels 
)
inlineprotected

Template helper to process samples of a specific type.

Converts audio samples from their native format to normalized floats, applies volume scaling, and feeds them to the appropriate channel detectors. This method handles the format conversion and channel distribution automatically.

Template Parameters
TSample data type (uint8_t, int16_t, int24_t, int32_t)
Parameters
dataRaw audio data buffer
data_lenLength of data buffer in bytes
channelsNumber of audio channels (for sample distribution)

◆ readBytes()

size_t readBytes ( uint8_t *  data,
size_t  len 
)
inlineoverridevirtual

Read data from input stream and process it.

Reads audio data from the input stream, processes it through the Goertzel detectors for frequency analysis, and returns the data to the caller. This allows for frequency detection in pull-mode audio processing.

Parameters
dataOutput buffer to store read data
lenMaximum number of bytes to read
Returns
Number of bytes actually read

Reimplemented from AudioStream.

◆ setAudioInfo()

void setAudioInfo ( AudioInfo  info)
inlineoverridevirtual

Set audio format and initialize detector array.

This method is called when the audio format changes. It updates the internal configuration and resizes the detector array to match the number of audio channels.

Parameters
infoAudio format information (sample rate, channels, bits per sample)

Reimplemented from AudioStream.

◆ setChannelDetectionCallback()

void setChannelDetectionCallback ( void(*)(int channel, float frequency, float magnitude, void *ref callback)
inline

Set detection callback function for channel-aware frequency detection.

Registers a callback function that will be called when the target frequency is detected on any channel. The callback receives the channel number, detected frequency, magnitude, and a user reference pointer.

Parameters
callbackFunction to call when frequency is detected, includes channel info

◆ setReference()

void setReference ( void *  ref)
inline

Set reference pointer for callback context.

Defines a reference to any object that should be available in the detection callback. This allows the callback to access application context or other objects.

Parameters
refPointer to user-defined context object

◆ write() [1/2]

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

Process audio data and pass it through.

This method receives audio data, processes it through the Goertzel detectors for frequency analysis, and then passes the unmodified data to the output stream. This allows for real-time frequency detection without affecting the audio flow.

Parameters
dataInput audio data buffer
lenLength of data in bytes
Returns
Number of bytes written to output stream

If there is no output stream, we just return the length

Reimplemented from AudioStream.

◆ write() [2/2]

virtual size_t write ( uint8_t  ch)
inlineoverridevirtualinherited

Reimplemented in BufferedTaskStream, and BufferedStream.


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