synthio: add biquad filter type & basic filter calculations

the filter cannot be applied as yet.
This commit is contained in:
Jeff Epler 2023-05-29 09:50:18 -05:00
parent 0aaf5a4a98
commit fed8d5825b
No known key found for this signature in database
GPG Key ID: D5BF15AB975AB4DE
9 changed files with 341 additions and 0 deletions

View File

@ -45,6 +45,7 @@ SRC_BITMAP := \
shared-bindings/synthio/MidiTrack.c \
shared-bindings/synthio/LFO.c \
shared-bindings/synthio/Note.c \
shared-bindings/synthio/Biquad.c \
shared-bindings/synthio/Synthesizer.c \
shared-bindings/traceback/__init__.c \
shared-bindings/util.c \
@ -70,6 +71,7 @@ SRC_BITMAP := \
shared-module/synthio/MidiTrack.c \
shared-module/synthio/LFO.c \
shared-module/synthio/Note.c \
shared-module/synthio/Biquad.c \
shared-module/synthio/Synthesizer.c \
shared-module/traceback/__init__.c \
shared-module/zlib/__init__.c \

View File

@ -650,6 +650,7 @@ SRC_SHARED_MODULE_ALL = \
struct/__init__.c \
supervisor/__init__.c \
supervisor/StatusBar.c \
synthio/Biquad.c \
synthio/LFO.c \
synthio/Math.c \
synthio/MidiTrack.c \

View File

@ -0,0 +1,110 @@
/*
* This file is part of the MicroPython project, http://micropython.org/
*
* The MIT License (MIT)
*
* Copyright (c) 2021 Artyom Skrobov
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include <math.h>
#include <string.h>
#include "py/enum.h"
#include "py/mperrno.h"
#include "py/obj.h"
#include "py/objnamedtuple.h"
#include "py/runtime.h"
#include "shared-bindings/synthio/__init__.h"
#include "shared-bindings/synthio/LFO.h"
#include "shared-bindings/synthio/Math.h"
#include "shared-bindings/synthio/MidiTrack.h"
#include "shared-bindings/synthio/Note.h"
#include "shared-bindings/synthio/Synthesizer.h"
#include "shared-module/synthio/LFO.h"
#define default_attack_time (MICROPY_FLOAT_CONST(0.1))
#define default_decay_time (MICROPY_FLOAT_CONST(0.05))
#define default_release_time (MICROPY_FLOAT_CONST(0.2))
#define default_attack_level (MICROPY_FLOAT_CONST(1.))
#define default_sustain_level (MICROPY_FLOAT_CONST(0.8))
static const mp_arg_t biquad_properties[] = {
{ MP_QSTR_a1, MP_ARG_OBJ | MP_ARG_REQUIRED, {.u_obj = MP_ROM_NONE} },
{ MP_QSTR_a2, MP_ARG_OBJ | MP_ARG_REQUIRED, {.u_obj = MP_ROM_NONE} },
{ MP_QSTR_b0, MP_ARG_OBJ | MP_ARG_REQUIRED, {.u_obj = MP_ROM_NONE} },
{ MP_QSTR_b1, MP_ARG_OBJ | MP_ARG_REQUIRED, {.u_obj = MP_ROM_NONE} },
{ MP_QSTR_b2, MP_ARG_OBJ | MP_ARG_REQUIRED, {.u_obj = MP_ROM_NONE} },
};
//| class Biquad:
//| def __init__(self, b0: float, b1: float, b2: float, a1: float, a2: float) -> None:
//| """Construct a normalized biquad filter object.
//|
//| This implements the "direct form 1" biquad filter, where each coefficient
//| has been pre-divided by a0.
//|
//| Biquad objects are usually constructed via one of the related methods on a `Synthesizer` object
//| rather than directly from coefficients.
//|
//| https://github.com/WebAudio/Audio-EQ-Cookbook/blob/main/Audio-EQ-Cookbook.txt
//| """
//|
STATIC mp_obj_t synthio_biquad_make_new(const mp_obj_type_t *type_in, size_t n_args, size_t n_kw, const mp_obj_t *all_args) {
mp_arg_val_t args[MP_ARRAY_SIZE(biquad_properties)];
mp_arg_parse_all_kw_array(n_args, n_kw, all_args, MP_ARRAY_SIZE(biquad_properties), biquad_properties, args);
for (size_t i = 0; i < MP_ARRAY_SIZE(biquad_properties); i++) {
args[i].u_obj = mp_obj_new_float(mp_arg_validate_type_float(args[i].u_obj, biquad_properties[i].qst));
}
MP_STATIC_ASSERT(sizeof(mp_arg_val_t) == sizeof(mp_obj_t));
return namedtuple_make_new(type_in, MP_ARRAY_SIZE(args), 0, &args[0].u_obj);
}
const mp_obj_namedtuple_type_t synthio_biquad_type_obj = {
.base = {
.base = {
.type = &mp_type_type
},
.flags = MP_TYPE_FLAG_EXTENDED,
.name = MP_QSTR_Biquad,
.print = namedtuple_print,
.parent = &mp_type_tuple,
.make_new = synthio_biquad_make_new,
.attr = namedtuple_attr,
MP_TYPE_EXTENDED_FIELDS(
.unary_op = mp_obj_tuple_unary_op,
.binary_op = mp_obj_tuple_binary_op,
.subscr = mp_obj_tuple_subscr,
.getiter = mp_obj_tuple_getiter,
),
},
.n_fields = 5,
.fields = {
MP_QSTR_a1,
MP_QSTR_a2,
MP_QSTR_b0,
MP_QSTR_b1,
MP_QSTR_b2,
},
};

View File

@ -0,0 +1,9 @@
#pragma once
#include "py/obj.h"
#include "py/objnamedtuple.h"
extern const mp_obj_namedtuple_type_t synthio_biquad_type_obj;
mp_obj_t common_hal_synthio_new_lpf(mp_float_t w0, mp_float_t Q);
mp_obj_t common_hal_synthio_new_hpf(mp_float_t w0, mp_float_t Q);
mp_obj_t common_hal_synthio_new_bpf(mp_float_t w0, mp_float_t Q);

View File

@ -32,6 +32,7 @@
#include "py/objproperty.h"
#include "py/runtime.h"
#include "shared-bindings/util.h"
#include "shared-bindings/synthio/Biquad.h"
#include "shared-bindings/synthio/Synthesizer.h"
#include "shared-bindings/synthio/LFO.h"
#include "shared-bindings/synthio/__init__.h"
@ -292,6 +293,110 @@ MP_PROPERTY_GETTER(synthio_synthesizer_blocks_obj,
//| """Maximum polyphony of the synthesizer (read-only class property)"""
//|
//| def low_pass_filter(cls, cutoff_frequency, q_factor: float = 1 / math.sqrt(2)) -> Biquad:
//| """Construct a low-pass filter with the given parameters.
//|
//| `frequency`, called f0 in the cookbook, is the corner frequency in Hz
//| of the filter.
//|
//| `q_factor`, called `Q` in the cookbook. Controls how peaked the response will be at the cutoff frequency. A large value makes the response more peaked.
//| """
enum passfilter_arg_e { ARG_f0, ARG_Q };
// M_PI is not part of the math.h standard and may not be defined
// And by defining our own we can ensure it uses the correct const format.
#define MP_PI MICROPY_FLOAT_CONST(3.14159265358979323846)
static const mp_arg_t passfilter_properties[] = {
{ MP_QSTR_frequency, MP_ARG_OBJ | MP_ARG_REQUIRED, {.u_obj = MP_ROM_NONE} },
{ MP_QSTR_Q, MP_ARG_OBJ, {.u_obj = MP_OBJ_NULL } },
};
STATIC mp_obj_t synthio_synthesizer_lpf(size_t n_pos, const mp_obj_t *pos_args, mp_map_t *kw_args) {
mp_arg_val_t args[MP_ARRAY_SIZE(passfilter_properties)];
mp_obj_t self_in = pos_args[0];
synthio_synthesizer_obj_t *self = MP_OBJ_TO_PTR(self_in);
mp_arg_parse_all(n_pos - 1, pos_args + 1, kw_args, MP_ARRAY_SIZE(passfilter_properties), passfilter_properties, args);
mp_float_t f0 = mp_arg_validate_type_float(args[ARG_f0].u_obj, MP_QSTR_f0);
mp_float_t Q =
args[ARG_Q].u_obj == MP_OBJ_NULL ? MICROPY_FLOAT_CONST(0.7071067811865475) :
mp_arg_validate_type_float(args[ARG_Q].u_obj, MP_QSTR_Q);
mp_float_t w0 = f0 / self->synth.sample_rate * 2 * MP_PI;
return common_hal_synthio_new_lpf(w0, Q);
}
MP_DEFINE_CONST_FUN_OBJ_KW(synthio_synthesizer_lpf_fun_obj, 1, synthio_synthesizer_lpf);
//| def high_pass_filter(cls, cutoff_frequency, q_factor: float = 1 / math.sqrt(2)) -> Biquad:
//| """Construct a high-pass filter with the given parameters.
//|
//| `frequency`, called f0 in the cookbook, is the corner frequency in Hz
//| of the filter.
//|
//| `q_factor`, called `Q` in the cookbook. Controls how peaked the response will be at the cutoff frequency. A large value makes the response more peaked.
//| """
STATIC mp_obj_t synthio_synthesizer_hpf(size_t n_pos, const mp_obj_t *pos_args, mp_map_t *kw_args) {
mp_arg_val_t args[MP_ARRAY_SIZE(passfilter_properties)];
mp_obj_t self_in = pos_args[0];
synthio_synthesizer_obj_t *self = MP_OBJ_TO_PTR(self_in);
mp_arg_parse_all(n_pos - 1, pos_args + 1, kw_args, MP_ARRAY_SIZE(passfilter_properties), passfilter_properties, args);
mp_float_t f0 = mp_arg_validate_type_float(args[ARG_f0].u_obj, MP_QSTR_f0);
mp_float_t Q =
args[ARG_Q].u_obj == MP_OBJ_NULL ? MICROPY_FLOAT_CONST(0.7071067811865475) :
mp_arg_validate_type_float(args[ARG_Q].u_obj, MP_QSTR_Q);
mp_float_t w0 = f0 / self->synth.sample_rate * 2 * MP_PI;
return common_hal_synthio_new_hpf(w0, Q);
}
//| def band_pass_filter(cls, frequency, q_factor: float = 1 / math.sqrt(2)) -> Biquad:
//| """Construct a band-pass filter with the given parameters.
//|
//| `frequency`, called f0 in the cookbook, is the center frequency in Hz
//| of the filter.
//|
//| `q_factor`, called `Q` in the cookbook. Controls how peaked the response will be at the cutoff frequency. A large value makes the response more peaked.
//|
//| The coefficients are scaled such that the filter has a 0dB peak gain.
//| """
//|
MP_DEFINE_CONST_FUN_OBJ_KW(synthio_synthesizer_hpf_fun_obj, 1, synthio_synthesizer_hpf);
STATIC mp_obj_t synthio_synthesizer_bpf(size_t n_pos, const mp_obj_t *pos_args, mp_map_t *kw_args) {
mp_arg_val_t args[MP_ARRAY_SIZE(passfilter_properties)];
mp_obj_t self_in = pos_args[0];
synthio_synthesizer_obj_t *self = MP_OBJ_TO_PTR(self_in);
mp_arg_parse_all(n_pos - 1, pos_args + 1, kw_args, MP_ARRAY_SIZE(passfilter_properties), passfilter_properties, args);
mp_float_t f0 = mp_arg_validate_type_float(args[ARG_f0].u_obj, MP_QSTR_f0);
mp_float_t Q =
args[ARG_Q].u_obj == MP_OBJ_NULL ? MICROPY_FLOAT_CONST(0.7071067811865475) :
mp_arg_validate_type_float(args[ARG_Q].u_obj, MP_QSTR_Q);
mp_float_t w0 = f0 / self->synth.sample_rate * 2 * MP_PI;
return common_hal_synthio_new_bpf(w0, Q);
}
MP_DEFINE_CONST_FUN_OBJ_KW(synthio_synthesizer_bpf_fun_obj, 1, synthio_synthesizer_bpf);
STATIC const mp_rom_map_elem_t synthio_synthesizer_locals_dict_table[] = {
// Methods
{ MP_ROM_QSTR(MP_QSTR_press), MP_ROM_PTR(&synthio_synthesizer_press_obj) },
@ -304,6 +409,9 @@ STATIC const mp_rom_map_elem_t synthio_synthesizer_locals_dict_table[] = {
{ MP_ROM_QSTR(MP_QSTR___enter__), MP_ROM_PTR(&default___enter___obj) },
{ MP_ROM_QSTR(MP_QSTR___exit__), MP_ROM_PTR(&synthio_synthesizer___exit___obj) },
{ MP_ROM_QSTR(MP_QSTR_low_pass_filter), MP_ROM_PTR(&synthio_synthesizer_lpf_fun_obj) },
{ MP_ROM_QSTR(MP_QSTR_high_pass_filter), MP_ROM_PTR(&synthio_synthesizer_hpf_fun_obj) },
{ MP_ROM_QSTR(MP_QSTR_band_pass_filter), MP_ROM_PTR(&synthio_synthesizer_bpf_fun_obj) },
// Properties
{ MP_ROM_QSTR(MP_QSTR_envelope), MP_ROM_PTR(&synthio_synthesizer_envelope_obj) },
{ MP_ROM_QSTR(MP_QSTR_sample_rate), MP_ROM_PTR(&synthio_synthesizer_sample_rate_obj) },

View File

@ -36,6 +36,7 @@
#include "extmod/vfs_posix.h"
#include "shared-bindings/synthio/__init__.h"
#include "shared-bindings/synthio/Biquad.h"
#include "shared-bindings/synthio/LFO.h"
#include "shared-bindings/synthio/Math.h"
#include "shared-bindings/synthio/MidiTrack.h"
@ -310,6 +311,7 @@ MP_DEFINE_CONST_FUN_OBJ_VAR(synthio_lfo_tick_obj, 1, synthio_lfo_tick);
STATIC const mp_rom_map_elem_t synthio_module_globals_table[] = {
{ MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_synthio) },
{ MP_ROM_QSTR(MP_QSTR_Biquad), MP_ROM_PTR(&synthio_biquad_type_obj) },
{ MP_ROM_QSTR(MP_QSTR_Math), MP_ROM_PTR(&synthio_math_type) },
{ MP_ROM_QSTR(MP_QSTR_MathOperation), MP_ROM_PTR(&synthio_math_operation_type) },
{ MP_ROM_QSTR(MP_QSTR_MidiTrack), MP_ROM_PTR(&synthio_miditrack_type) },

View File

@ -0,0 +1,94 @@
/*
* This file is part of the Micro Python project, http://micropython.org/
*
* The MIT License (MIT)
*
* Copyright (c) 2023 Jeff Epler for Adafruit Industries
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include <math.h>
#include "shared-bindings/synthio/Biquad.h"
mp_obj_t common_hal_synthio_new_lpf(mp_float_t w0, mp_float_t Q) {
mp_float_t s = MICROPY_FLOAT_C_FUN(sin)(w0);
mp_float_t c = MICROPY_FLOAT_C_FUN(cos)(w0);
mp_float_t alpha = s / (2 * Q);
mp_float_t a0 = 1 + alpha;
mp_float_t a1 = -2 * c;
mp_float_t a2 = 1 - alpha;
mp_float_t b0 = (1 - c) / 2;
mp_float_t b1 = 1 - c;
mp_float_t b2 = (1 - c) / 2;
mp_obj_t out_args[] = {
mp_obj_new_float(a1 / a0),
mp_obj_new_float(a2 / a0),
mp_obj_new_float(b0 / a0),
mp_obj_new_float(b1 / a0),
mp_obj_new_float(b2 / a0),
};
return namedtuple_make_new((const mp_obj_type_t *)&synthio_biquad_type_obj, MP_ARRAY_SIZE(out_args), 0, out_args);
}
mp_obj_t common_hal_synthio_new_hpf(mp_float_t w0, mp_float_t Q) {
mp_float_t s = MICROPY_FLOAT_C_FUN(sin)(w0);
mp_float_t c = MICROPY_FLOAT_C_FUN(cos)(w0);
mp_float_t alpha = s / (2 * Q);
mp_float_t a0 = 1 + alpha;
mp_float_t a1 = -2 * c;
mp_float_t a2 = 1 - alpha;
mp_float_t b0 = (1 + c) / 2;
mp_float_t b1 = -(1 + c);
mp_float_t b2 = (1 + c) / 2;
mp_obj_t out_args[] = {
mp_obj_new_float(a1 / a0),
mp_obj_new_float(a2 / a0),
mp_obj_new_float(b0 / a0),
mp_obj_new_float(b1 / a0),
mp_obj_new_float(b2 / a0),
};
return namedtuple_make_new((const mp_obj_type_t *)&synthio_biquad_type_obj, MP_ARRAY_SIZE(out_args), 0, out_args);
}
mp_obj_t common_hal_synthio_new_bpf(mp_float_t w0, mp_float_t Q) {
mp_float_t s = MICROPY_FLOAT_C_FUN(sin)(w0);
mp_float_t c = MICROPY_FLOAT_C_FUN(cos)(w0);
mp_float_t alpha = s / (2 * Q);
mp_float_t a0 = 1 + alpha;
mp_float_t a1 = -2 * c;
mp_float_t a2 = 1 - alpha;
mp_float_t b0 = alpha;
mp_float_t b1 = 0;
mp_float_t b2 = -alpha;
mp_obj_t out_args[] = {
mp_obj_new_float(a1 / a0),
mp_obj_new_float(a2 / a0),
mp_obj_new_float(b0 / a0),
mp_obj_new_float(b1 / a0),
mp_obj_new_float(b2 / a0),
};
return namedtuple_make_new((const mp_obj_type_t *)&synthio_biquad_type_obj, MP_ARRAY_SIZE(out_args), 0, out_args);
}

View File

@ -0,0 +1,12 @@
from synthio import Synthesizer
s = Synthesizer(sample_rate=48000)
def print_filter(x):
print(" ".join(f"{v:.4g}" for v in x))
print_filter(s.low_pass_filter(330))
print_filter(s.high_pass_filter(330))
print_filter(s.band_pass_filter(330))

View File

@ -0,0 +1,3 @@
-1.939 0.9407 0.0004526 0.0009052 0.0004526
-1.939 0.9407 0.9699 -1.94 0.9699
-1.939 0.9407 0.02963 0 -0.02963