Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions ports/unix/variants/coverage/mpconfigvariant.mk
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ SRC_BITMAP := \
shared-bindings/audiofilters/Filter.c \
shared-bindings/audiofilters/Phaser.c \
shared-bindings/audiofilters/__init__.c \
shared-bindings/audiotap/LevelReader.c \
shared-bindings/audiotap/Tap.c \
shared-bindings/audiotap/__init__.c \
shared-bindings/audiofreeverb/Freeverb.c \
Expand Down Expand Up @@ -95,6 +96,7 @@ SRC_BITMAP := \
shared-module/audiofilters/Filter.c \
shared-module/audiofilters/Phaser.c \
shared-module/audiofilters/__init__.c \
shared-module/audiotap/LevelReader.c \
shared-module/audiotap/Tap.c \
shared-module/audiotap/__init__.c \
shared-module/audiofreeverb/Freeverb.c \
Expand Down
1 change: 1 addition & 0 deletions py/circuitpy_defns.mk
Original file line number Diff line number Diff line change
Expand Up @@ -792,6 +792,7 @@ SRC_SHARED_MODULE_ALL = \
audiospeed/Resampler.c \
audiospeed/SpeedChanger.c \
audiospeed/__init__.c \
audiotap/LevelReader.c \
audiotap/Tap.c \
audiotap/__init__.c \
audiodelays/Echo.c \
Expand Down
5 changes: 3 additions & 2 deletions shared-bindings/audiofilewriter/AudioFileWriter.c
Original file line number Diff line number Diff line change
Expand Up @@ -120,14 +120,15 @@
//| samples_signed=mic_format.samples_signed,
//| max_packet_size=mic_format.max_packet_size,
//| )
//| # The tap only measures the levels, so it keeps no audio.
//| # The tap is only there to measure the levels, so it keeps no audio.
//| tap = audiotap.Tap(capacity=0)
//| levels = audiotap.LevelReader(tap)
//| # No file: fetch buffers through the tap at the microphone's rate and drop them.
//| sink = AudioFileWriter(None)
//| sink.play(tap.play(mic))
//|
//| while True:
//| print(f"peak {tap.peak:.3f} rms {tap.rms:.3f}")
//| print(f"peak {levels.peak:.3f} rms {levels.rms:.3f}")
//| time.sleep(0.5)
//| """
//| ...
Expand Down
133 changes: 133 additions & 0 deletions shared-bindings/audiotap/LevelReader.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
// 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 <stdint.h>

#include "shared-bindings/audiotap/LevelReader.h"
#include "shared-bindings/audiotap/Tap.h"

#include "shared/runtime/context_manager_helpers.h"
#include "py/objproperty.h"
#include "py/runtime.h"
#include "shared-bindings/util.h"

//| class LevelReader:
//| """Measures the peak and RMS levels of the audio that passes through a `Tap`"""
//|
//| def __init__(self, tap: Tap) -> None:
//| """Create a LevelReader that measures the audio passing through ``tap``.
//|
//| The levels are measured on all of the audio that passes through the
//| tap, whether or not it is read with `Tap.readinto`, so a tap made
//| with a ``capacity`` of 0 can be used for levels alone.
//|
//| A tap can have one LevelReader at a time. `deinit` it to detach it
//| from the tap.
//|
//| :param Tap tap: The tap whose audio is measured.
//|
//| """
//| ...
//|
static mp_obj_t audiotap_levelreader_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *all_args) {
enum { ARG_tap, };
static const mp_arg_t allowed_args[] = {
{ MP_QSTR_tap, MP_ARG_OBJ | MP_ARG_REQUIRED, {} },
};

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);

audiotap_tap_obj_t *tap = MP_OBJ_TO_PTR(mp_arg_validate_type(args[ARG_tap].u_obj, &audiotap_tap_type, MP_QSTR_tap));

audiotap_levelreader_obj_t *self = mp_obj_malloc(audiotap_levelreader_obj_t, &audiotap_levelreader_type);
common_hal_audiotap_levelreader_construct(self, tap);

return MP_OBJ_FROM_PTR(self);
}

//| def deinit(self) -> None:
//| """Detaches the LevelReader from its tap, which stops measuring levels."""
//| ...
//|
static mp_obj_t audiotap_levelreader_deinit(mp_obj_t self_in) {
audiotap_levelreader_obj_t *self = MP_OBJ_TO_PTR(self_in);
common_hal_audiotap_levelreader_deinit(self);
return mp_const_none;
}
static MP_DEFINE_CONST_FUN_OBJ_1(audiotap_levelreader_deinit_obj, audiotap_levelreader_deinit);

static void check_for_deinit(audiotap_levelreader_obj_t *self) {
if (common_hal_audiotap_levelreader_deinited(self)) {
raise_deinited_error();
}
}

//| def __enter__(self) -> LevelReader:
//| """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."""
//| ...
//|
// Provided by context manager helper.

//| peak: float
//| """The largest magnitude of the audio that passed through the tap since
//| this was last read, from 0.0 to 1.0 of full scale. Reading this starts a
//| new measurement. 0.0 when no audio passed through. The channels of
//| stereo audio are measured together. (read-only)"""
//|
static mp_obj_t audiotap_levelreader_obj_get_peak(mp_obj_t self_in) {
audiotap_levelreader_obj_t *self = MP_OBJ_TO_PTR(self_in);
check_for_deinit(self);
return mp_obj_new_float(common_hal_audiotap_levelreader_get_peak(self));
}
MP_DEFINE_CONST_FUN_OBJ_1(audiotap_levelreader_get_peak_obj, audiotap_levelreader_obj_get_peak);

MP_PROPERTY_GETTER(audiotap_levelreader_peak_obj,
(mp_obj_t)&audiotap_levelreader_get_peak_obj);

//| rms: float
//| """The RMS level of the audio that passed through the tap since this was
//| last read, from 0.0 to 1.0 of full scale. Reading this starts a new
//| measurement, separate from `peak`'s. 0.0 when no audio passed through.
//| The channels of stereo audio are measured together. (read-only)"""
//|
//|
static mp_obj_t audiotap_levelreader_obj_get_rms(mp_obj_t self_in) {
audiotap_levelreader_obj_t *self = MP_OBJ_TO_PTR(self_in);
check_for_deinit(self);
return mp_obj_new_float(common_hal_audiotap_levelreader_get_rms(self));
}
MP_DEFINE_CONST_FUN_OBJ_1(audiotap_levelreader_get_rms_obj, audiotap_levelreader_obj_get_rms);

MP_PROPERTY_GETTER(audiotap_levelreader_rms_obj,
(mp_obj_t)&audiotap_levelreader_get_rms_obj);

static const mp_rom_map_elem_t audiotap_levelreader_locals_dict_table[] = {
// Methods
{ MP_ROM_QSTR(MP_QSTR_deinit), MP_ROM_PTR(&audiotap_levelreader_deinit_obj) },
{ MP_ROM_QSTR(MP_QSTR___enter__), MP_ROM_PTR(&default___enter___obj) },
{ MP_ROM_QSTR(MP_QSTR___exit__), MP_ROM_PTR(&default___exit___obj) },

// Properties
{ MP_ROM_QSTR(MP_QSTR_peak), MP_ROM_PTR(&audiotap_levelreader_peak_obj) },
{ MP_ROM_QSTR(MP_QSTR_rms), MP_ROM_PTR(&audiotap_levelreader_rms_obj) },
};
static MP_DEFINE_CONST_DICT(audiotap_levelreader_locals_dict, audiotap_levelreader_locals_dict_table);

MP_DEFINE_CONST_OBJ_TYPE(
audiotap_levelreader_type,
MP_QSTR_LevelReader,
MP_TYPE_FLAG_HAS_SPECIAL_ACCESSORS,
make_new, audiotap_levelreader_make_new,
locals_dict, &audiotap_levelreader_locals_dict
);
18 changes: 18 additions & 0 deletions shared-bindings/audiotap/LevelReader.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
// 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/audiotap/LevelReader.h"

extern const mp_obj_type_t audiotap_levelreader_type;

void common_hal_audiotap_levelreader_construct(audiotap_levelreader_obj_t *self, audiotap_tap_obj_t *tap);
void common_hal_audiotap_levelreader_deinit(audiotap_levelreader_obj_t *self);
bool common_hal_audiotap_levelreader_deinited(audiotap_levelreader_obj_t *self);

mp_float_t common_hal_audiotap_levelreader_get_peak(audiotap_levelreader_obj_t *self);
mp_float_t common_hal_audiotap_levelreader_get_rms(audiotap_levelreader_obj_t *self);
51 changes: 9 additions & 42 deletions shared-bindings/audiotap/Tap.c
Original file line number Diff line number Diff line change
Expand Up @@ -24,10 +24,10 @@
//| plays the tap gets the sample's audio unchanged.
//|
//| As the audio passes through, the tap keeps up to ``capacity`` seconds
//| of it in a buffer, which `readinto` copies out of without waiting, and
//| measures its `peak` and `rms` levels. The program can look at
//| the audio this way, at the point in the chain where the tap is,
//| while it plays.
//| of it in a buffer, which `readinto` copies out of without waiting.
//| The program can look at the audio this way, at the point in the
//| chain where the tap is, while it plays. To measure its peak and RMS
//| levels as well, attach a `LevelReader` to the tap.
//|
//| The tap takes its sample rate, channel count, bits per sample and
//| signedness from the first sample it plays, and allocates the buffer
Expand All @@ -45,8 +45,8 @@
//| never affected.
//|
//| :param float capacity: How many seconds of audio are kept for
//| `readinto`. 0 keeps none, for a tap that only measures `peak` and
//| `rms`.
//| `readinto`. 0 keeps none, for a tap that is only measured by a
//| `LevelReader`.
//|
//| Showing the level of a USB microphone while it is heard through the
//| DVI output, and keeping the audio for a spectrum display. The
Expand Down Expand Up @@ -94,6 +94,7 @@
//| )
//| # Keep a quarter second, more than arrives between reads of the loop below.
//| tap = audiotap.Tap(capacity=0.25)
//| levels = audiotap.LevelReader(tap)
//| mixer = audiomixer.Mixer(voice_count=1, sample_rate=48000, channel_count=mic.channel_count)
//| supervisor.runtime.audio.play(mixer)
//| mixer.voice[0].play(audiospeed.Resampler(tap.play(mic)))
Expand All @@ -116,8 +117,8 @@
//| # Read the audio that is waiting. A spectrum display would use these samples.
//| while tap.available >= len(samples):
//| tap.readinto(samples)
//| peak = tap.peak
//| rms = tap.rms
//| peak = levels.peak
//| rms = levels.rms
//| peak_bar.width = max(1, int(peak * display.width))
//| rms_bar.width = max(1, int(rms * display.width))
//| print(f"peak {peak:.3f} rms {rms:.3f}")
Expand Down Expand Up @@ -249,38 +250,6 @@ static mp_obj_t audiotap_tap_obj_clear(mp_obj_t self_in) {
}
MP_DEFINE_CONST_FUN_OBJ_1(audiotap_tap_clear_obj, audiotap_tap_obj_clear);

//| peak: float
//| """The largest magnitude of the audio that passed through since this was
//| last read, from 0.0 to 1.0 of full scale. Reading this starts a new
//| measurement. 0.0 when no audio passed through. The channels of stereo
//| audio are measured together. (read-only)"""
//|
static mp_obj_t audiotap_tap_obj_get_peak(mp_obj_t self_in) {
audiotap_tap_obj_t *self = MP_OBJ_TO_PTR(self_in);
check_for_deinit(self);
return mp_obj_new_float(common_hal_audiotap_tap_get_peak(self));
}
MP_DEFINE_CONST_FUN_OBJ_1(audiotap_tap_get_peak_obj, audiotap_tap_obj_get_peak);

MP_PROPERTY_GETTER(audiotap_tap_peak_obj,
(mp_obj_t)&audiotap_tap_get_peak_obj);

//| rms: float
//| """The RMS level of the audio that passed through since this was last
//| read, from 0.0 to 1.0 of full scale. Reading this starts a new
//| measurement, separate from `peak`'s. 0.0 when no audio passed through.
//| The channels of stereo audio are measured together. (read-only)"""
//|
static mp_obj_t audiotap_tap_obj_get_rms(mp_obj_t self_in) {
audiotap_tap_obj_t *self = MP_OBJ_TO_PTR(self_in);
check_for_deinit(self);
return mp_obj_new_float(common_hal_audiotap_tap_get_rms(self));
}
MP_DEFINE_CONST_FUN_OBJ_1(audiotap_tap_get_rms_obj, audiotap_tap_obj_get_rms);

MP_PROPERTY_GETTER(audiotap_tap_rms_obj,
(mp_obj_t)&audiotap_tap_get_rms_obj);

//| def play(self, sample: circuitpython_typing.AudioSample, *, loop: bool = False) -> Tap:
//| """Plays the sample once when loop=False and continuously when loop=True.
//| Does not block. Use `playing` to block.
Expand Down Expand Up @@ -337,8 +306,6 @@ static const mp_rom_map_elem_t audiotap_tap_locals_dict_table[] = {
{ MP_ROM_QSTR(MP_QSTR_playing), MP_ROM_PTR(&audiotap_tap_playing_obj) },
{ MP_ROM_QSTR(MP_QSTR_available), MP_ROM_PTR(&audiotap_tap_available_obj) },
{ MP_ROM_QSTR(MP_QSTR_overflow), MP_ROM_PTR(&audiotap_tap_overflow_obj) },
{ MP_ROM_QSTR(MP_QSTR_peak), MP_ROM_PTR(&audiotap_tap_peak_obj) },
{ MP_ROM_QSTR(MP_QSTR_rms), MP_ROM_PTR(&audiotap_tap_rms_obj) },
AUDIOSAMPLE_FIELDS,
};
static MP_DEFINE_CONST_DICT(audiotap_tap_locals_dict, audiotap_tap_locals_dict_table);
Expand Down
2 changes: 0 additions & 2 deletions shared-bindings/audiotap/Tap.h
Original file line number Diff line number Diff line change
Expand Up @@ -23,5 +23,3 @@ uint32_t common_hal_audiotap_tap_get_available(audiotap_tap_obj_t *self);
uint32_t common_hal_audiotap_tap_readinto(audiotap_tap_obj_t *self, uint8_t *buffer, uint32_t length);
void common_hal_audiotap_tap_clear(audiotap_tap_obj_t *self);
bool common_hal_audiotap_tap_get_overflow(audiotap_tap_obj_t *self);
mp_float_t common_hal_audiotap_tap_get_peak(audiotap_tap_obj_t *self);
mp_float_t common_hal_audiotap_tap_get_rms(audiotap_tap_obj_t *self);
7 changes: 5 additions & 2 deletions shared-bindings/audiotap/__init__.c
Original file line number Diff line number Diff line change
Expand Up @@ -9,17 +9,20 @@
#include "py/obj.h"
#include "py/runtime.h"

#include "shared-bindings/audiotap/LevelReader.h"
#include "shared-bindings/audiotap/Tap.h"

//| """Look at audio as it plays
//|
//| The `audiotap` module contains `Tap`, which goes into an audio chain like
//| the effects in `audiofilters` and `audiodelays`. Audio passes through it
//| unchanged, and the program can read a copy of it and its levels, for meters,
//| waveforms, spectrum analysis or recording, while it plays."""
//| unchanged, and the program can read a copy of it, for waveforms, spectrum
//| analysis or recording, while it plays. A `LevelReader` attached to a tap
//| measures the peak and RMS levels of its audio, for meters."""

static const mp_rom_map_elem_t audiotap_module_globals_table[] = {
{ MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_audiotap) },
{ MP_ROM_QSTR(MP_QSTR_LevelReader), MP_ROM_PTR(&audiotap_levelreader_type) },
{ MP_ROM_QSTR(MP_QSTR_Tap), MP_ROM_PTR(&audiotap_tap_type) },
};

Expand Down
Loading
Loading