diff --git a/locale/circuitpython.pot b/locale/circuitpython.pot index 0b19dce9c427c..123902650b958 100644 --- a/locale/circuitpython.pot +++ b/locale/circuitpython.pot @@ -1965,20 +1965,8 @@ msgstr "" msgid "The length of rgb_pins must be 6, 12, 18, 24, or 30" msgstr "" -#: shared-module/audiomixer/MixerVoice.c -msgid "The sample's bits_per_sample does not match the mixer's" -msgstr "" - -#: shared-module/audiomixer/MixerVoice.c -msgid "The sample's channel count does not match the mixer's" -msgstr "" - -#: shared-module/audiomixer/MixerVoice.c -msgid "The sample's sample rate does not match the mixer's" -msgstr "" - -#: shared-module/audiomixer/MixerVoice.c -msgid "The sample's signedness does not match the mixer's" +#: shared-module/audiodelays/Echo.c shared-module/audiomixer/MixerVoice.c +msgid "The sample's %q does not match" msgstr "" #: supervisor/shared/safe_mode.c @@ -2511,7 +2499,7 @@ msgstr "" msgid "bits must be 32 or less" msgstr "" -#: shared-bindings/audiomixer/Mixer.c +#: shared-bindings/audiodelays/Echo.c shared-bindings/audiomixer/Mixer.c msgid "bits_per_sample must be 8 or 16" msgstr "" diff --git a/ports/raspberrypi/mpconfigport.mk b/ports/raspberrypi/mpconfigport.mk index 81913bde01a76..d619e78bd97a8 100644 --- a/ports/raspberrypi/mpconfigport.mk +++ b/ports/raspberrypi/mpconfigport.mk @@ -21,7 +21,7 @@ CIRCUITPY_PWMIO ?= 1 CIRCUITPY_RGBMATRIX ?= $(CIRCUITPY_DISPLAYIO) CIRCUITPY_ROTARYIO ?= 1 CIRCUITPY_ROTARYIO_SOFTENCODER = 1 -CIRCUITPY_SYNTHIO_MAX_CHANNELS = 12 +CIRCUITPY_SYNTHIO_MAX_CHANNELS = 24 CIRCUITPY_USB_HOST ?= 1 CIRCUITPY_USB_VIDEO ?= 1 @@ -64,6 +64,9 @@ CIRCUITPY_PICODVI ?= 1 # Our generic touchio uses a pull down and RP2350 A2 hardware doesn't work correctly. # So, turn touchio off because it doesn't work. CIRCUITPY_TOUCHIO = 0 + +# Audio effects +CIRCUITPY_AUDIOEFFECTS ?= 1 endif INTERNAL_LIBM = 1 diff --git a/py/circuitpy_defns.mk b/py/circuitpy_defns.mk index 6d7848997cac2..c2c9ffa6736e8 100644 --- a/py/circuitpy_defns.mk +++ b/py/circuitpy_defns.mk @@ -131,6 +131,9 @@ endif ifeq ($(CIRCUITPY_AUDIOCORE),1) SRC_PATTERNS += audiocore/% endif +ifeq ($(CIRCUITPY_AUDIODELAYS),1) +SRC_PATTERNS += audiodelays/% +endif ifeq ($(CIRCUITPY_AUDIOMIXER),1) SRC_PATTERNS += audiomixer/% endif @@ -617,6 +620,8 @@ SRC_SHARED_MODULE_ALL = \ audiocore/RawSample.c \ audiocore/WaveFile.c \ audiocore/__init__.c \ + audiodelays/Echo.c \ + audiodelays/__init__.c \ audioio/__init__.c \ audiomixer/Mixer.c \ audiomixer/MixerVoice.c \ diff --git a/py/circuitpy_mpconfig.mk b/py/circuitpy_mpconfig.mk index 81d46270f8f9c..a8e44a12c9418 100644 --- a/py/circuitpy_mpconfig.mk +++ b/py/circuitpy_mpconfig.mk @@ -141,6 +141,10 @@ CFLAGS += -DCIRCUITPY_AUDIOCORE_DEBUG=$(CIRCUITPY_AUDIOCORE_DEBUG) CIRCUITPY_AUDIOMP3 ?= $(call enable-if-all,$(CIRCUITPY_FULL_BUILD) $(CIRCUITPY_AUDIOCORE)) CFLAGS += -DCIRCUITPY_AUDIOMP3=$(CIRCUITPY_AUDIOMP3) +CIRCUITPY_AUDIOEFFECTS ?= 0 +CIRCUITPY_AUDIODELAYS ?= $(CIRCUITPY_AUDIOEFFECTS) +CFLAGS += -DCIRCUITPY_AUDIODELAYS=$(CIRCUITPY_AUDIODELAYS) + CIRCUITPY_AURORA_EPAPER ?= 0 CFLAGS += -DCIRCUITPY_AURORA_EPAPER=$(CIRCUITPY_AURORA_EPAPER) diff --git a/shared-bindings/audiodelays/Echo.c b/shared-bindings/audiodelays/Echo.c new file mode 100644 index 0000000000000..c0f1556ed75cc --- /dev/null +++ b/shared-bindings/audiodelays/Echo.c @@ -0,0 +1,340 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2024 Mark Komus +// +// SPDX-License-Identifier: MIT + +#include + +#include "shared-bindings/audiodelays/Echo.h" +#include "shared-module/audiodelays/Echo.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" + +#define DECAY_DEFAULT 0.7f +#define MIX_DEFAULT 0.5f + +//| class Echo: +//| """An Echo effect""" +//| +//| def __init__( +//| self, +//| max_delay_ms: int = 500, +//| delay_ms: synthio.BlockInput = 250.0, +//| decay: synthio.BlockInput = 0.7, +//| mix: synthio.BlockInput = 0.5, +//| buffer_size: int = 512, +//| sample_rate: int = 8000, +//| bits_per_sample: int = 16, +//| samples_signed: bool = True, +//| channel_count: int = 1, +//| ) -> None: +//| """Create a Echo effect where you hear the original sample play back, at a lesser volume after +//| a set number of millisecond delay. The delay timing of the echo can be changed at runtime +//| with the delay_ms parameter but the delay can never exceed the max_delay_ms parameter. The +//| maximum delay you can set is limited by available memory. +//| +//| Each time the echo plays back the volume is reduced by the decay setting (echo * decay). +//| +//| The mix parameter allows you to change how much of the unchanged sample passes through to +//| the output to how much of the effect audio you hear as the output. +//| +//| :param int max_delay_ms: The maximum time the echo can be in milliseconds +//| :param synthio.BlockInput delay_ms: The current time of the echo delay in milliseconds. Must be less the max_delay_ms +//| :param synthio.BlockInput decay: The rate the echo fades. 0.0 = instant; 1.0 = never. +//| :param synthio.BlockInput mix: The mix as a ratio of the sample (0.0) to the effect (1.0). +//| :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) +//| :param bool freq_shift: Do echos change frequency as the echo delay changes +//| +//| Playing adding an echo to a synth:: +//| +//| import time +//| import board +//| import audiobusio +//| import synthio +//| import audiodelays +//| +//| audio = audiobusio.I2SOut(bit_clock=board.GP20, word_select=board.GP21, data=board.GP22) +//| synth = synthio.Synthesizer(channel_count=1, sample_rate=44100) +//| echo = audiodelays.Echo(max_delay_ms=1000, delay_ms=850, decay=0.65, buffer_size=1024, channel_count=1, sample_rate=44100, mix=0.7, freq_shift=False) +//| echo.play(synth) +//| audio.play(echo) +//| +//| note = synthio.Note(261) +//| while True: +//| synth.press(note) +//| time.sleep(0.25) +//| synth.release(note) +//| time.sleep(5)""" +//| ... +static mp_obj_t audiodelays_echo_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_delay_ms, ARG_decay, ARG_mix, ARG_buffer_size, ARG_sample_rate, ARG_bits_per_sample, ARG_samples_signed, ARG_channel_count, ARG_freq_shift, }; + static const mp_arg_t allowed_args[] = { + { MP_QSTR_max_delay_ms, MP_ARG_INT | MP_ARG_KW_ONLY, {.u_int = 500 } }, + { MP_QSTR_delay_ms, MP_ARG_OBJ | MP_ARG_KW_ONLY, {.u_obj = MP_OBJ_NULL} }, + { MP_QSTR_decay, 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_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_QSTR_freq_shift, MP_ARG_BOOL | MP_ARG_KW_ONLY, {.u_bool = true } }, + }; + + 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, 4000, 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_echo_obj_t *self = mp_obj_malloc(audiodelays_echo_obj_t, &audiodelays_echo_type); + common_hal_audiodelays_echo_construct(self, max_delay_ms, args[ARG_delay_ms].u_obj, args[ARG_decay].u_obj, args[ARG_mix].u_obj, args[ARG_buffer_size].u_int, bits_per_sample, args[ARG_samples_signed].u_bool, channel_count, sample_rate, args[ARG_freq_shift].u_bool); + + return MP_OBJ_FROM_PTR(self); +} + +//| def deinit(self) -> None: +//| """Deinitialises the Echo.""" +//| ... +static mp_obj_t audiodelays_echo_deinit(mp_obj_t self_in) { + audiodelays_echo_obj_t *self = MP_OBJ_TO_PTR(self_in); + common_hal_audiodelays_echo_deinit(self); + return mp_const_none; +} +static MP_DEFINE_CONST_FUN_OBJ_1(audiodelays_echo_deinit_obj, audiodelays_echo_deinit); + +static void check_for_deinit(audiodelays_echo_obj_t *self) { + if (common_hal_audiodelays_echo_deinited(self)) { + raise_deinited_error(); + } +} + +//| def __enter__(self) -> Echo: +//| """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_echo_obj___exit__(size_t n_args, const mp_obj_t *args) { + (void)n_args; + common_hal_audiodelays_echo_deinit(args[0]); + return mp_const_none; +} +static MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(audiodelays_echo___exit___obj, 4, 4, audiodelays_echo_obj___exit__); + + +//| delay_ms: synthio.BlockInput +//| """Delay of the echo in milliseconds. (read-only)""" +//| +static mp_obj_t audiodelays_echo_obj_get_delay_ms(mp_obj_t self_in) { + audiodelays_echo_obj_t *self = MP_OBJ_TO_PTR(self_in); + + return common_hal_audiodelays_echo_get_delay_ms(self); + +} +MP_DEFINE_CONST_FUN_OBJ_1(audiodelays_echo_get_delay_ms_obj, audiodelays_echo_obj_get_delay_ms); + +static mp_obj_t audiodelays_echo_obj_set_delay_ms(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { + enum { ARG_delay_ms }; + static const mp_arg_t allowed_args[] = { + { MP_QSTR_delay_ms, MP_ARG_OBJ | MP_ARG_REQUIRED, {} }, + }; + audiodelays_echo_obj_t *self = MP_OBJ_TO_PTR(pos_args[0]); + 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); + + common_hal_audiodelays_echo_set_delay_ms(self, args[ARG_delay_ms].u_obj); + + return mp_const_none; +} +MP_DEFINE_CONST_FUN_OBJ_KW(audiodelays_echo_set_delay_ms_obj, 1, audiodelays_echo_obj_set_delay_ms); + +MP_PROPERTY_GETSET(audiodelays_echo_delay_ms_obj, + (mp_obj_t)&audiodelays_echo_get_delay_ms_obj, + (mp_obj_t)&audiodelays_echo_set_delay_ms_obj); + +//| decay: synthio.BlockInput +//| """The rate the echo decays between 0 and 1 where 1 is forever and 0 is no echo.""" +static mp_obj_t audiodelays_echo_obj_get_decay(mp_obj_t self_in) { + return common_hal_audiodelays_echo_get_decay(self_in); +} +MP_DEFINE_CONST_FUN_OBJ_1(audiodelays_echo_get_decay_obj, audiodelays_echo_obj_get_decay); + +static mp_obj_t audiodelays_echo_obj_set_decay(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { + enum { ARG_decay }; + static const mp_arg_t allowed_args[] = { + { MP_QSTR_decay, MP_ARG_OBJ | MP_ARG_REQUIRED, {} }, + }; + audiodelays_echo_obj_t *self = MP_OBJ_TO_PTR(pos_args[0]); + 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); + + common_hal_audiodelays_echo_set_decay(self, args[ARG_decay].u_obj); + + return mp_const_none; +} +MP_DEFINE_CONST_FUN_OBJ_KW(audiodelays_echo_set_decay_obj, 1, audiodelays_echo_obj_set_decay); + +MP_PROPERTY_GETSET(audiodelays_echo_decay_obj, + (mp_obj_t)&audiodelays_echo_get_decay_obj, + (mp_obj_t)&audiodelays_echo_set_decay_obj); + +//| mix: synthio.BlockInput +//| """The rate the echo mix between 0 and 1 where 0 is only sample and 1 is all effect.""" +static mp_obj_t audiodelays_echo_obj_get_mix(mp_obj_t self_in) { + return common_hal_audiodelays_echo_get_mix(self_in); +} +MP_DEFINE_CONST_FUN_OBJ_1(audiodelays_echo_get_mix_obj, audiodelays_echo_obj_get_mix); + +static mp_obj_t audiodelays_echo_obj_set_mix(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { + enum { ARG_mix }; + static const mp_arg_t allowed_args[] = { + { MP_QSTR_mix, MP_ARG_OBJ | MP_ARG_REQUIRED, {} }, + }; + audiodelays_echo_obj_t *self = MP_OBJ_TO_PTR(pos_args[0]); + 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); + + common_hal_audiodelays_echo_set_mix(self, args[ARG_mix].u_obj); + + return mp_const_none; +} +MP_DEFINE_CONST_FUN_OBJ_KW(audiodelays_echo_set_mix_obj, 1, audiodelays_echo_obj_set_mix); + +MP_PROPERTY_GETSET(audiodelays_echo_mix_obj, + (mp_obj_t)&audiodelays_echo_get_mix_obj, + (mp_obj_t)&audiodelays_echo_set_mix_obj); + + + +//| freq_shift: bool +//| """Does the echo change frequencies as the delay changes.""" +static mp_obj_t audiodelays_echo_obj_get_freq_shift(mp_obj_t self_in) { + return mp_obj_new_bool(common_hal_audiodelays_echo_get_freq_shift(self_in)); +} +MP_DEFINE_CONST_FUN_OBJ_1(audiodelays_echo_get_freq_shift_obj, audiodelays_echo_obj_get_freq_shift); + +static mp_obj_t audiodelays_echo_obj_set_freq_shift(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { + enum { ARG_freq_shift }; + static const mp_arg_t allowed_args[] = { + { MP_QSTR_freq_shift, MP_ARG_BOOL | MP_ARG_REQUIRED, {} }, + }; + audiodelays_echo_obj_t *self = MP_OBJ_TO_PTR(pos_args[0]); + 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); + + common_hal_audiodelays_echo_set_freq_shift(self, args[ARG_freq_shift].u_bool); + + return mp_const_none; +} +MP_DEFINE_CONST_FUN_OBJ_KW(audiodelays_echo_set_freq_shift_obj, 1, audiodelays_echo_obj_set_freq_shift); + +MP_PROPERTY_GETSET(audiodelays_echo_freq_shift_obj, + (mp_obj_t)&audiodelays_echo_get_freq_shift_obj, + (mp_obj_t)&audiodelays_echo_set_freq_shift_obj); + + + +//| playing: bool +//| """True when the effect is playing a sample. (read-only)""" +static mp_obj_t audiodelays_echo_obj_get_playing(mp_obj_t self_in) { + audiodelays_echo_obj_t *self = MP_OBJ_TO_PTR(self_in); + check_for_deinit(self); + return mp_obj_new_bool(common_hal_audiodelays_echo_get_playing(self)); +} +MP_DEFINE_CONST_FUN_OBJ_1(audiodelays_echo_get_playing_obj, audiodelays_echo_obj_get_playing); + +MP_PROPERTY_GETTER(audiodelays_echo_playing_obj, + (mp_obj_t)&audiodelays_echo_get_playing_obj); + +//| def play(self, sample: circuitpython_typing.AudioSample, *, loop: bool = False) -> None: +//| """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.""" +//| ... +static mp_obj_t audiodelays_echo_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_echo_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_echo_play(self, sample, args[ARG_loop].u_bool); + + return mp_const_none; +} +MP_DEFINE_CONST_FUN_OBJ_KW(audiodelays_echo_play_obj, 1, audiodelays_echo_obj_play); + +//| def stop(self) -> None: +//| """Stops playback of the sample. The echo continues playing.""" +//| ... +//| +static mp_obj_t audiodelays_echo_obj_stop(mp_obj_t self_in) { + audiodelays_echo_obj_t *self = MP_OBJ_TO_PTR(self_in); + + common_hal_audiodelays_echo_stop(self); + return mp_const_none; +} +MP_DEFINE_CONST_FUN_OBJ_1(audiodelays_echo_stop_obj, audiodelays_echo_obj_stop); + +static const mp_rom_map_elem_t audiodelays_echo_locals_dict_table[] = { + // Methods + { MP_ROM_QSTR(MP_QSTR_deinit), MP_ROM_PTR(&audiodelays_echo_deinit_obj) }, + { MP_ROM_QSTR(MP_QSTR___enter__), MP_ROM_PTR(&default___enter___obj) }, + { MP_ROM_QSTR(MP_QSTR___exit__), MP_ROM_PTR(&audiodelays_echo___exit___obj) }, + { MP_ROM_QSTR(MP_QSTR_play), MP_ROM_PTR(&audiodelays_echo_play_obj) }, + { MP_ROM_QSTR(MP_QSTR_stop), MP_ROM_PTR(&audiodelays_echo_stop_obj) }, + + // Properties + { MP_ROM_QSTR(MP_QSTR_playing), MP_ROM_PTR(&audiodelays_echo_playing_obj) }, + { MP_ROM_QSTR(MP_QSTR_delay_ms), MP_ROM_PTR(&audiodelays_echo_delay_ms_obj) }, + { MP_ROM_QSTR(MP_QSTR_decay), MP_ROM_PTR(&audiodelays_echo_decay_obj) }, + { MP_ROM_QSTR(MP_QSTR_mix), MP_ROM_PTR(&audiodelays_echo_mix_obj) }, + { MP_ROM_QSTR(MP_QSTR_freq_shift), MP_ROM_PTR(&audiodelays_echo_freq_shift_obj) }, +}; +static MP_DEFINE_CONST_DICT(audiodelays_echo_locals_dict, audiodelays_echo_locals_dict_table); + +static const audiosample_p_t audiodelays_echo_proto = { + MP_PROTO_IMPLEMENT(MP_QSTR_protocol_audiosample) + .sample_rate = (audiosample_sample_rate_fun)common_hal_audiodelays_echo_get_sample_rate, + .bits_per_sample = (audiosample_bits_per_sample_fun)common_hal_audiodelays_echo_get_bits_per_sample, + .channel_count = (audiosample_channel_count_fun)common_hal_audiodelays_echo_get_channel_count, + .reset_buffer = (audiosample_reset_buffer_fun)audiodelays_echo_reset_buffer, + .get_buffer = (audiosample_get_buffer_fun)audiodelays_echo_get_buffer, + .get_buffer_structure = (audiosample_get_buffer_structure_fun)audiodelays_echo_get_buffer_structure, +}; + +MP_DEFINE_CONST_OBJ_TYPE( + audiodelays_echo_type, + MP_QSTR_Echo, + MP_TYPE_FLAG_HAS_SPECIAL_ACCESSORS, + make_new, audiodelays_echo_make_new, + locals_dict, &audiodelays_echo_locals_dict, + protocol, &audiodelays_echo_proto + ); diff --git a/shared-bindings/audiodelays/Echo.h b/shared-bindings/audiodelays/Echo.h new file mode 100644 index 0000000000000..b276a328b3a21 --- /dev/null +++ b/shared-bindings/audiodelays/Echo.h @@ -0,0 +1,39 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2024 Mark Komus +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include "shared-module/audiodelays/Echo.h" + +extern const mp_obj_type_t audiodelays_echo_type; + +void common_hal_audiodelays_echo_construct(audiodelays_echo_obj_t *self, uint32_t max_delay_ms, + mp_obj_t delay_ms, mp_obj_t decay, mp_obj_t mix, + uint32_t buffer_size, uint8_t bits_per_sample, bool samples_signed, + uint8_t channel_count, uint32_t sample_rate, bool freq_shift); + +void common_hal_audiodelays_echo_deinit(audiodelays_echo_obj_t *self); +bool common_hal_audiodelays_echo_deinited(audiodelays_echo_obj_t *self); + +uint32_t common_hal_audiodelays_echo_get_sample_rate(audiodelays_echo_obj_t *self); +uint8_t common_hal_audiodelays_echo_get_channel_count(audiodelays_echo_obj_t *self); +uint8_t common_hal_audiodelays_echo_get_bits_per_sample(audiodelays_echo_obj_t *self); + +mp_obj_t common_hal_audiodelays_echo_get_delay_ms(audiodelays_echo_obj_t *self); +void common_hal_audiodelays_echo_set_delay_ms(audiodelays_echo_obj_t *self, mp_obj_t delay_ms); + +bool common_hal_audiodelays_echo_get_freq_shift(audiodelays_echo_obj_t *self); +void common_hal_audiodelays_echo_set_freq_shift(audiodelays_echo_obj_t *self, bool freq_shift); + +mp_obj_t common_hal_audiodelays_echo_get_decay(audiodelays_echo_obj_t *self); +void common_hal_audiodelays_echo_set_decay(audiodelays_echo_obj_t *self, mp_obj_t decay); + +mp_obj_t common_hal_audiodelays_echo_get_mix(audiodelays_echo_obj_t *self); +void common_hal_audiodelays_echo_set_mix(audiodelays_echo_obj_t *self, mp_obj_t arg); + +bool common_hal_audiodelays_echo_get_playing(audiodelays_echo_obj_t *self); +void common_hal_audiodelays_echo_play(audiodelays_echo_obj_t *self, mp_obj_t sample, bool loop); +void common_hal_audiodelays_echo_stop(audiodelays_echo_obj_t *self); diff --git a/shared-bindings/audiodelays/__init__.c b/shared-bindings/audiodelays/__init__.c new file mode 100644 index 0000000000000..4b0be7b75ad86 --- /dev/null +++ b/shared-bindings/audiodelays/__init__.c @@ -0,0 +1,33 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2024 Mark Komus +// +// SPDX-License-Identifier: MIT + +#include + +#include "py/obj.h" +#include "py/runtime.h" + +#include "shared-bindings/audiodelays/__init__.h" +#include "shared-bindings/audiodelays/Echo.h" + +//| """Support for audio delay effects +//| +//| The `audiodelays` module contains classes to provide access to audio delay effects. +//| +//| """ + +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) }, +}; + +static MP_DEFINE_CONST_DICT(audiodelays_module_globals, audiodelays_module_globals_table); + +const mp_obj_module_t audiodelays_module = { + .base = { &mp_type_module }, + .globals = (mp_obj_dict_t *)&audiodelays_module_globals, +}; + +MP_REGISTER_MODULE(MP_QSTR_audiodelays, audiodelays_module); diff --git a/shared-bindings/audiodelays/__init__.h b/shared-bindings/audiodelays/__init__.h new file mode 100644 index 0000000000000..3bc9246e5bbf0 --- /dev/null +++ b/shared-bindings/audiodelays/__init__.h @@ -0,0 +1,7 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2024 Mark Komus +// +// SPDX-License-Identifier: MIT + +#pragma once diff --git a/shared-module/audiodelays/Echo.c b/shared-module/audiodelays/Echo.c new file mode 100644 index 0000000000000..3f45162cb5e93 --- /dev/null +++ b/shared-module/audiodelays/Echo.c @@ -0,0 +1,531 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2024 Mark Komus, Cooper Dalrymple +// +// SPDX-License-Identifier: MIT +#include "shared-bindings/audiodelays/Echo.h" + +#include +#include "py/runtime.h" + +void common_hal_audiodelays_echo_construct(audiodelays_echo_obj_t *self, uint32_t max_delay_ms, + mp_obj_t delay_ms, mp_obj_t decay, mp_obj_t mix, + uint32_t buffer_size, uint8_t bits_per_sample, + bool samples_signed, uint8_t channel_count, uint32_t sample_rate, bool freq_shift) { + + // Set whether the echo shifts frequencies as the delay changes like a doppler effect + self->freq_shift = freq_shift; + + // Basic settings every effect and audio sample has + // These are the effects values, not the source sample(s) + self->bits_per_sample = bits_per_sample; // Most common is 16, but 8 is also supported in many places + self->samples_signed = samples_signed; // Are the samples we provide signed (common is true) + self->channel_count = channel_count; // Channels can be 1 for mono or 2 for stereo + self->sample_rate = sample_rate; // Sample rate for the effect, this generally needs to match all audio objects + + // 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(self->buffer_len); + if (self->buffer[0] == NULL) { + common_hal_audiodelays_echo_deinit(self); + m_malloc_fail(self->buffer_len); + } + memset(self->buffer[0], 0, self->buffer_len); + + self->buffer[1] = m_malloc(self->buffer_len); + if (self->buffer[1] == NULL) { + common_hal_audiodelays_echo_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 echo effect's starting values. For a different effect this section will change + + // If we did not receive a BlockInput we need to create a default float value + if (decay == MP_OBJ_NULL) { + decay = mp_obj_new_float(0.7); + } + synthio_block_assign_slot(decay, &self->decay, MP_QSTR_decay); + + if (delay_ms == MP_OBJ_NULL) { + delay_ms = mp_obj_new_float(250.0); + } + synthio_block_assign_slot(delay_ms, &self->delay_ms, MP_QSTR_delay_ms); + + if (mix == MP_OBJ_NULL) { + mix = mp_obj_new_float(0.5); + } + synthio_block_assign_slot(mix, &self->mix, MP_QSTR_mix); + + // Many effects may need buffers of what was played this shows how it was done for the echo + // A maximum length buffer was created and then the current echo length can be dynamically changes + // without having to reallocate a large chunk of memory. + + // Allocate the echo buffer for the max possible delay, echo is always 16-bit + self->max_delay_ms = max_delay_ms; + self->max_echo_buffer_len = self->sample_rate / 1000.0f * max_delay_ms * (self->channel_count * sizeof(uint16_t)); // bytes + self->echo_buffer = m_malloc(self->max_echo_buffer_len); + if (self->echo_buffer == NULL) { + common_hal_audiodelays_echo_deinit(self); + m_malloc_fail(self->max_echo_buffer_len); + } + memset(self->echo_buffer, 0, self->max_echo_buffer_len); + + // calculate everything needed for the current delay + mp_float_t f_delay_ms = synthio_block_slot_get(&self->delay_ms); + recalculate_delay(self, f_delay_ms); + + // read is where we read previous echo from delay_ms ago to play back now + // write is where the store the latest playing sample to echo back later + self->echo_buffer_read_pos = self->buffer_len / sizeof(uint16_t); + self->echo_buffer_write_pos = 0; + + // where we read the previous echo from delay_ms ago to play back now (for freq shift) + self->echo_buffer_left_pos = self->echo_buffer_right_pos = 0; +} + +bool common_hal_audiodelays_echo_deinited(audiodelays_echo_obj_t *self) { + if (self->echo_buffer == NULL) { + return true; + } + return false; +} + +void common_hal_audiodelays_echo_deinit(audiodelays_echo_obj_t *self) { + if (common_hal_audiodelays_echo_deinited(self)) { + return; + } + self->echo_buffer = NULL; + self->buffer[0] = NULL; + self->buffer[1] = NULL; +} + +mp_obj_t common_hal_audiodelays_echo_get_delay_ms(audiodelays_echo_obj_t *self) { + return self->delay_ms.obj; +} + +void common_hal_audiodelays_echo_set_delay_ms(audiodelays_echo_obj_t *self, mp_obj_t delay_ms) { + synthio_block_assign_slot(delay_ms, &self->delay_ms, MP_QSTR_delay_ms); + + mp_float_t f_delay_ms = synthio_block_slot_get(&self->delay_ms); + + recalculate_delay(self, f_delay_ms); +} + +void recalculate_delay(audiodelays_echo_obj_t *self, mp_float_t f_delay_ms) { + if (self->freq_shift) { + // Calculate the rate of iteration over the echo buffer with 8 sub-bits + self->echo_buffer_rate = MAX(self->max_delay_ms / f_delay_ms * 256.0f, 1.0); + self->echo_buffer_len = self->max_echo_buffer_len; + } else { + // Calculate the current echo buffer length in bytes + uint32_t new_echo_buffer_len = self->sample_rate / 1000.0f * f_delay_ms * (self->channel_count * sizeof(uint16_t)); + + // Check if our new echo is too long for our maximum buffer + if (new_echo_buffer_len > self->max_echo_buffer_len) { + return; + } else if (new_echo_buffer_len < 0.0) { // or too short! + return; + } + + // If the echo buffer is larger then our audio buffer weird things happen + if (new_echo_buffer_len < self->buffer_len) { + return; + } + + self->echo_buffer_len = new_echo_buffer_len; + + // Clear the now unused part of the buffer or some weird artifacts appear + memset(self->echo_buffer + self->echo_buffer_len, 0, self->max_echo_buffer_len - self->echo_buffer_len); + } + + self->current_delay_ms = f_delay_ms; +} + +mp_obj_t common_hal_audiodelays_echo_get_decay(audiodelays_echo_obj_t *self) { + return self->decay.obj; +} + +void common_hal_audiodelays_echo_set_decay(audiodelays_echo_obj_t *self, mp_obj_t decay) { + synthio_block_assign_slot(decay, &self->decay, MP_QSTR_decay); +} + +mp_obj_t common_hal_audiodelays_echo_get_mix(audiodelays_echo_obj_t *self) { + return self->mix.obj; +} + +void common_hal_audiodelays_echo_set_mix(audiodelays_echo_obj_t *self, mp_obj_t arg) { + synthio_block_assign_slot(arg, &self->mix, MP_QSTR_mix); +} + +bool common_hal_audiodelays_echo_get_freq_shift(audiodelays_echo_obj_t *self) { + return self->freq_shift; +} + +void common_hal_audiodelays_echo_set_freq_shift(audiodelays_echo_obj_t *self, bool freq_shift) { + self->freq_shift = freq_shift; + uint32_t delay_ms = (uint32_t)synthio_block_slot_get(&self->delay_ms); + recalculate_delay(self, delay_ms); +} + +uint32_t common_hal_audiodelays_echo_get_sample_rate(audiodelays_echo_obj_t *self) { + return self->sample_rate; +} + +uint8_t common_hal_audiodelays_echo_get_channel_count(audiodelays_echo_obj_t *self) { + return self->channel_count; +} + +uint8_t common_hal_audiodelays_echo_get_bits_per_sample(audiodelays_echo_obj_t *self) { + return self->bits_per_sample; +} + +void audiodelays_echo_reset_buffer(audiodelays_echo_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->echo_buffer, 0, self->max_echo_buffer_len); +} + +bool common_hal_audiodelays_echo_get_playing(audiodelays_echo_obj_t *self) { + return self->sample != NULL; +} + +void common_hal_audiodelays_echo_play(audiodelays_echo_obj_t *self, mp_obj_t sample, bool loop) { + // When a sample is to be played we must ensure the samples values matches what we expect + // Then we reset the sample and get the first buffer to play + // The get_buffer function will actually process that data + + if (audiosample_sample_rate(sample) != self->sample_rate) { + mp_raise_ValueError_varg(MP_ERROR_TEXT("The sample's %q does not match"), MP_QSTR_sample_rate); + } + if (audiosample_channel_count(sample) != self->channel_count) { + mp_raise_ValueError_varg(MP_ERROR_TEXT("The sample's %q does not match"), MP_QSTR_channel_count); + } + if (audiosample_bits_per_sample(sample) != self->bits_per_sample) { + mp_raise_ValueError_varg(MP_ERROR_TEXT("The sample's %q does not match"), MP_QSTR_bits_per_sample); + } + bool single_buffer; + bool samples_signed; + uint32_t max_buffer_length; + uint8_t spacing; + audiosample_get_buffer_structure(sample, false, &single_buffer, &samples_signed, &max_buffer_length, &spacing); + if (samples_signed != self->samples_signed) { + mp_raise_ValueError_varg(MP_ERROR_TEXT("The sample's %q does not match"), MP_QSTR_signedness); + } + + 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->bits_per_sample / 8); + // Store if we have more data in the sample to retrieve + self->more_data = result == GET_BUFFER_MORE_DATA; + + return; +} + +void common_hal_audiodelays_echo_stop(audiodelays_echo_obj_t *self) { + // When the sample is set to stop playing do any cleanup here + // For echo we clear the sample but the echo continues until the object reading our effect stops + self->sample = NULL; + return; +} + +#define RANGE_LOW_16 (-28000) +#define RANGE_HIGH_16 (28000) +#define RANGE_SHIFT_16 (16) +#define RANGE_SCALE_16 (0xfffffff / (32768 * 2 - RANGE_HIGH_16)) // 2 for echo+sample + +// dynamic range compression via a downward compressor with hard knee +// +// When the output value is within the range +-28000 (about 85% of full scale), +// it is unchanged. Otherwise, it undergoes a gain reduction so that the +// largest possible values, (+32768,-32767) * 2 (2 for echo and sample), +// still fit within the output range +// +// This produces a much louder overall volume with multiple voices, without +// much additional processing. +// +// https://en.wikipedia.org/wiki/Dynamic_range_compression +static +int16_t mix_down_sample(int32_t sample) { + if (sample < RANGE_LOW_16) { + sample = (((sample - RANGE_LOW_16) * RANGE_SCALE_16) >> RANGE_SHIFT_16) + RANGE_LOW_16; + } else if (sample > RANGE_HIGH_16) { + sample = (((sample - RANGE_HIGH_16) * RANGE_SCALE_16) >> RANGE_SHIFT_16) + RANGE_HIGH_16; + } + return sample; +} + +audioio_get_buffer_result_t audiodelays_echo_get_buffer(audiodelays_echo_obj_t *self, bool single_channel_output, uint8_t channel, + uint8_t **buffer, uint32_t *buffer_length) { + + if (!single_channel_output) { + channel = 0; + } + + // get the effect values we need from the BlockInput. These may change at run time so you need to do bounds checking if required + mp_float_t mix = MIN(1.0, MAX(synthio_block_slot_get(&self->mix), 0.0)); + mp_float_t decay = MIN(1.0, MAX(synthio_block_slot_get(&self->decay), 0.0)); + + uint32_t delay_ms = (uint32_t)synthio_block_slot_get(&self->delay_ms); + if (self->current_delay_ms != delay_ms) { + recalculate_delay(self, delay_ms); + } + + // 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->bits_per_sample / 8); + + // The echo buffer is always stored as a 16-bit value internally + int16_t *echo_buffer = (int16_t *)self->echo_buffer; + uint32_t echo_buf_len = self->echo_buffer_len / sizeof(uint16_t); + + // Set our echo buffer position accounting for stereo + uint32_t echo_buffer_pos = 0; + if (self->freq_shift) { + echo_buffer_pos = self->echo_buffer_left_pos; + if (channel == 1) { + echo_buffer_pos = self->echo_buffer_right_pos; + } + } + + // 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 but we still need to play the echo + 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->bits_per_sample / 8); + self->more_data = result == GET_BUFFER_MORE_DATA; + } + } + + // If we have no sample keep the echo echoing + if (self->sample == NULL) { + if (mix <= 0.01) { // Mix of 0 is pure sample sound. We have no sample so no sound + if (self->samples_signed) { + memset(word_buffer, 0, length * (self->bits_per_sample / 8)); + } else { + // For unsigned samples set to the middle which is "quiet" + if (MP_LIKELY(self->bits_per_sample == 16)) { + memset(word_buffer, 32768, length * (self->bits_per_sample / 8)); + } else { + memset(hword_buffer, 128, length * (self->bits_per_sample / 8)); + } + } + } else { + // Since we have no sample we can just iterate over the our entire remaining buffer and finish + for (uint32_t i = 0; i < length; i++) { + int16_t echo, word = 0; + uint32_t next_buffer_pos = 0; + + if (self->freq_shift) { + echo = echo_buffer[echo_buffer_pos >> 8]; + next_buffer_pos = echo_buffer_pos + self->echo_buffer_rate; + + word = echo * decay; + for (uint32_t j = echo_buffer_pos >> 8; j < next_buffer_pos >> 8; j++) { + echo_buffer[j % echo_buf_len] = word; + } + } else { + echo = echo_buffer[self->echo_buffer_read_pos++]; + word = echo * decay; + echo_buffer[self->echo_buffer_write_pos++] = word; + } + + word = echo * mix; + + if (MP_LIKELY(self->bits_per_sample == 16)) { + word_buffer[i] = word; + if (!self->samples_signed) { + word_buffer[i] ^= 0x8000; + } + } else { + hword_buffer[i] = (int8_t)word; + if (!self->samples_signed) { + hword_buffer[i] ^= 0x80; + } + } + + if (self->freq_shift) { + echo_buffer_pos = next_buffer_pos % (echo_buf_len << 8); + } else { + if (self->echo_buffer_read_pos >= echo_buf_len) { + self->echo_buffer_read_pos = 0; + } + if (self->echo_buffer_write_pos >= echo_buf_len) { + self->echo_buffer_write_pos = 0; + } + } + } + } + + length = 0; + } else { + // we have a sample to play and echo + // Determine how many bytes we can process to our buffer, the less of the sample we have left and our buffer remaining + uint32_t n = MIN(self->sample_buffer_length, length); + + 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 + + if (mix <= 0.01) { // if mix is zero pure sample only + for (uint32_t i = 0; i < n; i++) { + if (MP_LIKELY(self->bits_per_sample == 16)) { + word_buffer[i] = sample_src[i]; + } else { + hword_buffer[i] = sample_hsrc[i]; + } + } + } else { + for (uint32_t i = 0; i < n; i++) { + int32_t sample_word = 0; + if (MP_LIKELY(self->bits_per_sample == 16)) { + sample_word = sample_src[i]; + } else { + if (self->samples_signed) { + sample_word = sample_hsrc[i]; + } else { + // Be careful here changing from an 8 bit unsigned to signed into a 32-bit signed + sample_word = (int8_t)(((uint8_t)sample_hsrc[i]) ^ 0x80); + } + } + + int32_t echo, word = 0; + uint32_t next_buffer_pos = 0; + if (self->freq_shift) { + echo = echo_buffer[echo_buffer_pos >> 8]; + next_buffer_pos = echo_buffer_pos + self->echo_buffer_rate; + word = echo * decay + sample_word; + } else { + echo = echo_buffer[self->echo_buffer_read_pos++]; + word = echo * decay + sample_word; + } + + if (MP_LIKELY(self->bits_per_sample == 16)) { + word = mix_down_sample(word); + if (self->freq_shift) { + for (uint32_t j = echo_buffer_pos >> 8; j < next_buffer_pos >> 8; j++) { + echo_buffer[j % echo_buf_len] = (int16_t)word; + } + } else { + echo_buffer[self->echo_buffer_write_pos++] = (int16_t)word; + } + } else { + // Do not have mix_down for 8 bit so just hard cap samples into 1 byte + if (word > 127) { + word = 127; + } else if (word < -128) { + word = -128; + } + if (self->freq_shift) { + for (uint32_t j = echo_buffer_pos >> 8; j < next_buffer_pos >> 8; j++) { + echo_buffer[j % echo_buf_len] = (int8_t)word; + } + } else { + echo_buffer[self->echo_buffer_write_pos++] = (int8_t)word; + } + } + + word = echo + sample_word; + + if (MP_LIKELY(self->bits_per_sample == 16)) { + word_buffer[i] = (sample_word * (1.0 - mix)) + (word * mix); + if (!self->samples_signed) { + word_buffer[i] ^= 0x8000; + } + } else { + int8_t mixed = (sample_word * (1.0 - mix)) + (word * mix); + if (self->samples_signed) { + hword_buffer[i] = mixed; + } else { + hword_buffer[i] = (uint8_t)mixed ^ 0x80; + } + } + + if (self->freq_shift) { + echo_buffer_pos = next_buffer_pos % (echo_buf_len << 8); + } else { + if (self->echo_buffer_read_pos >= echo_buf_len) { + self->echo_buffer_read_pos = 0; + } + if (self->echo_buffer_write_pos >= echo_buf_len) { + self->echo_buffer_write_pos = 0; + } + } + } + } + + // Update the remaining length and the buffer positions based on how much we wrote into our buffer + length -= n; + word_buffer += n; + hword_buffer += n; + self->sample_remaining_buffer += (n * (self->bits_per_sample / 8)); + self->sample_buffer_length -= n; + } + } + + if (self->freq_shift) { + if (channel == 0) { + self->echo_buffer_left_pos = echo_buffer_pos; + } else if (channel == 1) { + self->echo_buffer_right_pos = echo_buffer_pos; + } + } + + // 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; + + // Echo 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; +} + +void audiodelays_echo_get_buffer_structure(audiodelays_echo_obj_t *self, bool single_channel_output, + bool *single_buffer, bool *samples_signed, uint32_t *max_buffer_length, uint8_t *spacing) { + + // Return information about the effect's buffer (not the sample's) + // These are used by calling audio objects to determine how to handle the effect's buffer + *single_buffer = false; + *samples_signed = self->samples_signed; + *max_buffer_length = self->buffer_len; + if (single_channel_output) { + *spacing = self->channel_count; + } else { + *spacing = 1; + } +} diff --git a/shared-module/audiodelays/Echo.h b/shared-module/audiodelays/Echo.h new file mode 100644 index 0000000000000..8742f83898a75 --- /dev/null +++ b/shared-module/audiodelays/Echo.h @@ -0,0 +1,67 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2024 Mark Komus, Cooper Dalrymple +// +// 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_echo_type; + +typedef struct { + mp_obj_base_t base; + uint32_t max_delay_ms; + synthio_block_slot_t delay_ms; + uint32_t current_delay_ms; + synthio_block_slot_t decay; + synthio_block_slot_t mix; + + uint8_t bits_per_sample; + bool samples_signed; + uint8_t channel_count; + uint32_t sample_rate; + + 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; + bool freq_shift; // does the echo shift frequencies if delay changes + + int8_t *echo_buffer; + uint32_t echo_buffer_len; // bytes + uint32_t max_echo_buffer_len; // bytes + + uint32_t echo_buffer_read_pos; // words + uint32_t echo_buffer_write_pos; // words + + uint32_t echo_buffer_rate; // words << 8 + uint32_t echo_buffer_left_pos; // words << 8 + uint32_t echo_buffer_right_pos; // words << 8 + + mp_obj_t sample; +} audiodelays_echo_obj_t; + +void recalculate_delay(audiodelays_echo_obj_t *self, mp_float_t f_delay_ms); + +void audiodelays_echo_reset_buffer(audiodelays_echo_obj_t *self, + bool single_channel_output, + uint8_t channel); + +audioio_get_buffer_result_t audiodelays_echo_get_buffer(audiodelays_echo_obj_t *self, + bool single_channel_output, + uint8_t channel, + uint8_t **buffer, + uint32_t *buffer_length); // length in bytes + +void audiodelays_echo_get_buffer_structure(audiodelays_echo_obj_t *self, bool single_channel_output, + bool *single_buffer, bool *samples_signed, + uint32_t *max_buffer_length, uint8_t *spacing); diff --git a/shared-module/audiodelays/__init__.c b/shared-module/audiodelays/__init__.c new file mode 100644 index 0000000000000..7b5abdb4ff317 --- /dev/null +++ b/shared-module/audiodelays/__init__.c @@ -0,0 +1,5 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2024 Mark Komus +// +// SPDX-License-Identifier: MIT diff --git a/shared-module/audiodelays/__init__.h b/shared-module/audiodelays/__init__.h new file mode 100644 index 0000000000000..3bc9246e5bbf0 --- /dev/null +++ b/shared-module/audiodelays/__init__.h @@ -0,0 +1,7 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2024 Mark Komus +// +// SPDX-License-Identifier: MIT + +#pragma once diff --git a/shared-module/audiomixer/MixerVoice.c b/shared-module/audiomixer/MixerVoice.c index c32d37cdec288..cba7544b1e65b 100644 --- a/shared-module/audiomixer/MixerVoice.c +++ b/shared-module/audiomixer/MixerVoice.c @@ -32,13 +32,13 @@ void common_hal_audiomixer_mixervoice_set_level(audiomixer_mixervoice_obj_t *sel void common_hal_audiomixer_mixervoice_play(audiomixer_mixervoice_obj_t *self, mp_obj_t sample, bool loop) { if (audiosample_sample_rate(sample) != self->parent->sample_rate) { - mp_raise_ValueError(MP_ERROR_TEXT("The sample's sample rate does not match the mixer's")); + mp_raise_ValueError_varg(MP_ERROR_TEXT("The sample's %q does not match"), MP_QSTR_sample_rate); } if (audiosample_channel_count(sample) != self->parent->channel_count) { - mp_raise_ValueError(MP_ERROR_TEXT("The sample's channel count does not match the mixer's")); + mp_raise_ValueError_varg(MP_ERROR_TEXT("The sample's %q does not match"), MP_QSTR_channel_count); } if (audiosample_bits_per_sample(sample) != self->parent->bits_per_sample) { - mp_raise_ValueError(MP_ERROR_TEXT("The sample's bits_per_sample does not match the mixer's")); + mp_raise_ValueError_varg(MP_ERROR_TEXT("The sample's %q does not match"), MP_QSTR_bits_per_sample); } bool single_buffer; bool samples_signed; @@ -47,7 +47,7 @@ void common_hal_audiomixer_mixervoice_play(audiomixer_mixervoice_obj_t *self, mp audiosample_get_buffer_structure(sample, false, &single_buffer, &samples_signed, &max_buffer_length, &spacing); if (samples_signed != self->parent->samples_signed) { - mp_raise_ValueError(MP_ERROR_TEXT("The sample's signedness does not match the mixer's")); + mp_raise_ValueError_varg(MP_ERROR_TEXT("The sample's %q does not match"), MP_QSTR_signedness); } self->sample = sample; self->loop = loop;