diff --git a/ports/raspberrypi/boards/pimoroni_pico_dv_base_w/mpconfigboard.mk b/ports/raspberrypi/boards/pimoroni_pico_dv_base_w/mpconfigboard.mk index 016dd0d7269..02cbe3b69b7 100644 --- a/ports/raspberrypi/boards/pimoroni_pico_dv_base_w/mpconfigboard.mk +++ b/ports/raspberrypi/boards/pimoroni_pico_dv_base_w/mpconfigboard.mk @@ -19,6 +19,7 @@ CIRCUITPY_SOCKETPOOL = 1 CIRCUITPY_WIFI = 1 CIRCUITPY_PICODVI = 1 +CIRCUITPY_AUDIOEFFECTS = 0 CIRCUITPY_AUDIOFILEWRITER = 0 CIRCUITPY_BLEIO_HCI = 0 diff --git a/ports/unix/variants/coverage/mpconfigvariant.mk b/ports/unix/variants/coverage/mpconfigvariant.mk index 682fe77459e..0dd93b25cf4 100644 --- a/ports/unix/variants/coverage/mpconfigvariant.mk +++ b/ports/unix/variants/coverage/mpconfigvariant.mk @@ -39,6 +39,7 @@ SRC_BITMAP := \ shared-bindings/audiodelays/PitchShift.c \ shared-bindings/audiodelays/GranularPitchShift.c \ shared-bindings/audiodelays/MultiTapDelay.c \ + shared-bindings/audiodelays/Flanger.c \ shared-bindings/audiodelays/__init__.c \ shared-bindings/audiofilters/Distortion.c \ shared-bindings/audiofilters/Filter.c \ @@ -88,6 +89,7 @@ SRC_BITMAP := \ shared-module/audiodelays/PitchShift.c \ shared-module/audiodelays/GranularPitchShift.c \ shared-module/audiodelays/MultiTapDelay.c \ + shared-module/audiodelays/Flanger.c \ shared-module/audiodelays/__init__.c \ shared-module/audiofilters/Distortion.c \ shared-module/audiofilters/Filter.c \ diff --git a/py/circuitpy_defns.mk b/py/circuitpy_defns.mk index 7dfb9ae7c7d..b40efc561a1 100644 --- a/py/circuitpy_defns.mk +++ b/py/circuitpy_defns.mk @@ -712,6 +712,7 @@ SRC_SHARED_MODULE_ALL = \ audiospeed/__init__.c \ audiodelays/Echo.c \ audiodelays/Chorus.c \ + audiodelays/Flanger.c \ audiodelays/PitchShift.c \ audiodelays/GranularPitchShift.c \ audiodelays/MultiTapDelay.c \ diff --git a/shared-bindings/audiodelays/Flanger.c b/shared-bindings/audiodelays/Flanger.c new file mode 100644 index 00000000000..7c16e164944 --- /dev/null +++ b/shared-bindings/audiodelays/Flanger.c @@ -0,0 +1,389 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Tim Cocks for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include + +#include "shared-bindings/audiodelays/Flanger.h" +#include "shared-module/audiodelays/Flanger.h" +#include "shared-bindings/audiocore/__init__.h" + +#include "shared/runtime/context_manager_helpers.h" +#include "py/binary.h" +#include "py/objproperty.h" +#include "py/runtime.h" +#include "shared-bindings/util.h" +#include "shared-module/synthio/block.h" + +//| class Flanger: +//| """A Flanger effect""" +//| +//| def __init__( +//| self, +//| max_delay_ms: int = 10, +//| min_delay_ms: synthio.BlockInput = 1.0, +//| rate: synthio.BlockInput = 0.5, +//| depth: synthio.BlockInput = 0.5, +//| feedback: synthio.BlockInput = 0.5, +//| mix: synthio.BlockInput = 0.5, +//| invert: bool = False, +//| buffer_size: int = 512, +//| sample_rate: int = 8000, +//| bits_per_sample: int = 16, +//| samples_signed: bool = True, +//| channel_count: int = 1, +//| ) -> None: +//| """Create a Flanger effect by mixing the sample with a copy of itself taken from a very +//| short delay whose length is continuously swept up and down by an internal low frequency +//| oscillator. The moving delay creates a comb filter whose notches sweep through the +//| spectrum, and the ``feedback`` path routes the delayed signal back into the delay line +//| to sharpen those notches into resonant peaks. +//| +//| The delay is swept upwards from ``min_delay_ms`` towards ``max_delay_ms``:: +//| +//| sweep_top = min_delay_ms + depth * (max_delay_ms - min_delay_ms) +//| current_delay = min_delay_ms + triangle_lfo() * (sweep_top - min_delay_ms) +//| +//| where ``triangle_lfo()`` ranges from 0.0 to 1.0 at ``rate`` Hz. Because the sweep runs +//| upwards from a floor rather than around a centre, no combination of ``min_delay_ms`` and +//| ``depth`` can push the delay outside of the buffer. +//| +//| +//| :param int max_delay_ms: The maximum delay the flanger can sweep to in milliseconds, valid range is 1-100. +//| :param synthio.BlockInput min_delay_ms: The shortest delay of the sweep in milliseconds. Clamped between the length of one sample and max_delay_ms. +//| :param synthio.BlockInput rate: The frequency of the sweep in hertz. Clamped between 0.0 and 20.0. A rate of 0.0 holds the delay still. +//| :param synthio.BlockInput depth: How much of the range above min_delay_ms is swept, from 0.0 to 1.0. +//| :param synthio.BlockInput feedback: How much of the delayed signal is fed back into the delay line, from -0.95 to 0.95. Negative values invert the polarity of the feedback. +//| :param synthio.BlockInput mix: How much of the wet audio to include along with the original signal, from 0.0 to 1.0. +//| :param bool invert: Subtract the wet signal from the dry signal instead of adding it, which flips which frequencies cancel. +//| :param int buffer_size: The total size in bytes of each of the two playback buffers to use +//| :param int sample_rate: The sample rate to be used +//| :param int channel_count: The number of channels the source samples contain. 1 = mono; 2 = stereo. +//| :param int bits_per_sample: The bits per sample of the effect +//| :param bool samples_signed: Effect is signed (True) or unsigned (False) +//| +//| Adding a flanger to a synth:: +//| +//| import time +//| import board +//| import audiobusio +//| import synthio +//| import audiodelays +//| +//| audio = audiobusio.I2SOut(board.I2S_BIT_CLOCK, board.I2S_WS, board.I2S_DOUT) +//| synth = synthio.Synthesizer(channel_count=1, sample_rate=44100) +//| flanger = audiodelays.Flanger(max_delay_ms=10, min_delay_ms=1.0, rate=0.3, depth=0.8, +//| feedback=0.7, mix=1.0, buffer_size=1024, +//| channel_count=1, sample_rate=44100) +//| audio.play(flanger.play(synth)) +//| +//| note = synthio.Note(261) +//| while True: +//| synth.press(note) +//| time.sleep(3) +//| synth.release(note) +//| time.sleep(1)""" +//| ... +//| +static mp_obj_t audiodelays_flanger_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *all_args) { + enum { ARG_max_delay_ms, ARG_min_delay_ms, ARG_rate, ARG_depth, ARG_feedback, ARG_mix, ARG_invert, ARG_buffer_size, ARG_sample_rate, ARG_bits_per_sample, ARG_samples_signed, ARG_channel_count, }; + static const mp_arg_t allowed_args[] = { + { MP_QSTR_max_delay_ms, MP_ARG_INT | MP_ARG_KW_ONLY, {.u_int = 10 } }, + { MP_QSTR_min_delay_ms, MP_ARG_OBJ | MP_ARG_KW_ONLY, {.u_obj = MP_OBJ_NULL} }, + { MP_QSTR_rate, MP_ARG_OBJ | MP_ARG_KW_ONLY, {.u_obj = MP_OBJ_NULL} }, + { MP_QSTR_depth, MP_ARG_OBJ | MP_ARG_KW_ONLY, {.u_obj = MP_OBJ_NULL} }, + { MP_QSTR_feedback, MP_ARG_OBJ | MP_ARG_KW_ONLY, {.u_obj = MP_OBJ_NULL} }, + { MP_QSTR_mix, MP_ARG_OBJ | MP_ARG_KW_ONLY, {.u_obj = MP_OBJ_NULL} }, + { MP_QSTR_invert, MP_ARG_BOOL | MP_ARG_KW_ONLY, {.u_bool = false} }, + { MP_QSTR_buffer_size, MP_ARG_INT | MP_ARG_KW_ONLY, {.u_int = 512} }, + { MP_QSTR_sample_rate, MP_ARG_INT | MP_ARG_KW_ONLY, {.u_int = 8000} }, + { MP_QSTR_bits_per_sample, MP_ARG_INT | MP_ARG_KW_ONLY, {.u_int = 16} }, + { MP_QSTR_samples_signed, MP_ARG_BOOL | MP_ARG_KW_ONLY, {.u_bool = true} }, + { MP_QSTR_channel_count, MP_ARG_INT | MP_ARG_KW_ONLY, {.u_int = 1 } }, + }; + + mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)]; + mp_arg_parse_all_kw_array(n_args, n_kw, all_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args); + + mp_int_t max_delay_ms = mp_arg_validate_int_range(args[ARG_max_delay_ms].u_int, 1, 100, MP_QSTR_max_delay_ms); + + mp_int_t channel_count = mp_arg_validate_int_range(args[ARG_channel_count].u_int, 1, 2, MP_QSTR_channel_count); + mp_int_t sample_rate = mp_arg_validate_int_min(args[ARG_sample_rate].u_int, 1, MP_QSTR_sample_rate); + mp_int_t bits_per_sample = args[ARG_bits_per_sample].u_int; + if (bits_per_sample != 8 && bits_per_sample != 16) { + mp_raise_ValueError(MP_ERROR_TEXT("bits_per_sample must be 8 or 16")); + } + + audiodelays_flanger_obj_t *self = mp_obj_malloc(audiodelays_flanger_obj_t, &audiodelays_flanger_type); + common_hal_audiodelays_flanger_construct(self, max_delay_ms, args[ARG_min_delay_ms].u_obj, args[ARG_rate].u_obj, args[ARG_depth].u_obj, args[ARG_feedback].u_obj, args[ARG_mix].u_obj, args[ARG_invert].u_bool, args[ARG_buffer_size].u_int, bits_per_sample, args[ARG_samples_signed].u_bool, channel_count, sample_rate); + + return MP_OBJ_FROM_PTR(self); +} + +//| def deinit(self) -> None: +//| """Deinitialises the Flanger.""" +//| ... +//| +static mp_obj_t audiodelays_flanger_deinit(mp_obj_t self_in) { + audiodelays_flanger_obj_t *self = MP_OBJ_TO_PTR(self_in); + common_hal_audiodelays_flanger_deinit(self); + return mp_const_none; +} +static MP_DEFINE_CONST_FUN_OBJ_1(audiodelays_flanger_deinit_obj, audiodelays_flanger_deinit); + +static void check_for_deinit(audiodelays_flanger_obj_t *self) { + audiosample_check_for_deinit(&self->base); +} + +//| def __enter__(self) -> Flanger: +//| """No-op used by Context Managers.""" +//| ... +//| +// Provided by context manager helper. + +//| def __exit__(self) -> None: +//| """Automatically deinitializes when exiting a context. See +//| :ref:`lifetime-and-contextmanagers` for more info.""" +//| ... +//| +static mp_obj_t audiodelays_flanger_obj___exit__(size_t n_args, const mp_obj_t *args) { + (void)n_args; + common_hal_audiodelays_flanger_deinit(args[0]); + return mp_const_none; +} +static MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(audiodelays_flanger___exit___obj, 4, 4, audiodelays_flanger_obj___exit__); + + +//| min_delay_ms: synthio.BlockInput +//| """The shortest delay of the sweep in milliseconds. This is the floor that the sweep runs +//| upwards from. Clamped between the length of a single sample and ``max_delay_ms``.""" +//| +static mp_obj_t audiodelays_flanger_obj_get_min_delay_ms(mp_obj_t self_in) { + audiodelays_flanger_obj_t *self = MP_OBJ_TO_PTR(self_in); + + return common_hal_audiodelays_flanger_get_min_delay_ms(self); +} +MP_DEFINE_CONST_FUN_OBJ_1(audiodelays_flanger_get_min_delay_ms_obj, audiodelays_flanger_obj_get_min_delay_ms); + +static mp_obj_t audiodelays_flanger_obj_set_min_delay_ms(mp_obj_t self_in, mp_obj_t min_delay_ms_in) { + audiodelays_flanger_obj_t *self = MP_OBJ_TO_PTR(self_in); + common_hal_audiodelays_flanger_set_min_delay_ms(self, min_delay_ms_in); + return mp_const_none; +} +MP_DEFINE_CONST_FUN_OBJ_2(audiodelays_flanger_set_min_delay_ms_obj, audiodelays_flanger_obj_set_min_delay_ms); + +MP_PROPERTY_GETSET(audiodelays_flanger_min_delay_ms_obj, + (mp_obj_t)&audiodelays_flanger_get_min_delay_ms_obj, + (mp_obj_t)&audiodelays_flanger_set_min_delay_ms_obj); + +//| rate: synthio.BlockInput +//| """The frequency of the delay sweep in hertz. Clamped between 0.0 and 20.0. A rate of 0.0 +//| holds the delay still, which leaves a fixed comb filter.""" +//| +static mp_obj_t audiodelays_flanger_obj_get_rate(mp_obj_t self_in) { + return common_hal_audiodelays_flanger_get_rate(self_in); +} +MP_DEFINE_CONST_FUN_OBJ_1(audiodelays_flanger_get_rate_obj, audiodelays_flanger_obj_get_rate); + +static mp_obj_t audiodelays_flanger_obj_set_rate(mp_obj_t self_in, mp_obj_t rate_in) { + audiodelays_flanger_obj_t *self = MP_OBJ_TO_PTR(self_in); + common_hal_audiodelays_flanger_set_rate(self, rate_in); + return mp_const_none; +} +MP_DEFINE_CONST_FUN_OBJ_2(audiodelays_flanger_set_rate_obj, audiodelays_flanger_obj_set_rate); + +MP_PROPERTY_GETSET(audiodelays_flanger_rate_obj, + (mp_obj_t)&audiodelays_flanger_get_rate_obj, + (mp_obj_t)&audiodelays_flanger_set_rate_obj); + +//| depth: synthio.BlockInput +//| """How much of the range between ``min_delay_ms`` and ``max_delay_ms`` the sweep covers, from +//| 0.0 to 1.0. A depth of 0.0 leaves a static short delay.""" +//| +static mp_obj_t audiodelays_flanger_obj_get_depth(mp_obj_t self_in) { + return common_hal_audiodelays_flanger_get_depth(self_in); +} +MP_DEFINE_CONST_FUN_OBJ_1(audiodelays_flanger_get_depth_obj, audiodelays_flanger_obj_get_depth); + +static mp_obj_t audiodelays_flanger_obj_set_depth(mp_obj_t self_in, mp_obj_t depth_in) { + audiodelays_flanger_obj_t *self = MP_OBJ_TO_PTR(self_in); + common_hal_audiodelays_flanger_set_depth(self, depth_in); + return mp_const_none; +} +MP_DEFINE_CONST_FUN_OBJ_2(audiodelays_flanger_set_depth_obj, audiodelays_flanger_obj_set_depth); + +MP_PROPERTY_GETSET(audiodelays_flanger_depth_obj, + (mp_obj_t)&audiodelays_flanger_get_depth_obj, + (mp_obj_t)&audiodelays_flanger_set_depth_obj); + +//| feedback: synthio.BlockInput +//| """How much of the delayed signal is fed back into the delay line, clamped between -0.95 and +//| 0.95. Larger magnitudes give a more resonant, ringing sweep. Negative values invert the +//| polarity of the feedback for the hollower variant.""" +//| +static mp_obj_t audiodelays_flanger_obj_get_feedback(mp_obj_t self_in) { + return common_hal_audiodelays_flanger_get_feedback(self_in); +} +MP_DEFINE_CONST_FUN_OBJ_1(audiodelays_flanger_get_feedback_obj, audiodelays_flanger_obj_get_feedback); + +static mp_obj_t audiodelays_flanger_obj_set_feedback(mp_obj_t self_in, mp_obj_t feedback_in) { + audiodelays_flanger_obj_t *self = MP_OBJ_TO_PTR(self_in); + common_hal_audiodelays_flanger_set_feedback(self, feedback_in); + return mp_const_none; +} +MP_DEFINE_CONST_FUN_OBJ_2(audiodelays_flanger_set_feedback_obj, audiodelays_flanger_obj_set_feedback); + +MP_PROPERTY_GETSET(audiodelays_flanger_feedback_obj, + (mp_obj_t)&audiodelays_flanger_get_feedback_obj, + (mp_obj_t)&audiodelays_flanger_set_feedback_obj); + +//| mix: synthio.BlockInput +//| """How much of the wet audio to include along with the original signal, clamped between 0.0 +//| and 1.0 where 0.0 is only the sample and 1.0 is the full effect.""" +//| +static mp_obj_t audiodelays_flanger_obj_get_mix(mp_obj_t self_in) { + return common_hal_audiodelays_flanger_get_mix(self_in); +} +MP_DEFINE_CONST_FUN_OBJ_1(audiodelays_flanger_get_mix_obj, audiodelays_flanger_obj_get_mix); + +static mp_obj_t audiodelays_flanger_obj_set_mix(mp_obj_t self_in, mp_obj_t mix_in) { + audiodelays_flanger_obj_t *self = MP_OBJ_TO_PTR(self_in); + common_hal_audiodelays_flanger_set_mix(self, mix_in); + return mp_const_none; +} +MP_DEFINE_CONST_FUN_OBJ_2(audiodelays_flanger_set_mix_obj, audiodelays_flanger_obj_set_mix); + +MP_PROPERTY_GETSET(audiodelays_flanger_mix_obj, + (mp_obj_t)&audiodelays_flanger_get_mix_obj, + (mp_obj_t)&audiodelays_flanger_set_mix_obj); + +//| invert: bool +//| """Whether the wet signal is subtracted from the dry signal instead of added to it. This +//| flips which frequencies the comb filter cancels, the same as the polarity switch on a +//| flanger pedal.""" +//| +static mp_obj_t audiodelays_flanger_obj_get_invert(mp_obj_t self_in) { + audiodelays_flanger_obj_t *self = MP_OBJ_TO_PTR(self_in); + return mp_obj_new_bool(common_hal_audiodelays_flanger_get_invert(self)); +} +MP_DEFINE_CONST_FUN_OBJ_1(audiodelays_flanger_get_invert_obj, audiodelays_flanger_obj_get_invert); + +static mp_obj_t audiodelays_flanger_obj_set_invert(mp_obj_t self_in, mp_obj_t invert_in) { + audiodelays_flanger_obj_t *self = MP_OBJ_TO_PTR(self_in); + common_hal_audiodelays_flanger_set_invert(self, mp_obj_is_true(invert_in)); + return mp_const_none; +} +MP_DEFINE_CONST_FUN_OBJ_2(audiodelays_flanger_set_invert_obj, audiodelays_flanger_obj_set_invert); + +MP_PROPERTY_GETSET(audiodelays_flanger_invert_obj, + (mp_obj_t)&audiodelays_flanger_get_invert_obj, + (mp_obj_t)&audiodelays_flanger_set_invert_obj); + +//| lfo_value: float +//| """The current value of the internal LFO that sweeps the delay time, from 0.0 at +//| `min_delay_ms` to 1.0 at the top of the sweep. The LFO only advances while audio is being +//| played. (read-only)""" +//| +static mp_obj_t audiodelays_flanger_obj_get_lfo_value(mp_obj_t self_in) { + audiodelays_flanger_obj_t *self = MP_OBJ_TO_PTR(self_in); + check_for_deinit(self); + return mp_obj_new_float(common_hal_audiodelays_flanger_get_lfo_value(self)); +} +MP_DEFINE_CONST_FUN_OBJ_1(audiodelays_flanger_get_lfo_value_obj, audiodelays_flanger_obj_get_lfo_value); + +MP_PROPERTY_GETTER(audiodelays_flanger_lfo_value_obj, + (mp_obj_t)&audiodelays_flanger_get_lfo_value_obj); + +//| playing: bool +//| """True when the effect is playing a sample. (read-only)""" +//| +static mp_obj_t audiodelays_flanger_obj_get_playing(mp_obj_t self_in) { + audiodelays_flanger_obj_t *self = MP_OBJ_TO_PTR(self_in); + check_for_deinit(self); + return mp_obj_new_bool(common_hal_audiodelays_flanger_get_playing(self)); +} +MP_DEFINE_CONST_FUN_OBJ_1(audiodelays_flanger_get_playing_obj, audiodelays_flanger_obj_get_playing); + +MP_PROPERTY_GETTER(audiodelays_flanger_playing_obj, + (mp_obj_t)&audiodelays_flanger_get_playing_obj); + +//| def play(self, sample: circuitpython_typing.AudioSample, *, loop: bool = False) -> Flanger: +//| """Plays the sample once when loop=False and continuously when loop=True. +//| Does not block. Use `playing` to block. +//| +//| The sample must match the encoding settings given in the constructor. +//| +//| :return: The effect object itself. Can be used for chaining, ie: +//| ``audio.play(effect.play(sample))``. +//| :rtype: Flanger""" +//| ... +//| +static mp_obj_t audiodelays_flanger_obj_play(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { + enum { ARG_sample, ARG_loop }; + static const mp_arg_t allowed_args[] = { + { MP_QSTR_sample, MP_ARG_OBJ | MP_ARG_REQUIRED, {} }, + { MP_QSTR_loop, MP_ARG_BOOL | MP_ARG_KW_ONLY, {.u_bool = false} }, + }; + audiodelays_flanger_obj_t *self = MP_OBJ_TO_PTR(pos_args[0]); + check_for_deinit(self); + mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)]; + mp_arg_parse_all(n_args - 1, pos_args + 1, kw_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args); + + + mp_obj_t sample = args[ARG_sample].u_obj; + common_hal_audiodelays_flanger_play(self, sample, args[ARG_loop].u_bool); + + return MP_OBJ_FROM_PTR(self); +} +MP_DEFINE_CONST_FUN_OBJ_KW(audiodelays_flanger_play_obj, 1, audiodelays_flanger_obj_play); + +//| def stop(self) -> None: +//| """Stops playback of the sample.""" +//| ... +//| +//| +static mp_obj_t audiodelays_flanger_obj_stop(mp_obj_t self_in) { + audiodelays_flanger_obj_t *self = MP_OBJ_TO_PTR(self_in); + + common_hal_audiodelays_flanger_stop(self); + return mp_const_none; +} +MP_DEFINE_CONST_FUN_OBJ_1(audiodelays_flanger_stop_obj, audiodelays_flanger_obj_stop); + +static const mp_rom_map_elem_t audiodelays_flanger_locals_dict_table[] = { + // Methods + { MP_ROM_QSTR(MP_QSTR_deinit), MP_ROM_PTR(&audiodelays_flanger_deinit_obj) }, + { MP_ROM_QSTR(MP_QSTR___enter__), MP_ROM_PTR(&default___enter___obj) }, + { MP_ROM_QSTR(MP_QSTR___exit__), MP_ROM_PTR(&audiodelays_flanger___exit___obj) }, + { MP_ROM_QSTR(MP_QSTR_play), MP_ROM_PTR(&audiodelays_flanger_play_obj) }, + { MP_ROM_QSTR(MP_QSTR_stop), MP_ROM_PTR(&audiodelays_flanger_stop_obj) }, + + // Properties + { MP_ROM_QSTR(MP_QSTR_playing), MP_ROM_PTR(&audiodelays_flanger_playing_obj) }, + { MP_ROM_QSTR(MP_QSTR_min_delay_ms), MP_ROM_PTR(&audiodelays_flanger_min_delay_ms_obj) }, + { MP_ROM_QSTR(MP_QSTR_rate), MP_ROM_PTR(&audiodelays_flanger_rate_obj) }, + { MP_ROM_QSTR(MP_QSTR_depth), MP_ROM_PTR(&audiodelays_flanger_depth_obj) }, + { MP_ROM_QSTR(MP_QSTR_feedback), MP_ROM_PTR(&audiodelays_flanger_feedback_obj) }, + { MP_ROM_QSTR(MP_QSTR_mix), MP_ROM_PTR(&audiodelays_flanger_mix_obj) }, + { MP_ROM_QSTR(MP_QSTR_invert), MP_ROM_PTR(&audiodelays_flanger_invert_obj) }, + { MP_ROM_QSTR(MP_QSTR_lfo_value), MP_ROM_PTR(&audiodelays_flanger_lfo_value_obj) }, + AUDIOSAMPLE_FIELDS, +}; +static MP_DEFINE_CONST_DICT(audiodelays_flanger_locals_dict, audiodelays_flanger_locals_dict_table); + +static const audiosample_p_t audiodelays_flanger_proto = { + MP_PROTO_IMPLEMENT(MP_QSTR_protocol_audiosample) + .reset_buffer = (audiosample_reset_buffer_fun)audiodelays_flanger_reset_buffer, + .get_buffer = (audiosample_get_buffer_fun)audiodelays_flanger_get_buffer, +}; + +MP_DEFINE_CONST_OBJ_TYPE( + audiodelays_flanger_type, + MP_QSTR_Flanger, + MP_TYPE_FLAG_HAS_SPECIAL_ACCESSORS, + make_new, audiodelays_flanger_make_new, + locals_dict, &audiodelays_flanger_locals_dict, + protocol, &audiodelays_flanger_proto + ); diff --git a/shared-bindings/audiodelays/Flanger.h b/shared-bindings/audiodelays/Flanger.h new file mode 100644 index 00000000000..f139e842dbd --- /dev/null +++ b/shared-bindings/audiodelays/Flanger.h @@ -0,0 +1,43 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Tim Cocks for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include "shared-module/audiodelays/Flanger.h" + +extern const mp_obj_type_t audiodelays_flanger_type; + +void common_hal_audiodelays_flanger_construct(audiodelays_flanger_obj_t *self, uint32_t max_delay_ms, + mp_obj_t min_delay_ms, mp_obj_t rate, mp_obj_t depth, mp_obj_t feedback, mp_obj_t mix, bool invert, + uint32_t buffer_size, uint8_t bits_per_sample, + bool samples_signed, uint8_t channel_count, uint32_t sample_rate); + +void common_hal_audiodelays_flanger_deinit(audiodelays_flanger_obj_t *self); +bool common_hal_audiodelays_flanger_deinited(audiodelays_flanger_obj_t *self); + +mp_obj_t common_hal_audiodelays_flanger_get_min_delay_ms(audiodelays_flanger_obj_t *self); +void common_hal_audiodelays_flanger_set_min_delay_ms(audiodelays_flanger_obj_t *self, mp_obj_t min_delay_ms); + +mp_obj_t common_hal_audiodelays_flanger_get_rate(audiodelays_flanger_obj_t *self); +void common_hal_audiodelays_flanger_set_rate(audiodelays_flanger_obj_t *self, mp_obj_t rate); + +mp_obj_t common_hal_audiodelays_flanger_get_depth(audiodelays_flanger_obj_t *self); +void common_hal_audiodelays_flanger_set_depth(audiodelays_flanger_obj_t *self, mp_obj_t depth); + +mp_obj_t common_hal_audiodelays_flanger_get_feedback(audiodelays_flanger_obj_t *self); +void common_hal_audiodelays_flanger_set_feedback(audiodelays_flanger_obj_t *self, mp_obj_t feedback); + +mp_obj_t common_hal_audiodelays_flanger_get_mix(audiodelays_flanger_obj_t *self); +void common_hal_audiodelays_flanger_set_mix(audiodelays_flanger_obj_t *self, mp_obj_t arg); + +mp_float_t common_hal_audiodelays_flanger_get_lfo_value(audiodelays_flanger_obj_t *self); + +bool common_hal_audiodelays_flanger_get_invert(audiodelays_flanger_obj_t *self); +void common_hal_audiodelays_flanger_set_invert(audiodelays_flanger_obj_t *self, bool invert); + +bool common_hal_audiodelays_flanger_get_playing(audiodelays_flanger_obj_t *self); +void common_hal_audiodelays_flanger_play(audiodelays_flanger_obj_t *self, mp_obj_t sample, bool loop); +void common_hal_audiodelays_flanger_stop(audiodelays_flanger_obj_t *self); diff --git a/shared-bindings/audiodelays/__init__.c b/shared-bindings/audiodelays/__init__.c index 2125aa54683..6ee7a82ab79 100644 --- a/shared-bindings/audiodelays/__init__.c +++ b/shared-bindings/audiodelays/__init__.c @@ -12,6 +12,7 @@ #include "shared-bindings/audiodelays/__init__.h" #include "shared-bindings/audiodelays/Echo.h" #include "shared-bindings/audiodelays/Chorus.h" +#include "shared-bindings/audiodelays/Flanger.h" #include "shared-bindings/audiodelays/PitchShift.h" #include "shared-bindings/audiodelays/GranularPitchShift.h" #include "shared-bindings/audiodelays/MultiTapDelay.h" @@ -26,6 +27,7 @@ static const mp_rom_map_elem_t audiodelays_module_globals_table[] = { { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_audiodelays) }, { MP_ROM_QSTR(MP_QSTR_Echo), MP_ROM_PTR(&audiodelays_echo_type) }, { MP_ROM_QSTR(MP_QSTR_Chorus), MP_ROM_PTR(&audiodelays_chorus_type) }, + { MP_ROM_QSTR(MP_QSTR_Flanger), MP_ROM_PTR(&audiodelays_flanger_type) }, { MP_ROM_QSTR(MP_QSTR_PitchShift), MP_ROM_PTR(&audiodelays_pitch_shift_type) }, { MP_ROM_QSTR(MP_QSTR_GranularPitchShift), MP_ROM_PTR(&audiodelays_granular_pitch_shift_type) }, { MP_ROM_QSTR(MP_QSTR_MultiTapDelay), MP_ROM_PTR(&audiodelays_multi_tap_delay_type) }, diff --git a/shared-module/audiodelays/Flanger.c b/shared-module/audiodelays/Flanger.c new file mode 100644 index 00000000000..f0d1bb1e33f --- /dev/null +++ b/shared-module/audiodelays/Flanger.c @@ -0,0 +1,414 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Tim Cocks for Adafruit Industries +// +// SPDX-License-Identifier: MIT +#include "shared-bindings/audiodelays/Flanger.h" +#include "shared-bindings/audiocore/__init__.h" + +#include +#include "py/runtime.h" + +// The largest delay we will ever read, in frames. +#define FLANGER_MAX_DELAY_FRAMES (65535u) + +// Convert a delay in milliseconds to a Q16.16 count of frames, clamped so that both interpolation +// taps always land inside the delay line. +static uint32_t flanger_ms_to_frames_q16(audiodelays_flanger_obj_t *self, mp_float_t ms) { + mp_float_t frames = ms * self->base.sample_rate / MICROPY_FLOAT_CONST(1000.0); + mp_float_t max_frames = (mp_float_t)MIN(self->delay_buffer_frames - 2, FLANGER_MAX_DELAY_FRAMES); + + // A delay of less than one frame would read the frame we are about to overwrite + frames = MIN(MAX(frames, MICROPY_FLOAT_CONST(1.0)), max_frames); + + return (uint32_t)(frames * MICROPY_FLOAT_CONST(65536.0)); +} + +void common_hal_audiodelays_flanger_construct(audiodelays_flanger_obj_t *self, uint32_t max_delay_ms, + mp_obj_t min_delay_ms, mp_obj_t rate, mp_obj_t depth, mp_obj_t feedback, mp_obj_t mix, bool invert, + uint32_t buffer_size, uint8_t bits_per_sample, + bool samples_signed, uint8_t channel_count, uint32_t sample_rate) { + + // Basic format settings every effect and audio sample has + self->base.bits_per_sample = bits_per_sample; + self->base.samples_signed = samples_signed; // Are the samples we provide signed (common is true) + self->base.channel_count = channel_count; // Channels can be 1 for mono or 2 for stereo + self->base.sample_rate = sample_rate; // Sample rate for the effect, this generally needs to match all audio objects + self->base.single_buffer = false; + self->base.max_buffer_length = buffer_size; + + // To smooth things out as CircuitPython is doing other tasks most audio objects have a buffer + // A double buffer is set up here so the audio output can use DMA on buffer 1 while we + // write to and create buffer 2. + // This buffer is what is passed to the audio component that plays the effect. + // Samples are set sequentially. For stereo audio they are passed L/R/L/R/... + self->buffer_len = buffer_size; // in bytes + + self->buffer[0] = m_malloc_maybe(self->buffer_len); + if (self->buffer[0] == NULL) { + common_hal_audiodelays_flanger_deinit(self); + m_malloc_fail(self->buffer_len); + } + memset(self->buffer[0], 0, self->buffer_len); + + self->buffer[1] = m_malloc_maybe(self->buffer_len); + if (self->buffer[1] == NULL) { + common_hal_audiodelays_flanger_deinit(self); + m_malloc_fail(self->buffer_len); + } + memset(self->buffer[1], 0, self->buffer_len); + + self->last_buf_idx = 1; // Which buffer to use first, toggle between 0 and 1 + + // Initialize other values most effects will need. + self->sample = NULL; // The current playing sample + self->sample_remaining_buffer = NULL; // Pointer to the start of the sample buffer we have not played + self->sample_buffer_length = 0; // How many samples do we have left to play (these may be 16 bit!) + self->loop = false; // When the sample is done do we loop to the start again or stop (e.g. in a wav file) + self->more_data = false; // Is there still more data to read from the sample or did we finish + + // The below section sets up the flanger effect's starting values. + + // If we did not receive a BlockInput we need to create a default float value + if (min_delay_ms == MP_OBJ_NULL) { + min_delay_ms = mp_obj_new_float(MICROPY_FLOAT_CONST(1.0)); + } + synthio_block_assign_slot(min_delay_ms, &self->min_delay_ms, MP_QSTR_min_delay_ms); + + if (rate == MP_OBJ_NULL) { + rate = mp_obj_new_float(MICROPY_FLOAT_CONST(0.5)); + } + synthio_block_assign_slot(rate, &self->rate, MP_QSTR_rate); + + if (depth == MP_OBJ_NULL) { + depth = mp_obj_new_float(MICROPY_FLOAT_CONST(0.5)); + } + synthio_block_assign_slot(depth, &self->depth, MP_QSTR_depth); + + if (feedback == MP_OBJ_NULL) { + feedback = mp_obj_new_float(MICROPY_FLOAT_CONST(0.5)); + } + synthio_block_assign_slot(feedback, &self->feedback, MP_QSTR_feedback); + + if (mix == MP_OBJ_NULL) { + mix = mp_obj_new_float(MICROPY_FLOAT_CONST(0.5)); + } + synthio_block_assign_slot(mix, &self->mix, MP_QSTR_mix); + + self->invert = invert; + self->max_delay_ms = max_delay_ms; + + // calculate the length of a single sample in milliseconds + self->sample_ms = MICROPY_FLOAT_CONST(1000.0) / self->base.sample_rate; + + // Allocate the delay line for the largest delay we can sweep to. It is always 16-bit and each + // channel gets its own contiguous region. The two extra frames are interpolation headroom: at + // the top of the sweep the two taps sit at the far end of the line and without the extra room + // the older of the two would alias onto the frame we are about to write. + self->delay_buffer_frames = (uint32_t)(self->base.sample_rate / MICROPY_FLOAT_CONST(1000.0) * max_delay_ms) + 2; + size_t delay_buffer_size = self->delay_buffer_frames * self->base.channel_count * sizeof(int16_t); + self->delay_buffer = m_malloc_maybe(delay_buffer_size); + if (self->delay_buffer == NULL) { + common_hal_audiodelays_flanger_deinit(self); + m_malloc_fail(delay_buffer_size); + } + memset(self->delay_buffer, 0, delay_buffer_size); + + self->delay_buffer_pos[0] = self->delay_buffer_pos[1] = 0; + self->lfo_phase[0] = self->lfo_phase[1] = 0; + self->lfo_phase_inc = 0; +} + +bool common_hal_audiodelays_flanger_deinited(audiodelays_flanger_obj_t *self) { + if (self->delay_buffer == NULL) { + return true; + } + return false; +} + +void common_hal_audiodelays_flanger_deinit(audiodelays_flanger_obj_t *self) { + audiosample_mark_deinit(&self->base); + self->delay_buffer = NULL; + self->buffer[0] = NULL; + self->buffer[1] = NULL; +} + +mp_obj_t common_hal_audiodelays_flanger_get_min_delay_ms(audiodelays_flanger_obj_t *self) { + return self->min_delay_ms.obj; +} + +void common_hal_audiodelays_flanger_set_min_delay_ms(audiodelays_flanger_obj_t *self, mp_obj_t min_delay_ms) { + synthio_block_assign_slot(min_delay_ms, &self->min_delay_ms, MP_QSTR_min_delay_ms); +} + +mp_obj_t common_hal_audiodelays_flanger_get_rate(audiodelays_flanger_obj_t *self) { + return self->rate.obj; +} + +void common_hal_audiodelays_flanger_set_rate(audiodelays_flanger_obj_t *self, mp_obj_t rate) { + synthio_block_assign_slot(rate, &self->rate, MP_QSTR_rate); +} + +mp_obj_t common_hal_audiodelays_flanger_get_depth(audiodelays_flanger_obj_t *self) { + return self->depth.obj; +} + +void common_hal_audiodelays_flanger_set_depth(audiodelays_flanger_obj_t *self, mp_obj_t depth) { + synthio_block_assign_slot(depth, &self->depth, MP_QSTR_depth); +} + +mp_obj_t common_hal_audiodelays_flanger_get_feedback(audiodelays_flanger_obj_t *self) { + return self->feedback.obj; +} + +void common_hal_audiodelays_flanger_set_feedback(audiodelays_flanger_obj_t *self, mp_obj_t feedback) { + synthio_block_assign_slot(feedback, &self->feedback, MP_QSTR_feedback); +} + +mp_obj_t common_hal_audiodelays_flanger_get_mix(audiodelays_flanger_obj_t *self) { + return self->mix.obj; +} + +void common_hal_audiodelays_flanger_set_mix(audiodelays_flanger_obj_t *self, mp_obj_t arg) { + synthio_block_assign_slot(arg, &self->mix, MP_QSTR_mix); +} + +// Fold the sawtooth phase accumulator into a triangle in the range 0 to 65535 +static uint32_t flanger_phase_to_triangle(uint32_t phase) { + uint32_t tri = phase >> 15; + if (tri > 65535) { + tri = 131071 - tri; + } + return tri; +} + +mp_float_t common_hal_audiodelays_flanger_get_lfo_value(audiodelays_flanger_obj_t *self) { + return (mp_float_t)flanger_phase_to_triangle(self->lfo_phase[0]) / MICROPY_FLOAT_CONST(65535.0); +} + +bool common_hal_audiodelays_flanger_get_invert(audiodelays_flanger_obj_t *self) { + return self->invert; +} + +void common_hal_audiodelays_flanger_set_invert(audiodelays_flanger_obj_t *self, bool invert) { + self->invert = invert; +} + +void audiodelays_flanger_reset_buffer(audiodelays_flanger_obj_t *self, + bool single_channel_output, + uint8_t channel) { + + memset(self->buffer[0], 0, self->buffer_len); + memset(self->buffer[1], 0, self->buffer_len); + memset(self->delay_buffer, 0, self->delay_buffer_frames * self->base.channel_count * sizeof(int16_t)); + self->delay_buffer_pos[0] = self->delay_buffer_pos[1] = 0; + self->lfo_phase[0] = self->lfo_phase[1] = 0; +} + +bool common_hal_audiodelays_flanger_get_playing(audiodelays_flanger_obj_t *self) { + return self->sample != NULL; +} + +void common_hal_audiodelays_flanger_play(audiodelays_flanger_obj_t *self, mp_obj_t sample, bool loop) { + audiosample_must_match(&self->base, sample, false); + + self->sample = sample; + self->loop = loop; + + audiosample_reset_buffer(self->sample, false, 0); + audioio_get_buffer_result_t result = audiosample_get_buffer(self->sample, false, 0, (uint8_t **)&self->sample_remaining_buffer, &self->sample_buffer_length); + + // Track remaining sample length in terms of bytes per sample + self->sample_buffer_length /= (self->base.bits_per_sample / 8); + // Store if we have more data in the sample to retrieve + self->more_data = result == GET_BUFFER_MORE_DATA; +} + +void common_hal_audiodelays_flanger_stop(audiodelays_flanger_obj_t *self) { + self->sample = NULL; +} + +audioio_get_buffer_result_t audiodelays_flanger_get_buffer(audiodelays_flanger_obj_t *self, bool single_channel_output, uint8_t channel, + uint8_t **buffer, uint32_t *buffer_length) { + + if (!single_channel_output) { + channel = 0; + } + + // Switch our buffers to the other buffer + self->last_buf_idx = !self->last_buf_idx; + + // If we are using 16 bit samples we need a 16 bit pointer, 8 bit needs an 8 bit pointer + int16_t *word_buffer = (int16_t *)self->buffer[self->last_buf_idx]; + int8_t *hword_buffer = self->buffer[self->last_buf_idx]; + uint32_t length = self->buffer_len / (self->base.bits_per_sample / 8); + + uint8_t channel_count = self->base.channel_count; + uint32_t frames = self->delay_buffer_frames; + + // For single channel output every word in this call belongs to `channel`. Otherwise the + // channels are interleaved and alternate with every word. + bool single_right = single_channel_output && channel == 1 && channel_count == 2; + + // Loop over the entire length of our buffer to fill it, this may require several calls to get data from the sample + while (length != 0) { + // Check if there is no more sample to play, we will either load more data, reset the sample if loop is on or clear the sample + if (self->sample_buffer_length == 0) { + if (!self->more_data) { // The sample has indicated it has no more data to play + if (self->loop && self->sample) { // If we are supposed to loop reset the sample to the start + audiosample_reset_buffer(self->sample, false, 0); + } else { // If we were not supposed to loop the sample, stop playing it + self->sample = NULL; + } + } + if (self->sample) { + // Load another sample buffer to play + audioio_get_buffer_result_t result = audiosample_get_buffer(self->sample, false, 0, (uint8_t **)&self->sample_remaining_buffer, &self->sample_buffer_length); + // Track length in terms of words. + self->sample_buffer_length /= (self->base.bits_per_sample / 8); + self->more_data = result == GET_BUFFER_MORE_DATA; + } + } + + if (self->sample == NULL) { + // tick all block inputs so that anything attached to them stays in sync + shared_bindings_synthio_lfo_tick(self->base.sample_rate, length / channel_count); + (void)synthio_block_slot_get(&self->min_delay_ms); + (void)synthio_block_slot_get(&self->rate); + (void)synthio_block_slot_get(&self->depth); + (void)synthio_block_slot_get(&self->feedback); + (void)synthio_block_slot_get(&self->mix); + + if (self->base.samples_signed) { + memset(word_buffer, 0, length * (self->base.bits_per_sample / 8)); + } else { + // For unsigned samples set to the middle which is "quiet" + if (MP_LIKELY(self->base.bits_per_sample == 16)) { + uint16_t *uword_buffer = (uint16_t *)word_buffer; + while (length--) { + *uword_buffer++ = 32768; + } + } else { + memset(hword_buffer, 128, length * (self->base.bits_per_sample / 8)); + } + } + + length = 0; + } else { + // we have a sample to play and flange + // Determine how many bytes we can process to our buffer, the less of the sample we have left and our buffer remaining + uint32_t num_bytes = MIN(MIN(self->sample_buffer_length, length), SYNTHIO_MAX_DUR * channel_count); + + int16_t *sample_src = (int16_t *)self->sample_remaining_buffer; // for 16-bit samples + int8_t *sample_hsrc = (int8_t *)self->sample_remaining_buffer; // for 8-bit samples + + // get the effect values we need from the BlockInput + shared_bindings_synthio_lfo_tick(self->base.sample_rate, num_bytes / channel_count); + mp_float_t f_min_delay_ms = synthio_block_slot_get_limited(&self->min_delay_ms, self->sample_ms, (mp_float_t)self->max_delay_ms); + mp_float_t f_rate = synthio_block_slot_get_limited(&self->rate, MICROPY_FLOAT_CONST(0.0), MICROPY_FLOAT_CONST(20.0)); + mp_float_t f_depth = synthio_block_slot_get_limited(&self->depth, MICROPY_FLOAT_CONST(0.0), MICROPY_FLOAT_CONST(1.0)); + int32_t feedback = (int32_t)(synthio_block_slot_get_limited(&self->feedback, MICROPY_FLOAT_CONST(-0.95), MICROPY_FLOAT_CONST(0.95)) * 32767); + int32_t mix = (int32_t)(synthio_block_slot_get_limited(&self->mix, MICROPY_FLOAT_CONST(0.0), MICROPY_FLOAT_CONST(1.0)) * 32767); + + // The sweep runs upward from min_delay_ms towards max_delay_ms rather than around a + // centre, so no combination of min_delay_ms and depth can push it out of the delay line. + mp_float_t sweep_top_ms = f_min_delay_ms + f_depth * ((mp_float_t)self->max_delay_ms - f_min_delay_ms); + uint32_t delay_min_q16 = flanger_ms_to_frames_q16(self, f_min_delay_ms); + uint32_t delay_span_q16 = flanger_ms_to_frames_q16(self, sweep_top_ms) - delay_min_q16; + + // How far the LFO advances each frame. A rate at or above half the sample rate is + // meaningless, and clamping there also keeps the conversion inside a uint32_t. + mp_float_t phase_inc = MIN(f_rate / self->base.sample_rate, MICROPY_FLOAT_CONST(0.5)); + self->lfo_phase_inc = (uint32_t)(phase_inc * MICROPY_FLOAT_CONST(4294967296.0)); + + for (uint32_t i = 0; i < num_bytes; i++) { + bool right_channel = single_channel_output ? single_right : ((i % channel_count) == 1); + + int32_t sample_word = 0; + if (MP_LIKELY(self->base.bits_per_sample == 16)) { + sample_word = sample_src[i]; + } else { + if (self->base.samples_signed) { + sample_word = sample_hsrc[i]; + } else { + // changing from an 8 bit unsigned to signed into a 32-bit signed + sample_word = (int8_t)(((uint8_t)sample_hsrc[i]) ^ 0x80); + } + } + + // Advance this channel's LFO by one frame. Each channel has its own accumulator so + // that the sweep runs at `rate` whether the channels arrive interleaved (both + // accumulators step once per frame) or one channel per call. + self->lfo_phase[right_channel] += self->lfo_phase_inc; + + uint32_t tri = flanger_phase_to_triangle(self->lfo_phase[right_channel]); + + // The delay for this frame, in Q16.16 frames + uint32_t delay_q16 = delay_min_q16 + (uint32_t)(((uint64_t)delay_span_q16 * tri) >> 16); + uint32_t delay_int = delay_q16 >> 16; + uint32_t delay_frac = delay_q16 & 0xffff; + + int16_t *line = self->delay_buffer + (right_channel ? frames : 0); + uint32_t w = self->delay_buffer_pos[right_channel]; + + // Two taps straddling the fractional delay, counted back from the write head. + // delay_int is at most frames - 2 so neither index can escape the region. + uint32_t r0 = w + frames - delay_int; + if (r0 >= frames) { + r0 -= frames; + } + uint32_t r1 = r0 ? r0 - 1 : frames - 1; + + // Linear interpolation between them + int32_t s0 = line[r0]; + int32_t s1 = line[r1]; + int32_t wet = s0 + (((s1 - s0) * (int32_t)delay_frac) >> 16); + + // Write the input plus the regenerated signal back into the line + line[w] = synthio_sat16(sample_word + synthio_sat16(wet * feedback, 15), 0); + self->delay_buffer_pos[right_channel] = (w + 1 == frames) ? 0 : w + 1; + + int32_t word; + if (mix <= 328) { // if mix is zero (0.01 in fixed point), pure sample only + // Note that we still ran the delay line above. + word = sample_word; + } else { + int32_t wet_word = synthio_sat16(wet * mix, 15); + // Add (or, inverted, subtract) original sample + effect + word = self->invert ? sample_word - wet_word : sample_word + wet_word; + word = synthio_mix_down_sample(word, SYNTHIO_MIX_DOWN_SCALE(2)); + } + + if (MP_LIKELY(self->base.bits_per_sample == 16)) { + word_buffer[i] = word; + if (!self->base.samples_signed) { + word_buffer[i] ^= 0x8000; + } + } else { + // 8-bit samples have no headroom for synthio_mix_down_sample to work with, so + // clamp instead or the sum of the dry and wet signals wraps around + int8_t out = MIN(MAX(word, -128), 127); + if (self->base.samples_signed) { + hword_buffer[i] = out; + } else { + hword_buffer[i] = (uint8_t)out ^ 0x80; + } + } + } + + // Update the remaining length and the buffer positions based on how much we wrote into our buffer + length -= num_bytes; + word_buffer += num_bytes; + hword_buffer += num_bytes; + self->sample_remaining_buffer += (num_bytes * (self->base.bits_per_sample / 8)); + self->sample_buffer_length -= num_bytes; + } + } + + // Finally pass our buffer and length to the calling audio function + *buffer = (uint8_t *)self->buffer[self->last_buf_idx]; + *buffer_length = self->buffer_len; + + // Flanger always returns more data but some effects may return GET_BUFFER_DONE or GET_BUFFER_ERROR (see audiocore/__init__.h) + return GET_BUFFER_MORE_DATA; +} diff --git a/shared-module/audiodelays/Flanger.h b/shared-module/audiodelays/Flanger.h new file mode 100644 index 00000000000..6e8a37f51e2 --- /dev/null +++ b/shared-module/audiodelays/Flanger.h @@ -0,0 +1,62 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Tim Cocks for Adafruit Industries +// +// SPDX-License-Identifier: MIT +#pragma once + +#include "py/obj.h" + +#include "shared-module/audiocore/__init__.h" +#include "shared-module/synthio/block.h" + +extern const mp_obj_type_t audiodelays_flanger_type; + +typedef struct { + audiosample_base_t base; + + // Effect parameters. + synthio_block_slot_t min_delay_ms; // floor of the sweep + synthio_block_slot_t rate; // LFO frequency in Hz + synthio_block_slot_t depth; // 0 to 1, portion of the available range swept + synthio_block_slot_t feedback; // -0.95 to 0.95, regeneration + synthio_block_slot_t mix; // 0 to 1, dry to wet + + uint32_t max_delay_ms; + mp_float_t sample_ms; // length of a single sample in milliseconds + + bool invert; // subtract the wet signal instead of adding it + + int8_t *buffer[2]; + uint8_t last_buf_idx; + uint32_t buffer_len; // max buffer in bytes + + uint8_t *sample_remaining_buffer; + uint32_t sample_buffer_length; + + bool loop; + bool more_data; + + // The delay line is always 16-bit and is split into one contiguous region per channel so + // that read/write positions are plain frame counts and wrapping is a single modulo. + int16_t *delay_buffer; + uint32_t delay_buffer_frames; // frames in each per channel region + uint32_t delay_buffer_pos[2]; // write position in frames, per channel + + // Internal LFO. One phase accumulator per channel so that the sweep advances once per frame + // whether the channels are interleaved in one call or requested one channel at a time. + uint32_t lfo_phase[2]; // Q0.32, wraps naturally + uint32_t lfo_phase_inc; // Q0.32 step per frame, recalculated per chunk from rate + + mp_obj_t sample; +} audiodelays_flanger_obj_t; + +void audiodelays_flanger_reset_buffer(audiodelays_flanger_obj_t *self, + bool single_channel_output, + uint8_t channel); + +audioio_get_buffer_result_t audiodelays_flanger_get_buffer(audiodelays_flanger_obj_t *self, + bool single_channel_output, + uint8_t channel, + uint8_t **buffer, + uint32_t *buffer_length); // length in bytes