From b72352949ba50d4cece043f65e037de7e3ae3a1a Mon Sep 17 00:00:00 2001 From: Jeff Epler Date: Mon, 29 Jul 2019 18:39:00 -0400 Subject: PWM audio: Rename AudioOut -> PWMAudioOut, _audioio_ -> _audiopwmio_ --- ports/nrf/background.c | 2 +- ports/nrf/common-hal/audiopwmio/AudioOut.c | 318 -------------------------- ports/nrf/common-hal/audiopwmio/AudioOut.h | 59 ----- ports/nrf/common-hal/audiopwmio/PWMAudioOut.c | 318 ++++++++++++++++++++++++++ ports/nrf/common-hal/audiopwmio/PWMAudioOut.h | 59 +++++ ports/nrf/supervisor/port.c | 2 +- py/circuitpy_defns.mk | 2 +- shared-bindings/audiopwmio/AudioOut.c | 294 ------------------------ shared-bindings/audiopwmio/AudioOut.h | 49 ---- shared-bindings/audiopwmio/PWMAudioOut.c | 294 ++++++++++++++++++++++++ shared-bindings/audiopwmio/PWMAudioOut.h | 49 ++++ shared-bindings/audiopwmio/__init__.c | 4 +- 12 files changed, 725 insertions(+), 725 deletions(-) delete mode 100644 ports/nrf/common-hal/audiopwmio/AudioOut.c delete mode 100644 ports/nrf/common-hal/audiopwmio/AudioOut.h create mode 100644 ports/nrf/common-hal/audiopwmio/PWMAudioOut.c create mode 100644 ports/nrf/common-hal/audiopwmio/PWMAudioOut.h delete mode 100644 shared-bindings/audiopwmio/AudioOut.c delete mode 100644 shared-bindings/audiopwmio/AudioOut.h create mode 100644 shared-bindings/audiopwmio/PWMAudioOut.c create mode 100644 shared-bindings/audiopwmio/PWMAudioOut.h diff --git a/ports/nrf/background.c b/ports/nrf/background.c index 91ec66b36..453bc96df 100644 --- a/ports/nrf/background.c +++ b/ports/nrf/background.c @@ -34,7 +34,7 @@ #endif #if CIRCUITPY_AUDIOPWMIO -#include "common-hal/audiopwmio/AudioOut.h" +#include "common-hal/audiopwmio/PWMAudioOut.h" #endif static bool running_background_tasks = false; diff --git a/ports/nrf/common-hal/audiopwmio/AudioOut.c b/ports/nrf/common-hal/audiopwmio/AudioOut.c deleted file mode 100644 index a3c56c76b..000000000 --- a/ports/nrf/common-hal/audiopwmio/AudioOut.c +++ /dev/null @@ -1,318 +0,0 @@ -/* - * This file is part of the MicroPython project, http://micropython.org/ - * - * The MIT License (MIT) - * - * Copyright (c) 2019 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 -#include - -#include "extmod/vfs_fat.h" -#include "py/gc.h" -#include "py/mperrno.h" -#include "py/runtime.h" -#include "common-hal/audiopwmio/AudioOut.h" -#include "common-hal/pulseio/PWMOut.h" -#include "shared-bindings/audiopwmio/AudioOut.h" -#include "shared-bindings/microcontroller/__init__.h" -#include "shared-bindings/microcontroller/Pin.h" -#include "supervisor/shared/translate.h" - -// TODO: This should be the same size as PWMOut.c:pwms[], but there's no trivial way to accomplish that -STATIC audiopwmio_audioout_obj_t* active_audio[4]; - -#define F_TARGET (62500) -#define F_PWM (16000000) -// return the REFRESH value, store the TOP value in an out-parameter -// Tested for key values (worst relative error = 0.224% = 3.84 cents) -// 8000: top = 250 refresh = 7 [ 8000.0] -// 22050: top = 242 refresh = 2 [22038.5] -// 24000: top = 222 refresh = 2 [24024.0] -// 44100: top = 181 refresh = 1 [44198.8] -// 48000: top = 167 refresh = 1 [47904.1] -STATIC uint32_t calculate_pwm_parameters(uint32_t sample_rate, uint32_t *top_out) { - // the desired frequency is the closest integer multiple of sample_rate not less than F_TARGET - uint32_t desired_frequency = (F_TARGET + sample_rate - 1) / sample_rate * sample_rate; - // The top value is the PWM frequency divided by the desired frequency (round to nearest) - uint32_t top = (F_PWM + desired_frequency/2) / desired_frequency; - // The actual frequency is the PWM frequency divided by the top value (round to nearest) - uint32_t actual_frequency = (F_PWM + top/2) / top; - // The multiplier is the actual frequency divided by the sample rate (round to nearest) - uint32_t multiplier = (actual_frequency + sample_rate/2) / sample_rate; - *top_out = top; - return multiplier - 1; -} - -STATIC void activate_audiopwmout_obj(audiopwmio_audioout_obj_t *self) { - for(size_t i=0; i < MP_ARRAY_SIZE(active_audio); i++) { - if(!active_audio[i]) { - active_audio[i] = self; - break; - } - } -} -STATIC void deactivate_audiopwmout_obj(audiopwmio_audioout_obj_t *self) { - for(size_t i=0; i < MP_ARRAY_SIZE(active_audio); i++) { - if(active_audio[i] == self) - active_audio[i] = NULL; - } -} - -void audiopwmout_reset() { - for(size_t i=0; i < MP_ARRAY_SIZE(active_audio); i++) - active_audio[i] = NULL; -} - -STATIC void fill_buffers(audiopwmio_audioout_obj_t *self, int buf) { - self->pwm->EVENTS_SEQSTARTED[1-buf] = 0; - uint16_t *dev_buffer = self->buffers[buf]; - uint8_t *buffer; - uint32_t buffer_length; - audioio_get_buffer_result_t get_buffer_result = - audiosample_get_buffer(self->sample, false, 0, - &buffer, &buffer_length); - if (get_buffer_result == GET_BUFFER_ERROR) { - common_hal_audiopwmio_audioout_stop(self); - return; - } - uint32_t num_samples = buffer_length / self->bytes_per_sample / self->spacing; - - if(self->bytes_per_sample == 1) { - uint8_t offset = self->signed_to_unsigned ? 0x80 : 0; - uint16_t scale = self->scale; - for(uint32_t i=0; ispacing; i++) { - uint8_t rawval = (*buffer++ + offset); - uint16_t val = (uint16_t)(((uint32_t)rawval * (uint32_t)scale) >> 8); - *dev_buffer++ = val; - if(self->spacing == 1) - *dev_buffer++ = val; - } - } else { - uint16_t offset = self->signed_to_unsigned ? 0x8000 : 0; - uint16_t scale = self->scale; - uint16_t *buffer16 = (uint16_t*)buffer; - for(uint32_t i=0; ispacing; i++) { - uint16_t rawval = (*buffer16++ + offset); - uint16_t val = (uint16_t)((rawval * (uint32_t)scale) >> 16); - *dev_buffer++ = val; - if(self->spacing == 1) - *dev_buffer++ = val; - } - } - self->pwm->SEQ[buf].PTR = (intptr_t)self->buffers[buf]; - self->pwm->SEQ[buf].CNT = num_samples*2; - - if (self->loop && get_buffer_result == GET_BUFFER_DONE) { - audiosample_reset_buffer(self->sample, false, 0); - } else if(get_buffer_result == GET_BUFFER_DONE) { - self->pwm->LOOP = 0; - self->stopping = true; - } else { - self->pwm->LOOP = 0xffff; - } -} - -STATIC void audiopwmout_background_obj(audiopwmio_audioout_obj_t *self) { - if(!common_hal_audiopwmio_audioout_get_playing(self)) - return; - if(self->loop && self->single_buffer) { - self->pwm->LOOP = 0xffff; - } else if(self->stopping) { - bool stopped = - (self->pwm->EVENTS_SEQEND[0] || !self->pwm->EVENTS_SEQSTARTED[0]) && - (self->pwm->EVENTS_SEQEND[1] || !self->pwm->EVENTS_SEQSTARTED[1]); - if(stopped) - self->pwm->TASKS_STOP = 1; - } else if(!self->single_buffer) { - if(self->pwm->EVENTS_SEQSTARTED[0]) fill_buffers(self, 1); - if(self->pwm->EVENTS_SEQSTARTED[1]) fill_buffers(self, 0); - } -} - -void audiopwmout_background() { - for(size_t i=0; i < MP_ARRAY_SIZE(active_audio); i++) { - if(!active_audio[i]) continue; - audiopwmout_background_obj(active_audio[i]); - } -} - -void common_hal_audiopwmio_audioout_construct(audiopwmio_audioout_obj_t* self, - const mcu_pin_obj_t* left_channel, const mcu_pin_obj_t* right_channel, uint16_t quiescent_value) { - assert_pin_free(left_channel); - assert_pin_free(right_channel); - self->pwm = pwmout_allocate(256, PWM_PRESCALER_PRESCALER_DIV_1, true, NULL, NULL); - if(!self->pwm) { - mp_raise_RuntimeError(translate("All timers in use")); - } - - self->pwm->PRESCALER = PWM_PRESCALER_PRESCALER_DIV_1; - // two uint16_t values per sample when Grouped - // n.b. SEQ[#].CNT "counts" are 2 per sample (left and right channels) - self->pwm->DECODER = PWM_DECODER_LOAD_Grouped; - - // we use channels 0 and 2 because these are GROUPED; it lets us save half - // the space for sample data (no additional optimization is possible for - // single channel) - self->pwm->PSEL.OUT[0] = self->left_channel_number = left_channel->number; - claim_pin(left_channel); - - if(right_channel) - { - self->pwm->PSEL.OUT[2] = self->right_channel_number = right_channel->number; - claim_pin(right_channel); - } - - self->quiescent_value = quiescent_value >> 8; - - self->pwm->ENABLE = 1; - // TODO: Ramp from 0 to quiescent value -} - -bool common_hal_audiopwmio_audioout_deinited(audiopwmio_audioout_obj_t* self) { - return !self->pwm; -} - -void common_hal_audiopwmio_audioout_deinit(audiopwmio_audioout_obj_t* self) { - if (common_hal_audiopwmio_audioout_deinited(self)) { - return; - } - // TODO: ramp the pwm down from quiescent value to 0 - self->pwm->ENABLE = 0; - - if(self->left_channel_number) - reset_pin_number(self->left_channel_number); - if(self->right_channel_number) - reset_pin_number(self->right_channel_number); - - pwmout_free_channel(self->pwm, 0); - pwmout_free_channel(self->pwm, 2); - - self->pwm = NULL; - - m_free(self->buffers[0]); - self->buffers[0] = NULL; - - m_free(self->buffers[1]); - self->buffers[1] = NULL; -} - -void common_hal_audiopwmio_audioout_play(audiopwmio_audioout_obj_t* self, mp_obj_t sample, bool loop) { - if (common_hal_audiopwmio_audioout_get_playing(self)) { - common_hal_audiopwmio_audioout_stop(self); - } - self->sample = sample; - self->loop = loop; - - uint32_t sample_rate = audiosample_sample_rate(sample); - uint32_t max_sample_rate = 62500; - if (sample_rate > max_sample_rate) { - mp_raise_ValueError_varg(translate("Sample rate too high. It must be less than %d"), max_sample_rate); - } - self->bytes_per_sample = audiosample_bits_per_sample(sample) / 8; - - uint32_t max_buffer_length; - audiosample_get_buffer_structure(sample, /* single channel */ false, - &self->single_buffer, &self->signed_to_unsigned, &max_buffer_length, - &self->spacing); - if(max_buffer_length > UINT16_MAX) { - mp_raise_ValueError_varg(translate("Buffer length %d too big. It must be less than %d"), max_buffer_length, UINT16_MAX); - } - self->buffer_length = (uint16_t)max_buffer_length; - self->buffers[0] = m_malloc(self->buffer_length * 2 * sizeof(uint16_t), false); - if(!self->single_buffer) - self->buffers[1] = m_malloc(self->buffer_length * 2 * sizeof(uint16_t), false); - - - uint32_t top; - self->pwm->SEQ[0].REFRESH = self->pwm->SEQ[1].REFRESH = calculate_pwm_parameters(sample_rate, &top); - self->scale = top-1; - self->pwm->COUNTERTOP = top; - - if(!self->single_buffer) - self->pwm->LOOP = 1; - else if(self->loop) - self->pwm->LOOP = 0xffff; - else - self->pwm->LOOP = 0; - audiosample_reset_buffer(self->sample, false, 0); - activate_audiopwmout_obj(self); - fill_buffers(self, 0); - self->pwm->SEQ[1].PTR = self->pwm->SEQ[0].PTR; - self->pwm->SEQ[1].CNT = self->pwm->SEQ[0].CNT; - self->pwm->EVENTS_SEQSTARTED[0] = 0; - self->pwm->EVENTS_SEQSTARTED[1] = 0; - self->pwm->TASKS_SEQSTART[0] = 1; - self->pwm->EVENTS_STOPPED = 0; - self->playing = true; - self->stopping = false; - self->paused = false; -} - -void common_hal_audiopwmio_audioout_stop(audiopwmio_audioout_obj_t* self) { - deactivate_audiopwmout_obj(self); - self->pwm->TASKS_STOP = 1; - self->stopping = false; - self->paused = false; - - m_free(self->buffers[0]); - self->buffers[0] = NULL; - - m_free(self->buffers[1]); - self->buffers[1] = NULL; -} - -bool common_hal_audiopwmio_audioout_get_playing(audiopwmio_audioout_obj_t* self) { - if(self->pwm->EVENTS_STOPPED) { - self->playing = false; - self->pwm->EVENTS_STOPPED = 0; - } - return self->playing; -} - -/* pause/resume present difficulties for the NRF PWM audio module. - * - * A PWM sequence can be stopped in its tracks by sending a TASKS_STOP event, - * but there's no way to pick up the sequence where it was stopped; you could - * start at the start of one of the two sequences, but especially for "single buffer" - * sample, this seems undesirable. - * - * Or, you can stop at the end of a sequence so that you don't duplicate anything - * when restarting, but again this is unsatisfactory for a "single buffer" sample. - * - * For now, I've taken the coward's way and left these methods unimplemented. - * Perhaps the way forward is to divide even "single buffer" samples into tasks of - * only a few ms long, so that they can be stopped/restarted quickly enough that it - * feels instant. (This also saves on memory, for long in-memory "single buffer" - * samples!) - */ -void common_hal_audiopwmio_audioout_pause(audiopwmio_audioout_obj_t* self) { - self->paused = true; -} - -void common_hal_audiopwmio_audioout_resume(audiopwmio_audioout_obj_t* self) { - self->paused = false; -} - -bool common_hal_audiopwmio_audioout_get_paused(audiopwmio_audioout_obj_t* self) { - return self->paused; -} diff --git a/ports/nrf/common-hal/audiopwmio/AudioOut.h b/ports/nrf/common-hal/audiopwmio/AudioOut.h deleted file mode 100644 index 9d2b823ad..000000000 --- a/ports/nrf/common-hal/audiopwmio/AudioOut.h +++ /dev/null @@ -1,59 +0,0 @@ -/* - * This file is part of the MicroPython project, http://micropython.org/ - * - * The MIT License (MIT) - * - * Copyright (c) 2019 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. - */ - -#ifndef MICROPY_INCLUDED_NRF_COMMON_HAL_AUDIOPWM_AUDIOOUT_H -#define MICROPY_INCLUDED_NRF_COMMON_HAL_AUDIOPWM_AUDIOOUT_H - -#include "common-hal/microcontroller/Pin.h" - -typedef struct { - mp_obj_base_t base; - mp_obj_t *sample; - NRF_PWM_Type *pwm; - uint16_t *buffers[2]; - - uint16_t buffer_length; - uint16_t quiescent_value; - uint16_t scale; - - uint8_t left_channel_number; - uint8_t right_channel_number; - uint8_t spacing; - uint8_t bytes_per_sample; - - bool playing; - bool stopping; - bool paused; - bool loop; - bool signed_to_unsigned; - bool single_buffer; -} audiopwmio_audioout_obj_t; - -void audiopwmout_reset(void); - -void audiopwmout_background(void); - -#endif diff --git a/ports/nrf/common-hal/audiopwmio/PWMAudioOut.c b/ports/nrf/common-hal/audiopwmio/PWMAudioOut.c new file mode 100644 index 000000000..b4c409bb6 --- /dev/null +++ b/ports/nrf/common-hal/audiopwmio/PWMAudioOut.c @@ -0,0 +1,318 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2019 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 +#include + +#include "extmod/vfs_fat.h" +#include "py/gc.h" +#include "py/mperrno.h" +#include "py/runtime.h" +#include "common-hal/audiopwmio/PWMAudioOut.h" +#include "common-hal/pulseio/PWMOut.h" +#include "shared-bindings/audiopwmio/PWMAudioOut.h" +#include "shared-bindings/microcontroller/__init__.h" +#include "shared-bindings/microcontroller/Pin.h" +#include "supervisor/shared/translate.h" + +// TODO: This should be the same size as PWMOut.c:pwms[], but there's no trivial way to accomplish that +STATIC audiopwmio_pwmaudioout_obj_t* active_audio[4]; + +#define F_TARGET (62500) +#define F_PWM (16000000) +// return the REFRESH value, store the TOP value in an out-parameter +// Tested for key values (worst relative error = 0.224% = 3.84 cents) +// 8000: top = 250 refresh = 7 [ 8000.0] +// 22050: top = 242 refresh = 2 [22038.5] +// 24000: top = 222 refresh = 2 [24024.0] +// 44100: top = 181 refresh = 1 [44198.8] +// 48000: top = 167 refresh = 1 [47904.1] +STATIC uint32_t calculate_pwm_parameters(uint32_t sample_rate, uint32_t *top_out) { + // the desired frequency is the closest integer multiple of sample_rate not less than F_TARGET + uint32_t desired_frequency = (F_TARGET + sample_rate - 1) / sample_rate * sample_rate; + // The top value is the PWM frequency divided by the desired frequency (round to nearest) + uint32_t top = (F_PWM + desired_frequency/2) / desired_frequency; + // The actual frequency is the PWM frequency divided by the top value (round to nearest) + uint32_t actual_frequency = (F_PWM + top/2) / top; + // The multiplier is the actual frequency divided by the sample rate (round to nearest) + uint32_t multiplier = (actual_frequency + sample_rate/2) / sample_rate; + *top_out = top; + return multiplier - 1; +} + +STATIC void activate_audiopwmout_obj(audiopwmio_pwmaudioout_obj_t *self) { + for(size_t i=0; i < MP_ARRAY_SIZE(active_audio); i++) { + if(!active_audio[i]) { + active_audio[i] = self; + break; + } + } +} +STATIC void deactivate_audiopwmout_obj(audiopwmio_pwmaudioout_obj_t *self) { + for(size_t i=0; i < MP_ARRAY_SIZE(active_audio); i++) { + if(active_audio[i] == self) + active_audio[i] = NULL; + } +} + +void audiopwmout_reset() { + for(size_t i=0; i < MP_ARRAY_SIZE(active_audio); i++) + active_audio[i] = NULL; +} + +STATIC void fill_buffers(audiopwmio_pwmaudioout_obj_t *self, int buf) { + self->pwm->EVENTS_SEQSTARTED[1-buf] = 0; + uint16_t *dev_buffer = self->buffers[buf]; + uint8_t *buffer; + uint32_t buffer_length; + audioio_get_buffer_result_t get_buffer_result = + audiosample_get_buffer(self->sample, false, 0, + &buffer, &buffer_length); + if (get_buffer_result == GET_BUFFER_ERROR) { + common_hal_audiopwmio_pwmaudioout_stop(self); + return; + } + uint32_t num_samples = buffer_length / self->bytes_per_sample / self->spacing; + + if(self->bytes_per_sample == 1) { + uint8_t offset = self->signed_to_unsigned ? 0x80 : 0; + uint16_t scale = self->scale; + for(uint32_t i=0; ispacing; i++) { + uint8_t rawval = (*buffer++ + offset); + uint16_t val = (uint16_t)(((uint32_t)rawval * (uint32_t)scale) >> 8); + *dev_buffer++ = val; + if(self->spacing == 1) + *dev_buffer++ = val; + } + } else { + uint16_t offset = self->signed_to_unsigned ? 0x8000 : 0; + uint16_t scale = self->scale; + uint16_t *buffer16 = (uint16_t*)buffer; + for(uint32_t i=0; ispacing; i++) { + uint16_t rawval = (*buffer16++ + offset); + uint16_t val = (uint16_t)((rawval * (uint32_t)scale) >> 16); + *dev_buffer++ = val; + if(self->spacing == 1) + *dev_buffer++ = val; + } + } + self->pwm->SEQ[buf].PTR = (intptr_t)self->buffers[buf]; + self->pwm->SEQ[buf].CNT = num_samples*2; + + if (self->loop && get_buffer_result == GET_BUFFER_DONE) { + audiosample_reset_buffer(self->sample, false, 0); + } else if(get_buffer_result == GET_BUFFER_DONE) { + self->pwm->LOOP = 0; + self->stopping = true; + } else { + self->pwm->LOOP = 0xffff; + } +} + +STATIC void audiopwmout_background_obj(audiopwmio_pwmaudioout_obj_t *self) { + if(!common_hal_audiopwmio_pwmaudioout_get_playing(self)) + return; + if(self->loop && self->single_buffer) { + self->pwm->LOOP = 0xffff; + } else if(self->stopping) { + bool stopped = + (self->pwm->EVENTS_SEQEND[0] || !self->pwm->EVENTS_SEQSTARTED[0]) && + (self->pwm->EVENTS_SEQEND[1] || !self->pwm->EVENTS_SEQSTARTED[1]); + if(stopped) + self->pwm->TASKS_STOP = 1; + } else if(!self->single_buffer) { + if(self->pwm->EVENTS_SEQSTARTED[0]) fill_buffers(self, 1); + if(self->pwm->EVENTS_SEQSTARTED[1]) fill_buffers(self, 0); + } +} + +void audiopwmout_background() { + for(size_t i=0; i < MP_ARRAY_SIZE(active_audio); i++) { + if(!active_audio[i]) continue; + audiopwmout_background_obj(active_audio[i]); + } +} + +void common_hal_audiopwmio_pwmaudioout_construct(audiopwmio_pwmaudioout_obj_t* self, + const mcu_pin_obj_t* left_channel, const mcu_pin_obj_t* right_channel, uint16_t quiescent_value) { + assert_pin_free(left_channel); + assert_pin_free(right_channel); + self->pwm = pwmout_allocate(256, PWM_PRESCALER_PRESCALER_DIV_1, true, NULL, NULL); + if(!self->pwm) { + mp_raise_RuntimeError(translate("All timers in use")); + } + + self->pwm->PRESCALER = PWM_PRESCALER_PRESCALER_DIV_1; + // two uint16_t values per sample when Grouped + // n.b. SEQ[#].CNT "counts" are 2 per sample (left and right channels) + self->pwm->DECODER = PWM_DECODER_LOAD_Grouped; + + // we use channels 0 and 2 because these are GROUPED; it lets us save half + // the space for sample data (no additional optimization is possible for + // single channel) + self->pwm->PSEL.OUT[0] = self->left_channel_number = left_channel->number; + claim_pin(left_channel); + + if(right_channel) + { + self->pwm->PSEL.OUT[2] = self->right_channel_number = right_channel->number; + claim_pin(right_channel); + } + + self->quiescent_value = quiescent_value >> 8; + + self->pwm->ENABLE = 1; + // TODO: Ramp from 0 to quiescent value +} + +bool common_hal_audiopwmio_pwmaudioout_deinited(audiopwmio_pwmaudioout_obj_t* self) { + return !self->pwm; +} + +void common_hal_audiopwmio_pwmaudioout_deinit(audiopwmio_pwmaudioout_obj_t* self) { + if (common_hal_audiopwmio_pwmaudioout_deinited(self)) { + return; + } + // TODO: ramp the pwm down from quiescent value to 0 + self->pwm->ENABLE = 0; + + if(self->left_channel_number) + reset_pin_number(self->left_channel_number); + if(self->right_channel_number) + reset_pin_number(self->right_channel_number); + + pwmout_free_channel(self->pwm, 0); + pwmout_free_channel(self->pwm, 2); + + self->pwm = NULL; + + m_free(self->buffers[0]); + self->buffers[0] = NULL; + + m_free(self->buffers[1]); + self->buffers[1] = NULL; +} + +void common_hal_audiopwmio_pwmaudioout_play(audiopwmio_pwmaudioout_obj_t* self, mp_obj_t sample, bool loop) { + if (common_hal_audiopwmio_pwmaudioout_get_playing(self)) { + common_hal_audiopwmio_pwmaudioout_stop(self); + } + self->sample = sample; + self->loop = loop; + + uint32_t sample_rate = audiosample_sample_rate(sample); + uint32_t max_sample_rate = 62500; + if (sample_rate > max_sample_rate) { + mp_raise_ValueError_varg(translate("Sample rate too high. It must be less than %d"), max_sample_rate); + } + self->bytes_per_sample = audiosample_bits_per_sample(sample) / 8; + + uint32_t max_buffer_length; + audiosample_get_buffer_structure(sample, /* single channel */ false, + &self->single_buffer, &self->signed_to_unsigned, &max_buffer_length, + &self->spacing); + if(max_buffer_length > UINT16_MAX) { + mp_raise_ValueError_varg(translate("Buffer length %d too big. It must be less than %d"), max_buffer_length, UINT16_MAX); + } + self->buffer_length = (uint16_t)max_buffer_length; + self->buffers[0] = m_malloc(self->buffer_length * 2 * sizeof(uint16_t), false); + if(!self->single_buffer) + self->buffers[1] = m_malloc(self->buffer_length * 2 * sizeof(uint16_t), false); + + + uint32_t top; + self->pwm->SEQ[0].REFRESH = self->pwm->SEQ[1].REFRESH = calculate_pwm_parameters(sample_rate, &top); + self->scale = top-1; + self->pwm->COUNTERTOP = top; + + if(!self->single_buffer) + self->pwm->LOOP = 1; + else if(self->loop) + self->pwm->LOOP = 0xffff; + else + self->pwm->LOOP = 0; + audiosample_reset_buffer(self->sample, false, 0); + activate_audiopwmout_obj(self); + fill_buffers(self, 0); + self->pwm->SEQ[1].PTR = self->pwm->SEQ[0].PTR; + self->pwm->SEQ[1].CNT = self->pwm->SEQ[0].CNT; + self->pwm->EVENTS_SEQSTARTED[0] = 0; + self->pwm->EVENTS_SEQSTARTED[1] = 0; + self->pwm->TASKS_SEQSTART[0] = 1; + self->pwm->EVENTS_STOPPED = 0; + self->playing = true; + self->stopping = false; + self->paused = false; +} + +void common_hal_audiopwmio_pwmaudioout_stop(audiopwmio_pwmaudioout_obj_t* self) { + deactivate_audiopwmout_obj(self); + self->pwm->TASKS_STOP = 1; + self->stopping = false; + self->paused = false; + + m_free(self->buffers[0]); + self->buffers[0] = NULL; + + m_free(self->buffers[1]); + self->buffers[1] = NULL; +} + +bool common_hal_audiopwmio_pwmaudioout_get_playing(audiopwmio_pwmaudioout_obj_t* self) { + if(self->pwm->EVENTS_STOPPED) { + self->playing = false; + self->pwm->EVENTS_STOPPED = 0; + } + return self->playing; +} + +/* pause/resume present difficulties for the NRF PWM audio module. + * + * A PWM sequence can be stopped in its tracks by sending a TASKS_STOP event, + * but there's no way to pick up the sequence where it was stopped; you could + * start at the start of one of the two sequences, but especially for "single buffer" + * sample, this seems undesirable. + * + * Or, you can stop at the end of a sequence so that you don't duplicate anything + * when restarting, but again this is unsatisfactory for a "single buffer" sample. + * + * For now, I've taken the coward's way and left these methods unimplemented. + * Perhaps the way forward is to divide even "single buffer" samples into tasks of + * only a few ms long, so that they can be stopped/restarted quickly enough that it + * feels instant. (This also saves on memory, for long in-memory "single buffer" + * samples!) + */ +void common_hal_audiopwmio_pwmaudioout_pause(audiopwmio_pwmaudioout_obj_t* self) { + self->paused = true; +} + +void common_hal_audiopwmio_pwmaudioout_resume(audiopwmio_pwmaudioout_obj_t* self) { + self->paused = false; +} + +bool common_hal_audiopwmio_pwmaudioout_get_paused(audiopwmio_pwmaudioout_obj_t* self) { + return self->paused; +} diff --git a/ports/nrf/common-hal/audiopwmio/PWMAudioOut.h b/ports/nrf/common-hal/audiopwmio/PWMAudioOut.h new file mode 100644 index 000000000..8deff5d34 --- /dev/null +++ b/ports/nrf/common-hal/audiopwmio/PWMAudioOut.h @@ -0,0 +1,59 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2019 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. + */ + +#ifndef MICROPY_INCLUDED_NRF_COMMON_HAL_AUDIOPWM_AUDIOOUT_H +#define MICROPY_INCLUDED_NRF_COMMON_HAL_AUDIOPWM_AUDIOOUT_H + +#include "common-hal/microcontroller/Pin.h" + +typedef struct { + mp_obj_base_t base; + mp_obj_t *sample; + NRF_PWM_Type *pwm; + uint16_t *buffers[2]; + + uint16_t buffer_length; + uint16_t quiescent_value; + uint16_t scale; + + uint8_t left_channel_number; + uint8_t right_channel_number; + uint8_t spacing; + uint8_t bytes_per_sample; + + bool playing; + bool stopping; + bool paused; + bool loop; + bool signed_to_unsigned; + bool single_buffer; +} audiopwmio_pwmaudioout_obj_t; + +void audiopwmout_reset(void); + +void audiopwmout_background(void); + +#endif diff --git a/ports/nrf/supervisor/port.c b/ports/nrf/supervisor/port.c index c98d5ab28..03f787624 100644 --- a/ports/nrf/supervisor/port.c +++ b/ports/nrf/supervisor/port.c @@ -51,7 +51,7 @@ #include "shared-bindings/rtc/__init__.h" #ifdef CIRCUITPY_AUDIOPWMIO -#include "common-hal/audiopwmio/AudioOut.h" +#include "common-hal/audiopwmio/PWMAudioOut.h" #endif static void power_warning_handler(void) { diff --git a/py/circuitpy_defns.mk b/py/circuitpy_defns.mk index 28d560a73..a6dde61da 100644 --- a/py/circuitpy_defns.mk +++ b/py/circuitpy_defns.mk @@ -227,7 +227,7 @@ $(filter $(SRC_PATTERNS), \ audiobusio/I2SOut.c \ audiobusio/PDMIn.c \ audiopwmio/__init__.c \ - audiopwmio/AudioOut.c \ + audiopwmio/PWMAudioOut.c \ audioio/__init__.c \ audioio/AudioOut.c \ bleio/__init__.c \ diff --git a/shared-bindings/audiopwmio/AudioOut.c b/shared-bindings/audiopwmio/AudioOut.c deleted file mode 100644 index 79f83da89..000000000 --- a/shared-bindings/audiopwmio/AudioOut.c +++ /dev/null @@ -1,294 +0,0 @@ -/* - * This file is part of the Micro Python project, http://micropython.org/ - * - * The MIT License (MIT) - * - * Copyright (c) 2017 Scott Shawcroft 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 - -#include "lib/utils/context_manager_helpers.h" -#include "py/binary.h" -#include "py/objproperty.h" -#include "py/runtime.h" -#include "shared-bindings/microcontroller/Pin.h" -#include "shared-bindings/audiopwmio/AudioOut.h" -#include "shared-bindings/audiocore/RawSample.h" -#include "shared-bindings/util.h" -#include "supervisor/shared/translate.h" - -//| .. currentmodule:: audiopwmio -//| -//| :class:`AudioOut` -- Output an analog audio signal -//| ======================================================== -//| -//| AudioOut can be used to output an analog audio signal on a given pin. -//| -//| .. class:: AudioOut(left_channel, *, right_channel=None, quiescent_value=0x8000) -//| -//| Create a AudioOut object associated with the given pin(s). This allows you to -//| play audio signals out on the given pin(s). In contrast to mod:`audioio`, -//| the pin(s) specified are digital pins, and are driven with a device-dependent PWM -//| signal. -//| -//| :param ~microcontroller.Pin left_channel: The pin to output the left channel to -//| :param ~microcontroller.Pin right_channel: The pin to output the right channel to -//| :param int quiescent_value: The output value when no signal is present. Samples should start -//| and end with this value to prevent audible popping. -//| -//| Simple 8ksps 440 Hz sin wave:: -//| -//| import audiocore -//| import audiopwmio -//| import board -//| import array -//| import time -//| import math -//| -//| # Generate one period of sine wav. -//| length = 8000 // 440 -//| sine_wave = array.array("H", [0] * length) -//| for i in range(length): -//| sine_wave[i] = int(math.sin(math.pi * 2 * i / 18) * (2 ** 15) + 2 ** 15) -//| -//| dac = audiopwmio.AudioOut(board.SPEAKER) -//| sine_wave = audiocore.RawSample(sine_wave, sample_rate=8000) -//| dac.play(sine_wave, loop=True) -//| time.sleep(1) -//| dac.stop() -//| -//| Playing a wave file from flash:: -//| -//| import board -//| import audiocore -//| import audiopwmio -//| import digitalio -//| -//| # Required for CircuitPlayground Express -//| speaker_enable = digitalio.DigitalInOut(board.SPEAKER_ENABLE) -//| speaker_enable.switch_to_output(value=True) -//| -//| data = open("cplay-5.1-16bit-16khz.wav", "rb") -//| wav = audiocore.WaveFile(data) -//| a = audiopwmio.AudioOut(board.SPEAKER) -//| -//| print("playing") -//| a.play(wav) -//| while a.playing: -//| pass -//| print("stopped") -//| -STATIC mp_obj_t audiopwmio_audioout_make_new(const mp_obj_type_t *type, size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { - enum { ARG_left_channel, ARG_right_channel, ARG_quiescent_value }; - static const mp_arg_t allowed_args[] = { - { MP_QSTR_left_channel, MP_ARG_OBJ | MP_ARG_REQUIRED }, - { MP_QSTR_right_channel, MP_ARG_OBJ | MP_ARG_KW_ONLY, {.u_rom_obj = mp_const_none} }, - { MP_QSTR_quiescent_value, MP_ARG_INT | MP_ARG_KW_ONLY, {.u_int = 0x8000} }, - }; - mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)]; - mp_arg_parse_all(n_args, pos_args, kw_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args); - - mp_obj_t left_channel_obj = args[ARG_left_channel].u_obj; - assert_pin(left_channel_obj, false); - const mcu_pin_obj_t *left_channel_pin = MP_OBJ_TO_PTR(left_channel_obj); - - mp_obj_t right_channel_obj = args[ARG_right_channel].u_obj; - const mcu_pin_obj_t *right_channel_pin = NULL; - if (right_channel_obj != mp_const_none) { - assert_pin(right_channel_obj, false); - right_channel_pin = MP_OBJ_TO_PTR(right_channel_obj); - } - - // create AudioOut object from the given pin - audiopwmio_audioout_obj_t *self = m_new_obj(audiopwmio_audioout_obj_t); - self->base.type = &audiopwmio_audioout_type; - common_hal_audiopwmio_audioout_construct(self, left_channel_pin, right_channel_pin, args[ARG_quiescent_value].u_int); - - return MP_OBJ_FROM_PTR(self); -} - -//| .. method:: deinit() -//| -//| Deinitialises the AudioOut and releases any hardware resources for reuse. -//| -STATIC mp_obj_t audiopwmio_audioout_deinit(mp_obj_t self_in) { - audiopwmio_audioout_obj_t *self = MP_OBJ_TO_PTR(self_in); - common_hal_audiopwmio_audioout_deinit(self); - return mp_const_none; -} -STATIC MP_DEFINE_CONST_FUN_OBJ_1(audiopwmio_audioout_deinit_obj, audiopwmio_audioout_deinit); - -STATIC void check_for_deinit(audiopwmio_audioout_obj_t *self) { - if (common_hal_audiopwmio_audioout_deinited(self)) { - raise_deinited_error(); - } -} -//| .. method:: __enter__() -//| -//| No-op used by Context Managers. -//| -// Provided by context manager helper. - -//| .. method:: __exit__() -//| -//| Automatically deinitializes the hardware when exiting a context. See -//| :ref:`lifetime-and-contextmanagers` for more info. -//| -STATIC mp_obj_t audiopwmio_audioout_obj___exit__(size_t n_args, const mp_obj_t *args) { - (void)n_args; - common_hal_audiopwmio_audioout_deinit(args[0]); - return mp_const_none; -} -STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(audiopwmio_audioout___exit___obj, 4, 4, audiopwmio_audioout_obj___exit__); - - -//| .. method:: play(sample, *, loop=False) -//| -//| Plays the sample once when loop=False and continuously when loop=True. -//| Does not block. Use `playing` to block. -//| -//| Sample must be an `audiocore.WaveFile`, `audiocore.RawSample`, or `audiocore.Mixer`. -//| -//| The sample itself should consist of 16 bit samples. Microcontrollers with a lower output -//| resolution will use the highest order bits to output. For example, the SAMD21 has a 10 bit -//| DAC that ignores the lowest 6 bits when playing 16 bit samples. -//| -STATIC mp_obj_t audiopwmio_audioout_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} }, - }; - audiopwmio_audioout_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_audiopwmio_audioout_play(self, sample, args[ARG_loop].u_bool); - - return mp_const_none; -} -MP_DEFINE_CONST_FUN_OBJ_KW(audiopwmio_audioout_play_obj, 1, audiopwmio_audioout_obj_play); - -//| .. method:: stop() -//| -//| Stops playback and resets to the start of the sample. -//| -STATIC mp_obj_t audiopwmio_audioout_obj_stop(mp_obj_t self_in) { - audiopwmio_audioout_obj_t *self = MP_OBJ_TO_PTR(self_in); - check_for_deinit(self); - common_hal_audiopwmio_audioout_stop(self); - return mp_const_none; -} -MP_DEFINE_CONST_FUN_OBJ_1(audiopwmio_audioout_stop_obj, audiopwmio_audioout_obj_stop); - -//| .. attribute:: playing -//| -//| True when an audio sample is being output even if `paused`. (read-only) -//| -STATIC mp_obj_t audiopwmio_audioout_obj_get_playing(mp_obj_t self_in) { - audiopwmio_audioout_obj_t *self = MP_OBJ_TO_PTR(self_in); - check_for_deinit(self); - return mp_obj_new_bool(common_hal_audiopwmio_audioout_get_playing(self)); -} -MP_DEFINE_CONST_FUN_OBJ_1(audiopwmio_audioout_get_playing_obj, audiopwmio_audioout_obj_get_playing); - -const mp_obj_property_t audiopwmio_audioout_playing_obj = { - .base.type = &mp_type_property, - .proxy = {(mp_obj_t)&audiopwmio_audioout_get_playing_obj, - (mp_obj_t)&mp_const_none_obj, - (mp_obj_t)&mp_const_none_obj}, -}; - -//| .. method:: pause() -//| -//| Stops playback temporarily while remembering the position. Use `resume` to resume playback. -//| -STATIC mp_obj_t audiopwmio_audioout_obj_pause(mp_obj_t self_in) { - audiopwmio_audioout_obj_t *self = MP_OBJ_TO_PTR(self_in); - check_for_deinit(self); - - if (!common_hal_audiopwmio_audioout_get_playing(self)) { - mp_raise_RuntimeError(translate("Not playing")); - } - common_hal_audiopwmio_audioout_pause(self); - return mp_const_none; -} -MP_DEFINE_CONST_FUN_OBJ_1(audiopwmio_audioout_pause_obj, audiopwmio_audioout_obj_pause); - -//| .. method:: resume() -//| -//| Resumes sample playback after :py:func:`pause`. -//| -STATIC mp_obj_t audiopwmio_audioout_obj_resume(mp_obj_t self_in) { - audiopwmio_audioout_obj_t *self = MP_OBJ_TO_PTR(self_in); - check_for_deinit(self); - - if (common_hal_audiopwmio_audioout_get_paused(self)) { - common_hal_audiopwmio_audioout_resume(self); - } - - return mp_const_none; -} -MP_DEFINE_CONST_FUN_OBJ_1(audiopwmio_audioout_resume_obj, audiopwmio_audioout_obj_resume); - -//| .. attribute:: paused -//| -//| True when playback is paused. (read-only) -//| -STATIC mp_obj_t audiopwmio_audioout_obj_get_paused(mp_obj_t self_in) { - audiopwmio_audioout_obj_t *self = MP_OBJ_TO_PTR(self_in); - check_for_deinit(self); - return mp_obj_new_bool(common_hal_audiopwmio_audioout_get_paused(self)); -} -MP_DEFINE_CONST_FUN_OBJ_1(audiopwmio_audioout_get_paused_obj, audiopwmio_audioout_obj_get_paused); - -const mp_obj_property_t audiopwmio_audioout_paused_obj = { - .base.type = &mp_type_property, - .proxy = {(mp_obj_t)&audiopwmio_audioout_get_paused_obj, - (mp_obj_t)&mp_const_none_obj, - (mp_obj_t)&mp_const_none_obj}, -}; - -STATIC const mp_rom_map_elem_t audiopwmio_audioout_locals_dict_table[] = { - // Methods - { MP_ROM_QSTR(MP_QSTR_deinit), MP_ROM_PTR(&audiopwmio_audioout_deinit_obj) }, - { MP_ROM_QSTR(MP_QSTR___enter__), MP_ROM_PTR(&default___enter___obj) }, - { MP_ROM_QSTR(MP_QSTR___exit__), MP_ROM_PTR(&audiopwmio_audioout___exit___obj) }, - { MP_ROM_QSTR(MP_QSTR_play), MP_ROM_PTR(&audiopwmio_audioout_play_obj) }, - { MP_ROM_QSTR(MP_QSTR_stop), MP_ROM_PTR(&audiopwmio_audioout_stop_obj) }, - { MP_ROM_QSTR(MP_QSTR_pause), MP_ROM_PTR(&audiopwmio_audioout_pause_obj) }, - { MP_ROM_QSTR(MP_QSTR_resume), MP_ROM_PTR(&audiopwmio_audioout_resume_obj) }, - - // Properties - { MP_ROM_QSTR(MP_QSTR_playing), MP_ROM_PTR(&audiopwmio_audioout_playing_obj) }, - { MP_ROM_QSTR(MP_QSTR_paused), MP_ROM_PTR(&audiopwmio_audioout_paused_obj) }, -}; -STATIC MP_DEFINE_CONST_DICT(audiopwmio_audioout_locals_dict, audiopwmio_audioout_locals_dict_table); - -const mp_obj_type_t audiopwmio_audioout_type = { - { &mp_type_type }, - .name = MP_QSTR_PWMAudioOut, - .make_new = audiopwmio_audioout_make_new, - .locals_dict = (mp_obj_dict_t*)&audiopwmio_audioout_locals_dict, -}; diff --git a/shared-bindings/audiopwmio/AudioOut.h b/shared-bindings/audiopwmio/AudioOut.h deleted file mode 100644 index 7fb0e0f33..000000000 --- a/shared-bindings/audiopwmio/AudioOut.h +++ /dev/null @@ -1,49 +0,0 @@ -/* - * This file is part of the Micro Python project, http://micropython.org/ - * - * The MIT License (MIT) - * - * Copyright (c) 2017 Scott Shawcroft 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. - */ - -#ifndef MICROPY_INCLUDED_SHARED_BINDINGS_AUDIOPWMIO_AUDIOOUT_H -#define MICROPY_INCLUDED_SHARED_BINDINGS_AUDIOPWMIO_AUDIOOUT_H - -#include "common-hal/audiopwmio/AudioOut.h" -#include "common-hal/microcontroller/Pin.h" -#include "shared-bindings/audiocore/RawSample.h" - -extern const mp_obj_type_t audiopwmio_audioout_type; - -// left_channel will always be non-NULL but right_channel may be for mono output. -void common_hal_audiopwmio_audioout_construct(audiopwmio_audioout_obj_t* self, - const mcu_pin_obj_t* left_channel, const mcu_pin_obj_t* right_channel, uint16_t default_value); - -void common_hal_audiopwmio_audioout_deinit(audiopwmio_audioout_obj_t* self); -bool common_hal_audiopwmio_audioout_deinited(audiopwmio_audioout_obj_t* self); -void common_hal_audiopwmio_audioout_play(audiopwmio_audioout_obj_t* self, mp_obj_t sample, bool loop); -void common_hal_audiopwmio_audioout_stop(audiopwmio_audioout_obj_t* self); -bool common_hal_audiopwmio_audioout_get_playing(audiopwmio_audioout_obj_t* self); -void common_hal_audiopwmio_audioout_pause(audiopwmio_audioout_obj_t* self); -void common_hal_audiopwmio_audioout_resume(audiopwmio_audioout_obj_t* self); -bool common_hal_audiopwmio_audioout_get_paused(audiopwmio_audioout_obj_t* self); - -#endif // MICROPY_INCLUDED_SHARED_BINDINGS_AUDIOPWMIO_AUDIOOUT_H diff --git a/shared-bindings/audiopwmio/PWMAudioOut.c b/shared-bindings/audiopwmio/PWMAudioOut.c new file mode 100644 index 000000000..042da270d --- /dev/null +++ b/shared-bindings/audiopwmio/PWMAudioOut.c @@ -0,0 +1,294 @@ +/* + * This file is part of the Micro Python project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2017 Scott Shawcroft 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 + +#include "lib/utils/context_manager_helpers.h" +#include "py/binary.h" +#include "py/objproperty.h" +#include "py/runtime.h" +#include "shared-bindings/microcontroller/Pin.h" +#include "shared-bindings/audiopwmio/PWMAudioOut.h" +#include "shared-bindings/audiocore/RawSample.h" +#include "shared-bindings/util.h" +#include "supervisor/shared/translate.h" + +//| .. currentmodule:: audiopwmio +//| +//| :class:`AudioOut` -- Output an analog audio signal +//| ======================================================== +//| +//| AudioOut can be used to output an analog audio signal on a given pin. +//| +//| .. class:: AudioOut(left_channel, *, right_channel=None, quiescent_value=0x8000) +//| +//| Create a AudioOut object associated with the given pin(s). This allows you to +//| play audio signals out on the given pin(s). In contrast to mod:`audioio`, +//| the pin(s) specified are digital pins, and are driven with a device-dependent PWM +//| signal. +//| +//| :param ~microcontroller.Pin left_channel: The pin to output the left channel to +//| :param ~microcontroller.Pin right_channel: The pin to output the right channel to +//| :param int quiescent_value: The output value when no signal is present. Samples should start +//| and end with this value to prevent audible popping. +//| +//| Simple 8ksps 440 Hz sin wave:: +//| +//| import audiocore +//| import audiopwmio +//| import board +//| import array +//| import time +//| import math +//| +//| # Generate one period of sine wav. +//| length = 8000 // 440 +//| sine_wave = array.array("H", [0] * length) +//| for i in range(length): +//| sine_wave[i] = int(math.sin(math.pi * 2 * i / 18) * (2 ** 15) + 2 ** 15) +//| +//| dac = audiopwmio.AudioOut(board.SPEAKER) +//| sine_wave = audiocore.RawSample(sine_wave, sample_rate=8000) +//| dac.play(sine_wave, loop=True) +//| time.sleep(1) +//| dac.stop() +//| +//| Playing a wave file from flash:: +//| +//| import board +//| import audiocore +//| import audiopwmio +//| import digitalio +//| +//| # Required for CircuitPlayground Express +//| speaker_enable = digitalio.DigitalInOut(board.SPEAKER_ENABLE) +//| speaker_enable.switch_to_output(value=True) +//| +//| data = open("cplay-5.1-16bit-16khz.wav", "rb") +//| wav = audiocore.WaveFile(data) +//| a = audiopwmio.AudioOut(board.SPEAKER) +//| +//| print("playing") +//| a.play(wav) +//| while a.playing: +//| pass +//| print("stopped") +//| +STATIC mp_obj_t audiopwmio_pwmaudioout_make_new(const mp_obj_type_t *type, size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { + enum { ARG_left_channel, ARG_right_channel, ARG_quiescent_value }; + static const mp_arg_t allowed_args[] = { + { MP_QSTR_left_channel, MP_ARG_OBJ | MP_ARG_REQUIRED }, + { MP_QSTR_right_channel, MP_ARG_OBJ | MP_ARG_KW_ONLY, {.u_rom_obj = mp_const_none} }, + { MP_QSTR_quiescent_value, MP_ARG_INT | MP_ARG_KW_ONLY, {.u_int = 0x8000} }, + }; + mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)]; + mp_arg_parse_all(n_args, pos_args, kw_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args); + + mp_obj_t left_channel_obj = args[ARG_left_channel].u_obj; + assert_pin(left_channel_obj, false); + const mcu_pin_obj_t *left_channel_pin = MP_OBJ_TO_PTR(left_channel_obj); + + mp_obj_t right_channel_obj = args[ARG_right_channel].u_obj; + const mcu_pin_obj_t *right_channel_pin = NULL; + if (right_channel_obj != mp_const_none) { + assert_pin(right_channel_obj, false); + right_channel_pin = MP_OBJ_TO_PTR(right_channel_obj); + } + + // create AudioOut object from the given pin + audiopwmio_pwmaudioout_obj_t *self = m_new_obj(audiopwmio_pwmaudioout_obj_t); + self->base.type = &audiopwmio_pwmaudioout_type; + common_hal_audiopwmio_pwmaudioout_construct(self, left_channel_pin, right_channel_pin, args[ARG_quiescent_value].u_int); + + return MP_OBJ_FROM_PTR(self); +} + +//| .. method:: deinit() +//| +//| Deinitialises the AudioOut and releases any hardware resources for reuse. +//| +STATIC mp_obj_t audiopwmio_pwmaudioout_deinit(mp_obj_t self_in) { + audiopwmio_pwmaudioout_obj_t *self = MP_OBJ_TO_PTR(self_in); + common_hal_audiopwmio_pwmaudioout_deinit(self); + return mp_const_none; +} +STATIC MP_DEFINE_CONST_FUN_OBJ_1(audiopwmio_pwmaudioout_deinit_obj, audiopwmio_pwmaudioout_deinit); + +STATIC void check_for_deinit(audiopwmio_pwmaudioout_obj_t *self) { + if (common_hal_audiopwmio_pwmaudioout_deinited(self)) { + raise_deinited_error(); + } +} +//| .. method:: __enter__() +//| +//| No-op used by Context Managers. +//| +// Provided by context manager helper. + +//| .. method:: __exit__() +//| +//| Automatically deinitializes the hardware when exiting a context. See +//| :ref:`lifetime-and-contextmanagers` for more info. +//| +STATIC mp_obj_t audiopwmio_pwmaudioout_obj___exit__(size_t n_args, const mp_obj_t *args) { + (void)n_args; + common_hal_audiopwmio_pwmaudioout_deinit(args[0]); + return mp_const_none; +} +STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(audiopwmio_pwmaudioout___exit___obj, 4, 4, audiopwmio_pwmaudioout_obj___exit__); + + +//| .. method:: play(sample, *, loop=False) +//| +//| Plays the sample once when loop=False and continuously when loop=True. +//| Does not block. Use `playing` to block. +//| +//| Sample must be an `audiocore.WaveFile`, `audiocore.RawSample`, or `audiocore.Mixer`. +//| +//| The sample itself should consist of 16 bit samples. Microcontrollers with a lower output +//| resolution will use the highest order bits to output. For example, the SAMD21 has a 10 bit +//| DAC that ignores the lowest 6 bits when playing 16 bit samples. +//| +STATIC mp_obj_t audiopwmio_pwmaudioout_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} }, + }; + audiopwmio_pwmaudioout_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_audiopwmio_pwmaudioout_play(self, sample, args[ARG_loop].u_bool); + + return mp_const_none; +} +MP_DEFINE_CONST_FUN_OBJ_KW(audiopwmio_pwmaudioout_play_obj, 1, audiopwmio_pwmaudioout_obj_play); + +//| .. method:: stop() +//| +//| Stops playback and resets to the start of the sample. +//| +STATIC mp_obj_t audiopwmio_pwmaudioout_obj_stop(mp_obj_t self_in) { + audiopwmio_pwmaudioout_obj_t *self = MP_OBJ_TO_PTR(self_in); + check_for_deinit(self); + common_hal_audiopwmio_pwmaudioout_stop(self); + return mp_const_none; +} +MP_DEFINE_CONST_FUN_OBJ_1(audiopwmio_pwmaudioout_stop_obj, audiopwmio_pwmaudioout_obj_stop); + +//| .. attribute:: playing +//| +//| True when an audio sample is being output even if `paused`. (read-only) +//| +STATIC mp_obj_t audiopwmio_pwmaudioout_obj_get_playing(mp_obj_t self_in) { + audiopwmio_pwmaudioout_obj_t *self = MP_OBJ_TO_PTR(self_in); + check_for_deinit(self); + return mp_obj_new_bool(common_hal_audiopwmio_pwmaudioout_get_playing(self)); +} +MP_DEFINE_CONST_FUN_OBJ_1(audiopwmio_pwmaudioout_get_playing_obj, audiopwmio_pwmaudioout_obj_get_playing); + +const mp_obj_property_t audiopwmio_pwmaudioout_playing_obj = { + .base.type = &mp_type_property, + .proxy = {(mp_obj_t)&audiopwmio_pwmaudioout_get_playing_obj, + (mp_obj_t)&mp_const_none_obj, + (mp_obj_t)&mp_const_none_obj}, +}; + +//| .. method:: pause() +//| +//| Stops playback temporarily while remembering the position. Use `resume` to resume playback. +//| +STATIC mp_obj_t audiopwmio_pwmaudioout_obj_pause(mp_obj_t self_in) { + audiopwmio_pwmaudioout_obj_t *self = MP_OBJ_TO_PTR(self_in); + check_for_deinit(self); + + if (!common_hal_audiopwmio_pwmaudioout_get_playing(self)) { + mp_raise_RuntimeError(translate("Not playing")); + } + common_hal_audiopwmio_pwmaudioout_pause(self); + return mp_const_none; +} +MP_DEFINE_CONST_FUN_OBJ_1(audiopwmio_pwmaudioout_pause_obj, audiopwmio_pwmaudioout_obj_pause); + +//| .. method:: resume() +//| +//| Resumes sample playback after :py:func:`pause`. +//| +STATIC mp_obj_t audiopwmio_pwmaudioout_obj_resume(mp_obj_t self_in) { + audiopwmio_pwmaudioout_obj_t *self = MP_OBJ_TO_PTR(self_in); + check_for_deinit(self); + + if (common_hal_audiopwmio_pwmaudioout_get_paused(self)) { + common_hal_audiopwmio_pwmaudioout_resume(self); + } + + return mp_const_none; +} +MP_DEFINE_CONST_FUN_OBJ_1(audiopwmio_pwmaudioout_resume_obj, audiopwmio_pwmaudioout_obj_resume); + +//| .. attribute:: paused +//| +//| True when playback is paused. (read-only) +//| +STATIC mp_obj_t audiopwmio_pwmaudioout_obj_get_paused(mp_obj_t self_in) { + audiopwmio_pwmaudioout_obj_t *self = MP_OBJ_TO_PTR(self_in); + check_for_deinit(self); + return mp_obj_new_bool(common_hal_audiopwmio_pwmaudioout_get_paused(self)); +} +MP_DEFINE_CONST_FUN_OBJ_1(audiopwmio_pwmaudioout_get_paused_obj, audiopwmio_pwmaudioout_obj_get_paused); + +const mp_obj_property_t audiopwmio_pwmaudioout_paused_obj = { + .base.type = &mp_type_property, + .proxy = {(mp_obj_t)&audiopwmio_pwmaudioout_get_paused_obj, + (mp_obj_t)&mp_const_none_obj, + (mp_obj_t)&mp_const_none_obj}, +}; + +STATIC const mp_rom_map_elem_t audiopwmio_pwmaudioout_locals_dict_table[] = { + // Methods + { MP_ROM_QSTR(MP_QSTR_deinit), MP_ROM_PTR(&audiopwmio_pwmaudioout_deinit_obj) }, + { MP_ROM_QSTR(MP_QSTR___enter__), MP_ROM_PTR(&default___enter___obj) }, + { MP_ROM_QSTR(MP_QSTR___exit__), MP_ROM_PTR(&audiopwmio_pwmaudioout___exit___obj) }, + { MP_ROM_QSTR(MP_QSTR_play), MP_ROM_PTR(&audiopwmio_pwmaudioout_play_obj) }, + { MP_ROM_QSTR(MP_QSTR_stop), MP_ROM_PTR(&audiopwmio_pwmaudioout_stop_obj) }, + { MP_ROM_QSTR(MP_QSTR_pause), MP_ROM_PTR(&audiopwmio_pwmaudioout_pause_obj) }, + { MP_ROM_QSTR(MP_QSTR_resume), MP_ROM_PTR(&audiopwmio_pwmaudioout_resume_obj) }, + + // Properties + { MP_ROM_QSTR(MP_QSTR_playing), MP_ROM_PTR(&audiopwmio_pwmaudioout_playing_obj) }, + { MP_ROM_QSTR(MP_QSTR_paused), MP_ROM_PTR(&audiopwmio_pwmaudioout_paused_obj) }, +}; +STATIC MP_DEFINE_CONST_DICT(audiopwmio_pwmaudioout_locals_dict, audiopwmio_pwmaudioout_locals_dict_table); + +const mp_obj_type_t audiopwmio_pwmaudioout_type = { + { &mp_type_type }, + .name = MP_QSTR_PWMAudioOut, + .make_new = audiopwmio_pwmaudioout_make_new, + .locals_dict = (mp_obj_dict_t*)&audiopwmio_pwmaudioout_locals_dict, +}; diff --git a/shared-bindings/audiopwmio/PWMAudioOut.h b/shared-bindings/audiopwmio/PWMAudioOut.h new file mode 100644 index 000000000..22afc70d3 --- /dev/null +++ b/shared-bindings/audiopwmio/PWMAudioOut.h @@ -0,0 +1,49 @@ +/* + * This file is part of the Micro Python project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2017 Scott Shawcroft 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. + */ + +#ifndef MICROPY_INCLUDED_SHARED_BINDINGS_AUDIOPWMIO_AUDIOOUT_H +#define MICROPY_INCLUDED_SHARED_BINDINGS_AUDIOPWMIO_AUDIOOUT_H + +#include "common-hal/audiopwmio/PWMAudioOut.h" +#include "common-hal/microcontroller/Pin.h" +#include "shared-bindings/audiocore/RawSample.h" + +extern const mp_obj_type_t audiopwmio_pwmaudioout_type; + +// left_channel will always be non-NULL but right_channel may be for mono output. +void common_hal_audiopwmio_pwmaudioout_construct(audiopwmio_pwmaudioout_obj_t* self, + const mcu_pin_obj_t* left_channel, const mcu_pin_obj_t* right_channel, uint16_t default_value); + +void common_hal_audiopwmio_pwmaudioout_deinit(audiopwmio_pwmaudioout_obj_t* self); +bool common_hal_audiopwmio_pwmaudioout_deinited(audiopwmio_pwmaudioout_obj_t* self); +void common_hal_audiopwmio_pwmaudioout_play(audiopwmio_pwmaudioout_obj_t* self, mp_obj_t sample, bool loop); +void common_hal_audiopwmio_pwmaudioout_stop(audiopwmio_pwmaudioout_obj_t* self); +bool common_hal_audiopwmio_pwmaudioout_get_playing(audiopwmio_pwmaudioout_obj_t* self); +void common_hal_audiopwmio_pwmaudioout_pause(audiopwmio_pwmaudioout_obj_t* self); +void common_hal_audiopwmio_pwmaudioout_resume(audiopwmio_pwmaudioout_obj_t* self); +bool common_hal_audiopwmio_pwmaudioout_get_paused(audiopwmio_pwmaudioout_obj_t* self); + +#endif // MICROPY_INCLUDED_SHARED_BINDINGS_AUDIOPWMIO_AUDIOOUT_H diff --git a/shared-bindings/audiopwmio/__init__.c b/shared-bindings/audiopwmio/__init__.c index 6253d1e8e..aa41b0d4b 100644 --- a/shared-bindings/audiopwmio/__init__.c +++ b/shared-bindings/audiopwmio/__init__.c @@ -31,7 +31,7 @@ #include "shared-bindings/microcontroller/Pin.h" #include "shared-bindings/audiopwmio/__init__.h" -#include "shared-bindings/audiopwmio/AudioOut.h" +#include "shared-bindings/audiopwmio/PWMAudioOut.h" //| :mod:`audiopwmio` --- Support for audio input and output //| ======================================================== @@ -60,7 +60,7 @@ STATIC const mp_rom_map_elem_t audiopwmio_module_globals_table[] = { { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_audiopwmio) }, - { MP_ROM_QSTR(MP_QSTR_AudioOut), MP_ROM_PTR(&audiopwmio_audioout_type) }, + { MP_ROM_QSTR(MP_QSTR_AudioOut), MP_ROM_PTR(&audiopwmio_pwmaudioout_type) }, }; STATIC MP_DEFINE_CONST_DICT(audiopwmio_module_globals, audiopwmio_module_globals_table); -- cgit v1.2.3