Skip to content

Commit 1008dd5

Browse files
committed
Simplify audiofilters.DistortionMode.LOFI sample processing with bit mask.
1 parent 3a16daf commit 1008dd5

File tree

2 files changed

+5
-13
lines changed

2 files changed

+5
-13
lines changed

shared-bindings/audiofilters/Distortion.c

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -134,7 +134,7 @@ static mp_obj_t audiofilters_distortion_make_new(const mp_obj_type_t *type, size
134134
if (bits_per_sample != 8 && bits_per_sample != 16) {
135135
mp_raise_ValueError(MP_ERROR_TEXT("bits_per_sample must be 8 or 16"));
136136
}
137-
137+
138138
audiofilters_distortion_mode mode = DISTORTION_MODE_CLIP;
139139
if (args[ARG_mode].u_obj != MP_OBJ_NULL) {
140140
mode = validate_distortion_mode(args[ARG_mode].u_obj, MP_QSTR_mode);

shared-module/audiofilters/Distortion.c

Lines changed: 4 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -212,7 +212,7 @@ void common_hal_audiofilters_distortion_stop(audiofilters_distortion_obj_t *self
212212
}
213213

214214
static mp_float_t db_to_linear(mp_float_t value) {
215-
return expf(value * MICROPY_FLOAT_CONST(0.11512925464970228420089957273422));
215+
return expf(value * MICROPY_FLOAT_CONST(0.11512925464970228420089957273422));
216216
}
217217

218218
audioio_get_buffer_result_t audiofilters_distortion_get_buffer(audiofilters_distortion_obj_t *self, bool single_channel_output, uint8_t channel,
@@ -274,15 +274,7 @@ audioio_get_buffer_result_t audiofilters_distortion_get_buffer(audiofilters_dist
274274
}
275275
} else {
276276

277-
// Pre-calculate drive-based constants if needed by effect mode
278-
mp_float_t word_mult = 0;
279-
switch (self->mode) {
280-
case DISTORTION_MODE_LOFI:
281-
word_mult = powf(2.0, 2.0 + (1.0 - drive) * 14); // goes from 16 to 2 bits
282-
break;
283-
default:
284-
break;
285-
}
277+
uint32_t word_mask = 0xFFFFFFFF ^ ((1 << (uint32_t)roundf(drive * 14.0)) - 1); // LOFI mode bit mask
286278

287279
for (uint32_t i = 0; i < n; i++) {
288280
int32_t sample_word = 0;
@@ -305,7 +297,7 @@ audioio_get_buffer_result_t audiofilters_distortion_get_buffer(audiofilters_dist
305297
word = MIN(MAX(word, -32767), 32768); // Hard clip
306298
} break;
307299
case DISTORTION_MODE_LOFI: {
308-
word = floorf(word / 32768.0 * word_mult + 0.5) / word_mult * 32767.0;
300+
word = word & word_mask;
309301
} break;
310302
case DISTORTION_MODE_OVERDRIVE: {
311303
mp_float_t x = word / 32768.0 * 0.686306;
@@ -319,7 +311,7 @@ audioio_get_buffer_result_t audiofilters_distortion_get_buffer(audiofilters_dist
319311
} break;
320312
}
321313
word = word * post_gain;
322-
314+
323315
if (MP_LIKELY(self->bits_per_sample == 16)) {
324316
word_buffer[i] = (sample_word * (1.0 - mix)) + (word * mix);
325317
if (!self->samples_signed) {

0 commit comments

Comments
 (0)