diff --git a/locale/circuitpython.pot b/locale/circuitpython.pot index 32f6e4ef631..bc0286dfe61 100644 --- a/locale/circuitpython.pot +++ b/locale/circuitpython.pot @@ -3724,6 +3724,7 @@ msgid "file must be a file opened in byte mode" msgstr "" #: shared-bindings/audiodelays/Chorus.c shared-bindings/audiodelays/Echo.c +#: shared-bindings/audiodelays/GranularPitchShift.c #: shared-bindings/audiodelays/MultiTapDelay.c #: shared-bindings/audiodelays/PitchShift.c #: shared-bindings/audiofilters/Distortion.c diff --git a/ports/raspberrypi/boards/archi/mpconfigboard.mk b/ports/raspberrypi/boards/archi/mpconfigboard.mk index 1189e6879b9..faf9833da62 100644 --- a/ports/raspberrypi/boards/archi/mpconfigboard.mk +++ b/ports/raspberrypi/boards/archi/mpconfigboard.mk @@ -20,3 +20,5 @@ FROZEN_MPY_DIRS += $(TOP)/frozen/Adafruit_CircuitPython_Register FROZEN_MPY_DIRS += $(TOP)/frozen/Adafruit_CircuitPython_seesaw FROZEN_MPY_DIRS += $(TOP)/frozen/Adafruit_CircuitPython_framebuf FROZEN_MPY_DIRS += $(TOP)/frozen/Adafruit_CircuitPython_SimpleIO + +OPTIMIZATION_FLAGS = -O2 diff --git a/ports/unix/variants/coverage/mpconfigvariant.mk b/ports/unix/variants/coverage/mpconfigvariant.mk index 292e4de8169..682fe77459e 100644 --- a/ports/unix/variants/coverage/mpconfigvariant.mk +++ b/ports/unix/variants/coverage/mpconfigvariant.mk @@ -37,6 +37,7 @@ SRC_BITMAP := \ shared-bindings/audiodelays/Echo.c \ shared-bindings/audiodelays/Chorus.c \ shared-bindings/audiodelays/PitchShift.c \ + shared-bindings/audiodelays/GranularPitchShift.c \ shared-bindings/audiodelays/MultiTapDelay.c \ shared-bindings/audiodelays/__init__.c \ shared-bindings/audiofilters/Distortion.c \ @@ -85,6 +86,7 @@ SRC_BITMAP := \ shared-module/audiodelays/Echo.c \ shared-module/audiodelays/Chorus.c \ shared-module/audiodelays/PitchShift.c \ + shared-module/audiodelays/GranularPitchShift.c \ shared-module/audiodelays/MultiTapDelay.c \ shared-module/audiodelays/__init__.c \ shared-module/audiofilters/Distortion.c \ diff --git a/py/circuitpy_defns.mk b/py/circuitpy_defns.mk index 63a874b094e..7dfb9ae7c7d 100644 --- a/py/circuitpy_defns.mk +++ b/py/circuitpy_defns.mk @@ -713,6 +713,7 @@ SRC_SHARED_MODULE_ALL = \ audiodelays/Echo.c \ audiodelays/Chorus.c \ audiodelays/PitchShift.c \ + audiodelays/GranularPitchShift.c \ audiodelays/MultiTapDelay.c \ audiodelays/__init__.c \ audiofilters/Distortion.c \ diff --git a/shared-bindings/audiodelays/GranularPitchShift.c b/shared-bindings/audiodelays/GranularPitchShift.c new file mode 100644 index 00000000000..afbda30156a --- /dev/null +++ b/shared-bindings/audiodelays/GranularPitchShift.c @@ -0,0 +1,315 @@ +// 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/GranularPitchShift.h" +#include "shared-bindings/audiocore/__init__.h" +#include "shared-module/audiodelays/GranularPitchShift.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 GranularPitchShift: +//| """A granular-synthesis pitch shift effect""" +//| +//| def __init__( +//| self, +//| semitones: synthio.BlockInput = 0.0, +//| mix: synthio.BlockInput = 1.0, +//| grain_size: int = 1024, +//| density: int = 2, +//| spread: float = 0.0, +//| buffer_size: int = 512, +//| sample_rate: int = 8000, +//| bits_per_sample: int = 16, +//| samples_signed: bool = True, +//| channel_count: int = 1, +//| ) -> None: +//| """Create a pitch shift effect that shifts pitch using granular synthesis: a cloud of +//| short, overlapping, individually-enveloped grains resampled from a capture buffer. Unlike +//| `PitchShift` (a single crossfaded window), the overlapping grains tend to sound smoother +//| and less "robotic" at large shifts. This effect introduces a slight delay in the output +//| proportional to ``grain_size``. +//| +//| 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 synthio.BlockInput semitones: The amount of pitch shifting in semitones (1/12th of an octave) +//| :param synthio.BlockInput mix: The mix as a ratio of the sample (0.0) to the effect (1.0) +//| :param int grain_size: The length in samples of each grain +//| :param int density: The number of overlapping grains (overlap factor). Must be between 1 and 8. +//| :param float spread: The amount of random jitter applied to each grain's start position, +//| from 0.0 (deterministic; every grain starts at the same offset) to 1.0 (maximum jitter). +//| Higher values give the classic granular "cloud" texture. Jitter is always backward in +//| time, so it never introduces additional latency beyond ``grain_size``. +//| :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) +//| +//| Shifting the pitch of a synth by 5 semitones:: +//| +//| import time +//| import board +//| import audiobusio +//| import synthio +//| import audiodelays +//| from pwmio import PWMOut +//| import adafruit_tlv320 +//| +//| mclk_pwm = PWMOut(board.I2S_MCLK, frequency=15_000_000, duty_cycle=2**15) +//| i2c = board.I2C() +//| dac = adafruit_tlv320.TLV320DAC3100(i2c) +//| dac.configure_clocks(sample_rate=44100, bit_depth=16, mclk_freq=15_000_000) +//| dac.headphone_output = True +//| audio = audiobusio.I2SOut(board.I2S_BCLK, board.I2S_WS, board.I2S_DIN) +//| synth = synthio.Synthesizer(channel_count=1, sample_rate=44100) +//| pitch_shift = audiodelays.GranularPitchShift(semitones=5.0, mix=1.0, spread=0.25, grain_size=2048, density=2, buffer_size=1024, channel_count=1, sample_rate=44100) +//| pitch_shift.play(synth) +//| audio.play(pitch_shift) +//| +//| while True: +//| for notenum in (60, 64, 67, 71): +//| synth.press(notenum) +//| time.sleep(0.25) +//| synth.release_all()""" +//| ... +//| +static mp_obj_t audiodelays_granular_pitch_shift_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *all_args) { + enum { ARG_semitones, ARG_mix, ARG_grain_size, ARG_density, ARG_spread, 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_semitones, MP_ARG_OBJ | MP_ARG_KW_ONLY, {.u_obj = MP_ROM_INT(0)} }, + { MP_QSTR_mix, MP_ARG_OBJ | MP_ARG_KW_ONLY, {.u_obj = MP_ROM_INT(1)} }, + { MP_QSTR_grain_size, MP_ARG_INT | MP_ARG_KW_ONLY, {.u_int = 1024} }, + { MP_QSTR_density, MP_ARG_INT | MP_ARG_KW_ONLY, {.u_int = 2} }, + { MP_QSTR_spread, MP_ARG_OBJ | MP_ARG_KW_ONLY, {.u_obj = MP_ROM_INT(0)} }, + { 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 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 grain_size = mp_arg_validate_int_min(args[ARG_grain_size].u_int, 2, MP_QSTR_grain_size); + mp_int_t density = mp_arg_validate_int_range(args[ARG_density].u_int, 1, GRANULAR_MAX_GRAINS, MP_QSTR_density); + 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_granular_pitch_shift_obj_t *self = + mp_obj_malloc(audiodelays_granular_pitch_shift_obj_t, &audiodelays_granular_pitch_shift_type); + common_hal_audiodelays_granular_pitch_shift_construct(self, + args[ARG_semitones].u_obj, + args[ARG_mix].u_obj, + grain_size, + density, + mp_obj_get_float(args[ARG_spread].u_obj), + 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 GranularPitchShift.""" +//| ... +//| +static mp_obj_t audiodelays_granular_pitch_shift_deinit(mp_obj_t self_in) { + audiodelays_granular_pitch_shift_obj_t *self = MP_OBJ_TO_PTR(self_in); + common_hal_audiodelays_granular_pitch_shift_deinit(self); + return mp_const_none; +} +static MP_DEFINE_CONST_FUN_OBJ_1(audiodelays_granular_pitch_shift_deinit_obj, audiodelays_granular_pitch_shift_deinit); + +static void check_for_deinit(audiodelays_granular_pitch_shift_obj_t *self) { + audiosample_check_for_deinit(&self->base); +} + + +//| def __enter__(self) -> GranularPitchShift: +//| """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_granular_pitch_shift_obj___exit__(size_t n_args, const mp_obj_t *args) { + (void)n_args; + common_hal_audiodelays_granular_pitch_shift_deinit(args[0]); + return mp_const_none; +} +static MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(audiodelays_granular_pitch_shift___exit___obj, 4, 4, audiodelays_granular_pitch_shift_obj___exit__); + + +//| semitones: synthio.BlockInput +//| """The amount of pitch shifting in semitones (1/12th of an octave).""" +//| +static mp_obj_t audiodelays_granular_pitch_shift_obj_get_semitones(mp_obj_t self_in) { + audiodelays_granular_pitch_shift_obj_t *self = MP_OBJ_TO_PTR(self_in); + return common_hal_audiodelays_granular_pitch_shift_get_semitones(self); +} +MP_DEFINE_CONST_FUN_OBJ_1(audiodelays_granular_pitch_shift_get_semitones_obj, audiodelays_granular_pitch_shift_obj_get_semitones); + +static mp_obj_t audiodelays_granular_pitch_shift_obj_set_semitones(mp_obj_t self_in, mp_obj_t semitones_in) { + audiodelays_granular_pitch_shift_obj_t *self = MP_OBJ_TO_PTR(self_in); + common_hal_audiodelays_granular_pitch_shift_set_semitones(self, semitones_in); + return mp_const_none; +} +MP_DEFINE_CONST_FUN_OBJ_2(audiodelays_granular_pitch_shift_set_semitones_obj, audiodelays_granular_pitch_shift_obj_set_semitones); + +MP_PROPERTY_GETSET(audiodelays_granular_pitch_shift_semitones_obj, + (mp_obj_t)&audiodelays_granular_pitch_shift_get_semitones_obj, + (mp_obj_t)&audiodelays_granular_pitch_shift_set_semitones_obj); + + +//| mix: synthio.BlockInput +//| """The output mix between 0 and 1 where 0 is only sample and 1 is all effect.""" +static mp_obj_t audiodelays_granular_pitch_shift_obj_get_mix(mp_obj_t self_in) { + return common_hal_audiodelays_granular_pitch_shift_get_mix(self_in); +} +MP_DEFINE_CONST_FUN_OBJ_1(audiodelays_granular_pitch_shift_get_mix_obj, audiodelays_granular_pitch_shift_obj_get_mix); + +static mp_obj_t audiodelays_granular_pitch_shift_obj_set_mix(mp_obj_t self_in, mp_obj_t mix_in) { + audiodelays_granular_pitch_shift_obj_t *self = MP_OBJ_TO_PTR(self_in); + common_hal_audiodelays_granular_pitch_shift_set_mix(self, mix_in); + return mp_const_none; +} +MP_DEFINE_CONST_FUN_OBJ_2(audiodelays_granular_pitch_shift_set_mix_obj, audiodelays_granular_pitch_shift_obj_set_mix); + +MP_PROPERTY_GETSET(audiodelays_granular_pitch_shift_mix_obj, + (mp_obj_t)&audiodelays_granular_pitch_shift_get_mix_obj, + (mp_obj_t)&audiodelays_granular_pitch_shift_set_mix_obj); + + +//| spread: float +//| """The amount of random jitter applied to each grain's start position, from 0.0 +//| (deterministic) to 1.0 (maximum jitter). Higher values give a thicker granular texture.""" +static mp_obj_t audiodelays_granular_pitch_shift_obj_get_spread(mp_obj_t self_in) { + audiodelays_granular_pitch_shift_obj_t *self = MP_OBJ_TO_PTR(self_in); + return mp_obj_new_float(common_hal_audiodelays_granular_pitch_shift_get_spread(self)); +} +MP_DEFINE_CONST_FUN_OBJ_1(audiodelays_granular_pitch_shift_get_spread_obj, audiodelays_granular_pitch_shift_obj_get_spread); + +static mp_obj_t audiodelays_granular_pitch_shift_obj_set_spread(mp_obj_t self_in, mp_obj_t spread_in) { + audiodelays_granular_pitch_shift_obj_t *self = MP_OBJ_TO_PTR(self_in); + common_hal_audiodelays_granular_pitch_shift_set_spread(self, mp_obj_get_float(spread_in)); + return mp_const_none; +} +MP_DEFINE_CONST_FUN_OBJ_2(audiodelays_granular_pitch_shift_set_spread_obj, audiodelays_granular_pitch_shift_obj_set_spread); + +MP_PROPERTY_GETSET(audiodelays_granular_pitch_shift_spread_obj, + (mp_obj_t)&audiodelays_granular_pitch_shift_get_spread_obj, + (mp_obj_t)&audiodelays_granular_pitch_shift_set_spread_obj); + + +//| playing: bool +//| """True when the effect is playing a sample. (read-only)""" +//| +static mp_obj_t audiodelays_granular_pitch_shift_obj_get_playing(mp_obj_t self_in) { + audiodelays_granular_pitch_shift_obj_t *self = MP_OBJ_TO_PTR(self_in); + check_for_deinit(self); + return mp_obj_new_bool(common_hal_audiodelays_granular_pitch_shift_get_playing(self)); +} +MP_DEFINE_CONST_FUN_OBJ_1(audiodelays_granular_pitch_shift_get_playing_obj, audiodelays_granular_pitch_shift_obj_get_playing); + +MP_PROPERTY_GETTER(audiodelays_granular_pitch_shift_playing_obj, + (mp_obj_t)&audiodelays_granular_pitch_shift_get_playing_obj); + + +//| def play(self, sample: circuitpython_typing.AudioSample, *, loop: bool = False) -> GranularPitchShift: +//| """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: GranularPitchShift""" +//| ... +//| +static mp_obj_t audiodelays_granular_pitch_shift_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_granular_pitch_shift_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_granular_pitch_shift_play(self, sample, args[ARG_loop].u_bool); + + return MP_OBJ_FROM_PTR(self); +} +MP_DEFINE_CONST_FUN_OBJ_KW(audiodelays_granular_pitch_shift_play_obj, 1, audiodelays_granular_pitch_shift_obj_play); + + +//| def stop(self) -> None: +//| """Stops playback of the sample.""" +//| ... +//| +//| +static mp_obj_t audiodelays_granular_pitch_shift_obj_stop(mp_obj_t self_in) { + audiodelays_granular_pitch_shift_obj_t *self = MP_OBJ_TO_PTR(self_in); + common_hal_audiodelays_granular_pitch_shift_stop(self); + return mp_const_none; +} +MP_DEFINE_CONST_FUN_OBJ_1(audiodelays_granular_pitch_shift_stop_obj, audiodelays_granular_pitch_shift_obj_stop); + + +static const mp_rom_map_elem_t audiodelays_granular_pitch_shift_locals_dict_table[] = { + // Methods + { MP_ROM_QSTR(MP_QSTR_deinit), MP_ROM_PTR(&audiodelays_granular_pitch_shift_deinit_obj) }, + { MP_ROM_QSTR(MP_QSTR___enter__), MP_ROM_PTR(&default___enter___obj) }, + { MP_ROM_QSTR(MP_QSTR___exit__), MP_ROM_PTR(&audiodelays_granular_pitch_shift___exit___obj) }, + { MP_ROM_QSTR(MP_QSTR_play), MP_ROM_PTR(&audiodelays_granular_pitch_shift_play_obj) }, + { MP_ROM_QSTR(MP_QSTR_stop), MP_ROM_PTR(&audiodelays_granular_pitch_shift_stop_obj) }, + + // Properties + { MP_ROM_QSTR(MP_QSTR_playing), MP_ROM_PTR(&audiodelays_granular_pitch_shift_playing_obj) }, + { MP_ROM_QSTR(MP_QSTR_semitones), MP_ROM_PTR(&audiodelays_granular_pitch_shift_semitones_obj) }, + { MP_ROM_QSTR(MP_QSTR_mix), MP_ROM_PTR(&audiodelays_granular_pitch_shift_mix_obj) }, + { MP_ROM_QSTR(MP_QSTR_spread), MP_ROM_PTR(&audiodelays_granular_pitch_shift_spread_obj) }, + AUDIOSAMPLE_FIELDS, +}; +static MP_DEFINE_CONST_DICT(audiodelays_granular_pitch_shift_locals_dict, audiodelays_granular_pitch_shift_locals_dict_table); + +static const audiosample_p_t audiodelays_granular_pitch_shift_proto = { + MP_PROTO_IMPLEMENT(MP_QSTR_protocol_audiosample) + .reset_buffer = (audiosample_reset_buffer_fun)audiodelays_granular_pitch_shift_reset_buffer, + .get_buffer = (audiosample_get_buffer_fun)audiodelays_granular_pitch_shift_get_buffer, +}; + +MP_DEFINE_CONST_OBJ_TYPE( + audiodelays_granular_pitch_shift_type, + MP_QSTR_GranularPitchShift, + MP_TYPE_FLAG_HAS_SPECIAL_ACCESSORS, + make_new, audiodelays_granular_pitch_shift_make_new, + locals_dict, &audiodelays_granular_pitch_shift_locals_dict, + protocol, &audiodelays_granular_pitch_shift_proto + ); diff --git a/shared-bindings/audiodelays/GranularPitchShift.h b/shared-bindings/audiodelays/GranularPitchShift.h new file mode 100644 index 00000000000..e5a518110bd --- /dev/null +++ b/shared-bindings/audiodelays/GranularPitchShift.h @@ -0,0 +1,31 @@ +// 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/GranularPitchShift.h" + +extern const mp_obj_type_t audiodelays_granular_pitch_shift_type; + +void common_hal_audiodelays_granular_pitch_shift_construct(audiodelays_granular_pitch_shift_obj_t *self, + mp_obj_t semitones, mp_obj_t mix, uint32_t grain_size, uint32_t density, + mp_float_t spread, uint32_t buffer_size, uint8_t bits_per_sample, bool samples_signed, + uint8_t channel_count, uint32_t sample_rate); + +void common_hal_audiodelays_granular_pitch_shift_deinit(audiodelays_granular_pitch_shift_obj_t *self); + +mp_obj_t common_hal_audiodelays_granular_pitch_shift_get_semitones(audiodelays_granular_pitch_shift_obj_t *self); +void common_hal_audiodelays_granular_pitch_shift_set_semitones(audiodelays_granular_pitch_shift_obj_t *self, mp_obj_t semitones); + +mp_obj_t common_hal_audiodelays_granular_pitch_shift_get_mix(audiodelays_granular_pitch_shift_obj_t *self); +void common_hal_audiodelays_granular_pitch_shift_set_mix(audiodelays_granular_pitch_shift_obj_t *self, mp_obj_t arg); + +mp_float_t common_hal_audiodelays_granular_pitch_shift_get_spread(audiodelays_granular_pitch_shift_obj_t *self); +void common_hal_audiodelays_granular_pitch_shift_set_spread(audiodelays_granular_pitch_shift_obj_t *self, mp_float_t spread); + +bool common_hal_audiodelays_granular_pitch_shift_get_playing(audiodelays_granular_pitch_shift_obj_t *self); +void common_hal_audiodelays_granular_pitch_shift_play(audiodelays_granular_pitch_shift_obj_t *self, mp_obj_t sample, bool loop); +void common_hal_audiodelays_granular_pitch_shift_stop(audiodelays_granular_pitch_shift_obj_t *self); diff --git a/shared-bindings/audiodelays/__init__.c b/shared-bindings/audiodelays/__init__.c index e93052eabfd..2125aa54683 100644 --- a/shared-bindings/audiodelays/__init__.c +++ b/shared-bindings/audiodelays/__init__.c @@ -13,6 +13,7 @@ #include "shared-bindings/audiodelays/Echo.h" #include "shared-bindings/audiodelays/Chorus.h" #include "shared-bindings/audiodelays/PitchShift.h" +#include "shared-bindings/audiodelays/GranularPitchShift.h" #include "shared-bindings/audiodelays/MultiTapDelay.h" //| """Support for audio delay effects @@ -26,6 +27,7 @@ static const mp_rom_map_elem_t audiodelays_module_globals_table[] = { { 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_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/GranularPitchShift.c b/shared-module/audiodelays/GranularPitchShift.c new file mode 100644 index 00000000000..d439270b48a --- /dev/null +++ b/shared-module/audiodelays/GranularPitchShift.c @@ -0,0 +1,470 @@ +// 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/GranularPitchShift.h" +#include "shared-bindings/audiocore/__init__.h" + +#include +#include "py/runtime.h" +#include + +void common_hal_audiodelays_granular_pitch_shift_construct(audiodelays_granular_pitch_shift_obj_t *self, + mp_obj_t semitones, mp_obj_t mix, uint32_t grain_size, uint32_t density, + mp_float_t spread, uint32_t buffer_size, uint8_t bits_per_sample, bool samples_signed, + uint8_t channel_count, uint32_t sample_rate) { + + // Basic settings every effect and audio sample has + // These are the effect's values, not the source sample(s) + self->base.bits_per_sample = bits_per_sample; // Most common is 16, but 8 is also supported in many places + self->base.samples_signed = samples_signed; // Are the samples we provide signed + 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_without_collect(self->buffer_len); + if (self->buffer[0] == NULL) { + common_hal_audiodelays_granular_pitch_shift_deinit(self); + m_malloc_fail(self->buffer_len); + } + memset(self->buffer[0], 0, self->buffer_len); + + self->buffer[1] = m_malloc_without_collect(self->buffer_len); + if (self->buffer[1] == NULL) { + common_hal_audiodelays_granular_pitch_shift_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 effect's starting values. + + synthio_block_assign_slot(semitones, &self->semitones, MP_QSTR_semitones); + synthio_block_assign_slot(mix, &self->mix, MP_QSTR_mix); + + // Grain scheduling parameters. `density` (number of overlapping grains) is + // clamped to the fixed grain pool size so allocation stays deterministic. + self->grain_size = grain_size; + if (density < 1) { + density = 1; + } + if (density > GRANULAR_MAX_GRAINS) { + density = GRANULAR_MAX_GRAINS; + } + self->density = density; + + // Grain-start jitter amount and the PRNG that drives it. Seeded with a fixed + // nonzero constant so xorshift32 never degenerates to the all-zero state and + // the jitter sequence is reproducible from run to run. + common_hal_audiodelays_granular_pitch_shift_set_spread(self, spread); + self->rng_state = 0x1234abcdu; + + // Normalization for the overlap-add gain of the grain envelopes. A Hann + // window overlapped at hop = grain_size / density sums to a constant gain of + // density/2, so we scale the summed grains by 2/density in Q15 to keep the + // output at ~unity. Cap at 1.0 so the degenerate density==1 case (a single + // windowed grain, no overlap partner) is never amplified. + self->grain_gain = (1 << 15) * 2 / density; // 2/density in Q15 + if (self->grain_gain > (1 << 15)) { + self->grain_gain = (1 << 15); + } + + // Capture buffer (the delay line grains read from), stored as 16-bit, + // planar per channel. Length is grain_size * 2 words per channel so a grain + // starting grain_size words behind the write pointer never overruns the live + // write cursor even when reading ahead at a raised pitch + self->capture_len = self->grain_size * 2; // words per channel + uint32_t capture_bytes = self->capture_len * self->base.channel_count * sizeof(int16_t); + self->capture_buffer = m_malloc_without_collect(capture_bytes); + if (self->capture_buffer == NULL) { + common_hal_audiodelays_granular_pitch_shift_deinit(self); + m_malloc_fail(capture_bytes); + } + memset(self->capture_buffer, 0, capture_bytes); + self->write_index = 0; + + // Precompute the grain amplitude envelope: a raised-cosine (Hann) window in + // Q15 (0..32767), indexed directly by a grain's phase. + self->envelope_len = self->grain_size; + uint32_t envelope_bytes = self->envelope_len * sizeof(int16_t); + self->envelope_table = m_malloc_without_collect(envelope_bytes); + if (self->envelope_table == NULL) { + common_hal_audiodelays_granular_pitch_shift_deinit(self); + m_malloc_fail(envelope_bytes); + } + mp_float_t denom = (self->envelope_len > 1) ? (mp_float_t)(self->envelope_len - 1) : MICROPY_FLOAT_CONST(1.0); + for (uint32_t n = 0; n < self->envelope_len; n++) { + mp_float_t w = MICROPY_FLOAT_CONST(0.5) * + (MICROPY_FLOAT_CONST(1.0) - MICROPY_FLOAT_C_FUN(cos)( + MICROPY_FLOAT_CONST(2.0) * MICROPY_FLOAT_CONST(3.14159265358979323846) * (mp_float_t)n / denom)); + self->envelope_table[n] = (int16_t)(w * MICROPY_FLOAT_CONST(32767.0)); + } + + // Deactivate all grains and prime the scheduler so the first grain launches + // immediately on the first output sample. + for (uint32_t i = 0; i < GRANULAR_MAX_GRAINS; i++) { + self->grains[i].active = false; + } + self->samples_until_next_grain = 0; + + // Calculate the fixed-point read-rate increment applied to launched grains. + mp_float_t f_semitones = synthio_block_slot_get(&self->semitones); + granular_pitch_shift_recalculate_rate(self, f_semitones); +} + +void common_hal_audiodelays_granular_pitch_shift_deinit(audiodelays_granular_pitch_shift_obj_t *self) { + audiosample_mark_deinit(&self->base); + self->envelope_table = NULL; + self->capture_buffer = NULL; + self->buffer[0] = NULL; + self->buffer[1] = NULL; +} + +mp_obj_t common_hal_audiodelays_granular_pitch_shift_get_semitones(audiodelays_granular_pitch_shift_obj_t *self) { + return self->semitones.obj; +} + +void common_hal_audiodelays_granular_pitch_shift_set_semitones(audiodelays_granular_pitch_shift_obj_t *self, mp_obj_t semitones_in) { + synthio_block_assign_slot(semitones_in, &self->semitones, MP_QSTR_semitones); + mp_float_t semitones = synthio_block_slot_get(&self->semitones); + granular_pitch_shift_recalculate_rate(self, semitones); +} + +void granular_pitch_shift_recalculate_rate(audiodelays_granular_pitch_shift_obj_t *self, mp_float_t semitones) { + self->read_rate = (uint32_t)(MICROPY_FLOAT_C_FUN(pow)(2.0, semitones / MICROPY_FLOAT_CONST(12.0)) * (1 << GRANULAR_PITCH_READ_SHIFT)); + self->current_semitones = semitones; +} + +mp_obj_t common_hal_audiodelays_granular_pitch_shift_get_mix(audiodelays_granular_pitch_shift_obj_t *self) { + return self->mix.obj; +} + +void common_hal_audiodelays_granular_pitch_shift_set_mix(audiodelays_granular_pitch_shift_obj_t *self, mp_obj_t arg) { + synthio_block_assign_slot(arg, &self->mix, MP_QSTR_mix); +} + +mp_float_t common_hal_audiodelays_granular_pitch_shift_get_spread(audiodelays_granular_pitch_shift_obj_t *self) { + return self->spread; +} + +void common_hal_audiodelays_granular_pitch_shift_set_spread(audiodelays_granular_pitch_shift_obj_t *self, mp_float_t spread) { + if (spread < MICROPY_FLOAT_CONST(0.0)) { + spread = MICROPY_FLOAT_CONST(0.0); + } else if (spread > MICROPY_FLOAT_CONST(1.0)) { + spread = MICROPY_FLOAT_CONST(1.0); + } + self->spread = spread; +} + +void audiodelays_granular_pitch_shift_reset_buffer(audiodelays_granular_pitch_shift_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->capture_buffer, 0, self->capture_len * self->base.channel_count * sizeof(int16_t)); + + // Deactivate all grains and reset the scheduler/write cursor. + for (uint32_t i = 0; i < GRANULAR_MAX_GRAINS; i++) { + self->grains[i].active = false; + } + self->samples_until_next_grain = 0; + self->write_index = 0; +} + +bool common_hal_audiodelays_granular_pitch_shift_get_playing(audiodelays_granular_pitch_shift_obj_t *self) { + return self->sample != NULL; +} + +void common_hal_audiodelays_granular_pitch_shift_play(audiodelays_granular_pitch_shift_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; + + return; +} + +void common_hal_audiodelays_granular_pitch_shift_stop(audiodelays_granular_pitch_shift_obj_t *self) { + // When the sample is set to stop playing do any cleanup here + self->sample = NULL; + return; +} + +// xorshift32 PRNG for grain-start jitter. Kept local to this module so the +// effect doesn't depend on the `random` module being enabled in a build. +static uint32_t granular_pitch_shift_rand(audiodelays_granular_pitch_shift_obj_t *self) { + uint32_t x = self->rng_state; + x ^= x << 13; + x ^= x >> 17; + x ^= x << 5; + self->rng_state = x; + return x; +} + +// Launch a grain into the first free pool slot, seeded to read from the capture +// buffer starting grain_size words behind the current write cursor (so it reads +// already-captured audio) at the current pitch-shift read rate. When `spread` is +// nonzero the start is jittered up to a further grain_size words backward, which +// is what gives granular synthesis its characteristic "cloud" texture. Jitter is +// always backward (further behind the write cursor), so a grain never reads ahead +// of captured audio and the capture buffer (capture_len == grain_size * 2) is +// never overrun. Grain read state (read_index/phase) is per-frame / +// channel-independent; the per-channel plane offset is applied at read time. +static void granular_pitch_shift_launch_grain(audiodelays_granular_pitch_shift_obj_t *self) { + for (uint32_t g = 0; g < GRANULAR_MAX_GRAINS; g++) { + if (!self->grains[g].active) { + // Backward jitter in [0, spread * grain_size]. Capped at grain_size + // so grain_size + jitter <= capture_len (== grain_size * 2). + uint32_t jitter = 0; + if (self->spread > MICROPY_FLOAT_CONST(0.0)) { + uint32_t max_jitter = (uint32_t)(self->spread * (mp_float_t)self->grain_size); + if (max_jitter > 0) { + jitter = granular_pitch_shift_rand(self) % (max_jitter + 1); + } + } + uint32_t start = (self->write_index + self->capture_len - self->grain_size - jitter) % self->capture_len; + self->grains[g].active = true; + self->grains[g].read_index = start << GRANULAR_PITCH_READ_SHIFT; + self->grains[g].read_rate = self->read_rate; + self->grains[g].phase = 0; + self->grains[g].length = self->grain_size; + return; + } + } +} + +audioio_get_buffer_result_t audiodelays_granular_pitch_shift_get_buffer(audiodelays_granular_pitch_shift_obj_t *self, bool single_channel_output, uint8_t channel, + uint8_t **buffer, uint32_t *buffer_length) { + + // Grain scheduler + enveloped grain playback with dry/wet `mix` blending. + // Grains are launched at a fixed spacing (grain_size / density) and each + // active grain reads the capture buffer at its own pitch-shifted (fractional, + // linearly interpolated) read rate, scaled by a Hann amplitude envelope so + // overlapping grains fade in/out and add without seam clicks. The summed + // grains are normalized by grain_gain for ~unity overlap-add gain, then + // crossfaded against the dry input via the `mix` slot. The 8/16-bit, + // signed/unsigned, and mono/stereo (planar capture, buf_offset) paths are all + // handled below, mirroring PitchShift. + + 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); + + // The capture buffer (delay line) is always stored as 16-bit, planar per + // channel: channel c occupies capture_buffer[c * capture_len .. ). + int16_t *capture_buffer = self->capture_buffer; + + // Grains are launched this many frames apart (overlap factor `density`). + uint32_t grain_spacing = self->grain_size / self->density; + if (grain_spacing == 0) { + grain_spacing = 1; + } + + // 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) { + 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)) { + memset(word_buffer, 32768, length * (self->base.bits_per_sample / 8)); + } else { + memset(hword_buffer, 128, length * (self->base.bits_per_sample / 8)); + } + } + + // tick all block inputs + shared_bindings_synthio_lfo_tick(self->base.sample_rate, length / self->base.channel_count); + (void)synthio_block_slot_get(&self->semitones); + (void)synthio_block_slot_get(&self->mix); + + length = 0; + } else { + // we have a sample to play and apply effect + // 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(MIN(self->sample_buffer_length, length), SYNTHIO_MAX_DUR * self->base.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, n / self->base.channel_count); + mp_float_t semitones = synthio_block_slot_get(&self->semitones); + // Doubled (0.0..2.0) so the crossfade below can hold both dry and wet + // at full gain around the midpoint, matching PitchShift's mix curve. + mp_float_t mix = synthio_block_slot_get_limited(&self->mix, MICROPY_FLOAT_CONST(0.0), MICROPY_FLOAT_CONST(1.0)) * MICROPY_FLOAT_CONST(2.0); + + // Only recalculate rate if semitones has changed + if (memcmp(&semitones, &self->current_semitones, sizeof(mp_float_t))) { + granular_pitch_shift_recalculate_rate(self, semitones); + } + + for (uint32_t i = 0; i < n; i++) { + bool buf_offset = (channel == 1 || i % self->base.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); + } + } + + // Write the incoming sample into the capture buffer (the delay + // line grains read from) at the per-channel write cursor. + capture_buffer[self->write_index + self->capture_len * buf_offset] = (int16_t)sample_word; + + // Sum all active grains. Each grain reads the capture buffer at + // its own fractional read cursor (linearly interpolated between + // adjacent words), which is what produces the pitch shift, then + // is scaled by its amplitude envelope (Hann, indexed by the + // grain's phase) so grains fade in/out and overlap-add without + // seam clicks. + int32_t word = 0; + for (uint32_t g = 0; g < GRANULAR_MAX_GRAINS; g++) { + if (!self->grains[g].active) { + continue; + } + uint32_t read_index_fp = self->grains[g].read_index; + uint32_t ipart = read_index_fp >> GRANULAR_PITCH_READ_SHIFT; + uint32_t frac = read_index_fp & ((1 << GRANULAR_PITCH_READ_SHIFT) - 1); + uint32_t index_lo = ipart % self->capture_len; + uint32_t index_hi = (ipart + 1) % self->capture_len; + int32_t sample_lo = capture_buffer[index_lo + self->capture_len * buf_offset]; + int32_t sample_hi = capture_buffer[index_hi + self->capture_len * buf_offset]; + int32_t grain_out = sample_lo + (((sample_hi - sample_lo) * (int32_t)frac) >> GRANULAR_PITCH_READ_SHIFT); + // Apply the grain envelope (Q15). phase < length == envelope_len. + int32_t env = self->envelope_table[self->grains[g].phase]; + word += (grain_out * env) >> 15; + } + + // Normalize the overlap-add gain of the enveloped grains back to + // ~unity (int64 guards the Q15 multiply against overflow). This is + // the fully-wet (pitch-shifted) sample. + word = (int32_t)(((int64_t)word * (int64_t)self->grain_gain) >> 15); + + // Dry/wet crossfade: `mix` is doubled to 0.0..2.0 so both terms + // sit at full gain around the midpoint, then synthio_mix_down_sample + // scales/soft-clips the summed pair back into range (same curve as + // PitchShift). mix=0.0 -> dry input, mix=1.0 -> fully wet. + word = (int32_t)((sample_word * MIN(MICROPY_FLOAT_CONST(2.0) - mix, MICROPY_FLOAT_CONST(1.0))) + (word * MIN(mix, MICROPY_FLOAT_CONST(1.0)))); + word = synthio_mix_down_sample(word, SYNTHIO_MIX_DOWN_SCALE(2)); + + if (MP_LIKELY(self->base.bits_per_sample == 16)) { + word_buffer[i] = (int16_t)word; + if (!self->base.samples_signed) { + word_buffer[i] ^= 0x8000; + } + } else { + int8_t mixed = (int8_t)word; + if (self->base.samples_signed) { + hword_buffer[i] = mixed; + } else { + hword_buffer[i] = (uint8_t)mixed ^ 0x80; + } + } + + // Per-frame shared work (once per frame: mono every sample, + // interleaved stereo on the right-channel sample) so both + // channels read consistent grain state before it advances. + if (self->base.channel_count == 1 || buf_offset) { + // Advance and retire active grains (they were read above). + for (uint32_t g = 0; g < GRANULAR_MAX_GRAINS; g++) { + if (!self->grains[g].active) { + continue; + } + self->grains[g].read_index += self->grains[g].read_rate; + self->grains[g].phase++; + if (self->grains[g].phase >= self->grains[g].length) { + self->grains[g].active = false; + } + } + + // Launch a new grain when the scheduler counter elapses. + if (self->samples_until_next_grain == 0) { + granular_pitch_shift_launch_grain(self); + self->samples_until_next_grain = grain_spacing; + } else { + self->samples_until_next_grain--; + } + + // Advance the per-channel write cursor. + self->write_index++; + if (self->write_index >= self->capture_len) { + self->write_index = 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->base.bits_per_sample / 8)); + self->sample_buffer_length -= n; + } + } + + // 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; + + return GET_BUFFER_MORE_DATA; +} diff --git a/shared-module/audiodelays/GranularPitchShift.h b/shared-module/audiodelays/GranularPitchShift.h new file mode 100644 index 00000000000..26ee4804f36 --- /dev/null +++ b/shared-module/audiodelays/GranularPitchShift.h @@ -0,0 +1,104 @@ +// 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/__init__.h" +#include "shared-module/synthio/block.h" + +// Fixed-point fractional bits for grain read cursors and read rate. A grain's +// read_index and read_rate are stored as (words << GRANULAR_PITCH_READ_SHIFT), +// mirroring PITCH_READ_SHIFT from PitchShift.h. +#define GRANULAR_PITCH_READ_SHIFT (8) + +// Maximum number of concurrently active grains. `density` is clamped to this at +// construction so the grain pool is a fixed, deterministic allocation. +#define GRANULAR_MAX_GRAINS (8) + +extern const mp_obj_type_t audiodelays_granular_pitch_shift_type; + +// A single grain: a short, independently-scheduled, enveloped read of the +// capture buffer. Retired when `phase` reaches `length`. +typedef struct { + bool active; + uint32_t read_index; // words << GRANULAR_PITCH_READ_SHIFT into the capture buffer + uint32_t read_rate; // words << GRANULAR_PITCH_READ_SHIFT, the pitch-shift increment + uint32_t phase; // samples elapsed since the grain launched + uint32_t length; // grain length in samples (== grain_size) +} audiodelays_granular_grain_t; + +typedef struct { + audiosample_base_t base; + synthio_block_slot_t semitones; + mp_float_t current_semitones; + synthio_block_slot_t mix; + + // Double playback buffers (what we hand back to the audio component). + int8_t *buffer[2]; + uint8_t last_buf_idx; + uint32_t buffer_len; // max buffer in bytes + + // Current sample source bookkeeping. + uint8_t *sample_remaining_buffer; + uint32_t sample_buffer_length; + + bool loop; + bool more_data; + + // Capture buffer (the delay line grains read from). Always stored as 16-bit + // internally, planar per channel: channel c occupies + // capture_buffer[c * capture_len .. (c + 1) * capture_len). + int16_t *capture_buffer; + uint32_t capture_len; // words per channel + uint32_t write_index; // words, per-channel write cursor (0 .. capture_len) + + // Grain pool + scheduler. + audiodelays_granular_grain_t grains[GRANULAR_MAX_GRAINS]; + uint32_t samples_until_next_grain; + + uint32_t grain_size; // samples per grain + uint32_t density; // number of overlapping grains (<= GRANULAR_MAX_GRAINS) + + // Granular jitter: randomizes each grain's start position within the capture + // buffer. 0.0 is fully deterministic (grains always start grain_size words + // behind the write cursor); 1.0 spreads the start up to a further grain_size + // words backward, giving the classic granular "cloud" texture. Jitter is + // always backward (further behind the write cursor) so it never reads ahead + // of captured audio. + mp_float_t spread; + uint32_t rng_state; // xorshift32 state for grain-start jitter + + // Q15 (0..32768) normalization applied to the enveloped grain sum so the + // overlap-add gain of `density` Hann grains stays ~unity (Hann satisfies + // COLA at these hops with a summed gain of density/2, so the factor is + // 2/density, capped at 1.0 so a single grain is never amplified). + uint32_t grain_gain; + + // Precomputed amplitude envelope (raised-cosine / Hann), Q15 (0..32767), + // indexed directly by a grain's phase (envelope_len == grain_size). + int16_t *envelope_table; + uint32_t envelope_len; + + // Fixed-point read-rate increment computed from `semitones`, applied to each + // launched grain's read_rate. + uint32_t read_rate; // words << GRANULAR_PITCH_READ_SHIFT + + mp_obj_t sample; +} audiodelays_granular_pitch_shift_obj_t; + +void granular_pitch_shift_recalculate_rate(audiodelays_granular_pitch_shift_obj_t *self, mp_float_t semitones); + +void audiodelays_granular_pitch_shift_reset_buffer(audiodelays_granular_pitch_shift_obj_t *self, + bool single_channel_output, + uint8_t channel); + +audioio_get_buffer_result_t audiodelays_granular_pitch_shift_get_buffer(audiodelays_granular_pitch_shift_obj_t *self, + bool single_channel_output, + uint8_t channel, + uint8_t **buffer, + uint32_t *buffer_length); // length in bytes