From c80e5f9f8868ccaa8cb990be6f4da3f1011c2b78 Mon Sep 17 00:00:00 2001 From: Drashna Jaelre Date: Sun, 14 Feb 2021 14:40:38 -0800 Subject: Audio system overhaul (#11820) * Redo Arm DAC implementation for additive, wavetable synthesis, sample playback changes by Jack Humbert on an implementation for DAC audio on arm/chibios platforms this commits bundles the changes from the arm-dac-work branch focused on audio/audio_arm.* into one commit (leaving out the test-keyboard) f52faeb5d (origin/arm-dac-work) add sample and wavetable examples, parsers for both -> only the changes on audio_arm_.*, the keyboard related parts are split off to a separate commit bfe468ef1 start morphing wavetable 474d100b5 refined a bit 208bee10f play_notes working 3e6478b0b start in-place documentation of dac settings 3e1826a33 fixed blip (rounding error), other waves, added key selection (left/right) 73853d651 5 voices at 44.1khz dfb401b95 limit voices to working number 9632b3379 configuration for the ez 6241f3f3b notes working in a new way * Redo Arm DAC implementation for additive, wavetable synthesis, sample playback changes by Jack Humbert on an implementation for DAC audio on arm/chibios platforms this commit splits off the plank example keymap from commit f52faeb5d (origin/arm-dac-work) add sample and wavetable examples, parsers for both * refactoring: rename audio_ to reflect their supported hardware-platform and audio-generation method: avr vs arm, and pwm vs dac * refactoring: deducplicate ISR code to update the pwm duty-cycle and period in the avr-pwm-implementation pulls three copies of the same code into one function which should improve readability and maintainability :-) * refactoring: move common code of arm and avr implementation into a separate/new file * refactoring: audio_avr_pwm, renaming defines to decouple them from actually used timers, registers and ISRs * refactoring: audio_avr_pwm - replacing function defines with plain register defines aligns better with other existing qmk code (and the new audio_arm_pwm) doing similar pwm thing * add audio-arm-pwm since not all STM32 have a DAC onboard (STM32F2xx and STM32F3xx), pwm-audio is an alternative (STM32F1xx) this code works on a "BluePill" clone, with an STM32F103C8B * clang-format changes on quantum/audio/* only * audio_arm_dac: stopping the notes caused screeching when using the DAC audio paths * audio_arm_pwm: use pushpull on the pin; so that a piezzo can be hooked up direclty without additional components (opendrain would require an external pullup) * refactoring: remove unused file from/for atmel-avr chips * refactoring: remove unused (avr) wavetable file * audio_arm_dac: adapt dac_end callback to changed chibios DAC api the previous chibios (17.6.0) passed along a pointer into the buffer plus a sample_count (which are/already where included in the DACDrivre object) - the current chibios (19.1.0) only passes the driver object. this patch ports more or less exactly what the previous chibios ISR code did: either have the user-callback work the first or second half of the buffer (dacsample_t pointer, with half the DAC_BUFFER_SIZE samples) by adjusting the pointer and sample count * audio-arm-dac: show a compile-warning on undefined audio-pins Co-Authored-By: Drashna Jaelre * audio_arm_dac: switch from exemplary wavetable generation to sine only sine+triangle+squrare is exemplary, and not realy fit for "production" use 'stairs' are usefull for debugging (hardware, with an oscilloscope) * audio_arm_dac: enable output buffers in the STM32 to drive external loads without any additional ciruitry - external opamps and such * audio: prevent out-of-bounds array access * audio_arm_dac: add output-frequency correcting factor * audio_arm_pwm: get both the alternate-function and pm-callback variants back into working condition and do some code-cleanup, refine documentation, ... * audio_arm_pwm: increase pwm frequency for "higher fidelity" on the previous .frequency=100000 higher frequency musical notes came out wrong (frequency measured on a Tektronix TDS2014B) note | freq | arm-pwm C2 | 65.4 | 65.491 C5 | 523.25 | 523.93 C6 | 1046.5 | 1053.38 C7 | 2093 | 2129 C8 | 4186 | 4350.91 with .frequency = 500000 C8 | 4186 | 4204.6 * audio refactoring: remove unused variables * audio_arm_dac: calibrate note tempo: with a tempo of 60beats-per-second a whole-note should last for exactly one second * audio: allow feature selection in rules.mk so the user can switch the audio driver between DAC and PWM on STM32 boards which support both (STM32F2 and up) or select the "pin alternate" pwm mode, for example on STM32F103 * audio-refactoring: move codeblocks in audio.[ch] into more coherent groups and add some inline documentation * audio-refactoring: cleanup and streamline common code between audio_arm_[dac|pwm] untangeling the relation between audio.c and the two drivers and adding more documenting comments :-) * audio_avr_pwm: getting it back into working condition, and cleanup+refactor * audio-refactoring: documentation and typo fixes Co-Authored-By: Nick Brassel * audio-refactoring: cleanup defines, inludes and remove debug-prints * audio_chibios_dac: define&use a minimal sampling rate, based on the available tone-range to ease up on the cpu-load, while still rendering the higher notes/tones sufficiently also reenable the lower tones, since with the new implementation there is no evidence of them still beeing 'bugged' * audio-refactoring: one common AUDIO_MAX_VOICES define for all audio-drivers * audio-chibios-pwm: pwm-pin-allternate: make the the timer, timer-channel and alternate function user-#definable * audio_chibios_dac: math.h has fmod for this * Redo Arm DAC implementation for additive, wavetable synthesis, sample playback update Jack Humberts dac-example keymaps for the slight changes in the audio-dac interface * audio-refactoring: use a common AUDIO_PIN configuration switch instead of defines have the user select a pin by configuration in rules.mk instead of a define in config.h has the advantage of beeing in a common form/pattern across all audio-driver implementations * audio-refactoring: switch backlight_avr.c to the new AUDIO_PIN defines * audio-common: have advance_note return a boolean if the note changed, to the next one in the melody beeing played * audio-chibios-pwm: fix issue with ~130ms silence between note/frequency changes while playing a SONG through trial,error and a scope/logic analyzer figured out Chibios-PWMDriver (at least in the current version) misbehaves if the initial period is set to zero (or one; two seems to work); when thats the case subsequent calls to 'pwmChhangePeriod' + pwmEnableChannel took ~135ms of silence, before the PWM continued with the new frequency... * audio-refactoring: get 'play_note' working again with a limited number of available voices (say AUDIO_VOICES_MAX=1) allow new frequencies to be played, by discarding the oldest one in the 'frequencies' queue * audio: set the fallback driver to DAC for chibios and PWM for all others (==avr at the moment) * audio-refactoring: moore documentation and some cleanup * audio-avr-pwm: no fallback on unset AUDIO_PIN this seems to be the expected behaviour by some keyboards (looking at ckeys/handwire_101:default) which otherwise fail to build because the firmware-image ends up beeing too large for the atmega... so we fail silently instead to keep travis happy * audio-refactoring: untangling terminology: voice->tone the code actually was working on tones (combination of pitch/frequency, duration, timbre, intensity/volume) and not voices (characteristic sound of an instrument; think piano vs guitar, which can be played together, each having its own "track" = voice on a music sheet) * audio-pwm: allow freq=0 aka a pause/rest in a SONG continue processing, but do not enable pwm units, since freq=0 wouldn't produce any sound anyway (and lead to division by zero on that occasion) * audio-refactoring: audio_advance_note -> audio_advance_state since it does not only affect 'one note', but the internally kept state as a whole * audio-refactoring: untangling terminology: polyphony the feature om the "inherited" avr code has little to do with polyphony (see wikipedia), but is more a time-multiplexing feature, to work around hardware limitations - like only having one pwm channel, that could on its own only reproduce one voice/instrument at a time * audio-chibios-dac: add zero-crossing feature have tones only change/stop when the waveform approaches zero - to avoid audible clicks note that this also requires the samples to start at zero, since the internally kept index into the samples is reset to zero too * audio-refactoring: feature: time-multiplexing of tones on a single output channel this feature was in the original avr-pwm implementation misnomed as "polyphony" with polyphony_rate and so on; did the same thing though: time-multiplexing multiple active notes so that a single output channel could reproduce more than one note at a time (which is not the same as a polyphony - see wikipedia :-) ) * audio-avr-pwm: get music-mode working (again) on AVRs with both pwm channels, or either one of the two :-) play_notes worked already - but music_mode uses play_note * audio-refactoring: split define MAX_SIMULTANEOUS_TONES -> TONE_STACKSIZE since the two cases are independant from one another, the hardware might impose limitations on the number of simultaneously reproducable tones, but the audio state should be able to track an unrelated number of notes recently started by play_note * audio-arm-dac: per define selectable sample-luts plus generation script in ./util * audio-refactoring: heh, avr has a MIN... * audio-refactoring: add basic dac audio-driver based on the current/master implementation whereas current=d96380e65496912e0f68e6531565f4b45efd1623 which is the state of things before this whole audio-refactoring branch boiled down to interface with the refactored audio system = removing all redundant state-managing and frequency calculation * audio-refactoring: rename audio-drivers to driver_$PLATFORM_$DRIVER * audio-arm-pwm: split the software/hardware implementations into separate files which saves us partially from a 'define hell', with the tradeoff that now two somewhat similar chibios_pwm implementations have to be maintained * audio-refactoring: update documentation * audio-arm-dac: apply AUDIO_PIN defines to driver_chibios_dac_basic * audio-arm-dac: dac_additive: stop the hardware when the last sample completed the audio system calls for a driver_stop, which is delayed until the current sample conversion finishes * audio-refactoring: make function-namespace consistent - all (public) audio functions start with audio_ - also refactoring play*_notes/tones to play*_melody, to visually distance it a bit from play*_tone/_note * audio-refactoring: consistent define namespace: DAC_ -> AUDIO_DAC_ * audio-arm-dac: update (inline) documentation regarding MAX for sample values * audio-chibios-dac: remove zero-crossing feature didn't quite work as intended anyway, and stopping the hardware on close-to-zero seems to be enought anyway * audio-arm-dac: dac_basic: respect the configured sample-rate * audio-arm-pwm: have 'note_timbre' influence the pwm-duty cycle like it already does in the avr implementation * audio-refactoring: get VIBRATO working (again) with all drivers (verified with chibios_[dac|pwm]) * audio-arm-dac: zero-crossing feature (Mk II) wait for the generated waveform to approach 'zero' before either turning off the output+timer or switching to the current set of active_tones * audio-refactoring: re-add note-resting -> introduce short_rest inbetween - introduce a short pause/rest between two notes of the same frequency, to separate them audibly - also updating the refactoring comments * audio-refactoring: cleanup refactoring remnants remove the former avr-isr code block - since all its features are now refactored into the different parts of the current system also updates the TODOS * audio-refactoring: reserve negative numbers as unitialized frequencies to allow the valid tone/frequency f=0Hz == rest/pause * audio-refactoring: FIX: first note of melody was missing the first note was missing because 'goto_next_note'=false overrode a state_change=true of the initial play_tone and some code-indentations/cleanup of related parts * audio-arm-dac: fix hardware init-click due to wron .init= value * audio-refactoring: new conveniance function: audio_play_click which can be used to further refactor/remove fauxclicky (avr only) and/or the 'clicky' features * audio-refactoring: clang-format on quantum/audio/* * audio-avr-pwm: consecutive notes of the same frequency get a pause inserted inbetween by audio.c * audio-refactoring: use milliseconds instead of seconds for 'click' parameters clicks are supposed to be short, seconds make little sense * audio-refactoring: use timer ticks instead of counters local counters were used in the original (avr)ISR to advance an index into the lookup tables (for vibrato), and something similar was used for the tone-multiplexing feature decoupling these from the (possibly irregular) calls to advance_state made sesne, since those counters/lookups need to be in relation to a wall-time anyway * audio-refactoring: voices.c: drop 'envelope_index' counter in favour of timer ticks * audio-refactoring: move vibrato and timbre related parts from audio.c to voices.c also drops the now (globally) unused AUDIO_VIBRATO/AUDIO_ENABLE_VIBRATO defines * audio.c: use system-ticks instead of counters the drivers have to take care of for the internal state posision since there already is a system-tick with ms resolution, keeping count separatly with each driver implementation makes little sense; especially since they had to take special care to call audio_advance_state with the correct step/end parameters for the audio state to advance regularly and with the correct pace * audio.c: stop notes after new ones have been started avoids brief states of with no notes playing that would otherwise stop the hardware and might lead to clicks * audio.c: bugfix: actually play a pause instead of just idling/stopping which lead the pwm drivers to stop entirely... * audio-arm-pwm: pwm-software: add inverted output new define AUDIO_PIN_ALT_AS_NEGATIVE will generate an inverted signal on the alternate pin, which boosts the volume if a piezo is connected to both AUDIO_PIN and AUDIO_PIN_ALT * audio-arm-dac: basic: handle piezo configured&wired to both audio pins * audio-refactoring: docs: update for AUDIO_PIN_ALT_AS_NEGATIVE and piezo wiring * audio.c: bugfix: use timer_elapsed32 instad of keeping timestamps avoids running into issues when the uint32 of the timer overflows * audio-refactoring: add 'pragma once' and remove deprecated NOTE_REST * audio_arm_dac: basic: add missing bracket * audio.c: fix delta calculation was in the wrong place, needs to use the 'last_timestamp' before it was reset * audio-refactoring: buildfix: wrong legacy macro for set_timbre * audio.c: 16bit timerstamps suffice * audio-refactoring: separate includes for AVR and chibios * audio-refactoring: timbre: use uint8 instead of float * audio-refactoring: duration: use uint16 for internal per-tone/note state * audio-refactoring: tonemultiplexing: use uint16 instead of float * audio-arm-dac: additive: set second pin output-low used when a piezo is connected to AUDIO_PIN and AUDIO_PIN_ALT, with PIN_ALT_AS_NEGATIVE * audio-refactoring: move AUDIO_PIN selection from rules.mk to config.h to be consistent with how other features are handled in QMK * audio-refactoring: buildfix: wrong legacy macro for set_tempo * audio-arm-dac: additive: set second pin output-low -- FIXUP * audio.c: do duration<>ms conversion in uint instead of float on AVR, to save a couple of bytes in the firmware size * audio-refactoring: cleanup eeprom defines/usage for ARM, avr is handled automagically through the avr libc and common_features.mk Co-Authored-By: Drashna Jaelre * audio.h: throw an error if OFF is larger than MAX * audio-arm-dac: basic: actually stop the dac-conversion on a audio_driver_stop to put the output pin in a known state == AUDIO_DAC_OFF_VALUE, instead of just leaving them where the last conversion was... with AUDIO_PIN_ALT_AS_NEGATIVE this meant one output was left HIGH while the other was left LOW one CAVEAT: due to this change the opposing squarewave when using both A4 and A5 with AUDIO_PIN_ALT_AS_NEGATIVE show extra pulses at the beginning/end on one of the outputs, the two waveforms are in sync otherwise. the extra pusles probably matter little, since this is no high-fidelity sound generation :P * audio-arm-dac: additive: move zero-crossing code out of dac_value_generate which is/should be user-overridable == simple, and doing one thing: providing sample values state-transitions necessary for the zero crossing are better handled in the surrounding loop in the dac_end callback * audio-arm-dac: dac-additive: zero-crossing: ramping up or down after a start trigger ramp up: generate values until zero=OFF_VALUE is reached, then continue normally same in reverse for strop trigger: output values until zero is reached/crossed, then keep OFF_VALUE on the output * audio-arm-dac: dac-additive: BUGFIX: return OFF_VALUE when a pause is playing fixes a bug during SONG playback, which suddenly stopped when it encoutnered a pause * audio-arm-dac: set a sensible default for AUDIO_DAC_VALUE_OFF 1/2 MAX was probably exemplary, can't think of a setup where that would make sense :-P * audio-arm-dac: update synth_sample/_wavetable for new pin-defines * audio-arm-dac: default for AUDIO_DAC_VALUE_OFF turned out that zero or max are bad default choices: when multiple tones are played (>>5) and released at the same time (!), due to the complex waveform never reaching 'zero' the output can take quite a while to reach zero, and hence the zero-crossing code only "releases" the output waaay to late * audio-arm-dac: additive: use DAC for negative pin instead of PAL, which only allows the pin to be configured as output; LOW or HIGH * audio-arm-dac: more compile-time configuration checks * audio-refactoring: typo fixed * audio-refactoring: clang-format on quantum/audio/* * audio-avr-pwm: add defines for B-pin as primary/only speaker also updates documentation. * audio-refactoring: update documentation with proton-c config.h example * audio-refactoring: move glissando (TODO) to voices.c refactored/saved from the original glissando implementation in then upstream-master:audio_avr.c still needs some work though, as it is now the calculation *should* work, but the start-frequency needs to be tracked somewhere/somehow; not only during a SONG playback but also with user input? * audio-refactoring: cleanup: one round of aspell -c * audio-avr-pwm: back to AUDIO_PIN since config_common.h expands them to plain integers, the AUDIO_PIN define can directly be compared to e.g. B5 so there is no need to deal with separate defines like AUDIO_PIN_B5 * audio-refactoring: add technical documentation audio_driver.md which moves some in-code documentation there * audio-arm-dac: move AUDIO_PIN checks into c-code instead of doing everything with the preprocessor, since A4/A5 do not expand to simple integers, preprocessor int-comparison is not possible. but necessary to get a consistent configuration scheme going throughout the audio-code... solution: let c-code handle the different AUDIO_PIN configurations instead (and leave code/size optimizations to the compiler) * audio-arm-dac: compile-fix: set AUDIO_PIN if unset workaround to get the build going again, and be backwarts compatible to arm-keyboards which not yet set the AUDIO_PIN define. until the define is enforced through an '#error" * audio-refactoring: document tone-multiplexing feature * audio-refactoring: Apply suggestions from documentation review Co-authored-by: James Young <18669334+noroadsleft@users.noreply.github.com> * audio-refactoring: Update docs/audio_driver.md * audio-refactoring: docs: fix markdown newlines Terminating a line in Markdown with -- creates an HTML single-line break (
). Co-authored-by: James Young <18669334+noroadsleft@users.noreply.github.com> * audio-arm-dac: additive: fix AUDIO_PIN_ALT handling * audio-arm-pwm: align define naming with other drivers Co-authored-by: Joel Challis * audio-refactoring: set detault tempo to 120 and add documentation for the override * audio-refactoring: update backlight define checks to new AUDIO_PIN names * audio-refactoring: reworking PWM related defines to be more consistent with other QMK code Co-authored-by: Joel Challis * audio-arm: have the state-update-timer user configurable defaulting to GPTD6 or GPTD8 for stm32f2+ (=proton-c) stm32f1 might need to set this to GPTD4, since 6 and 8 are not available * audio-refactoring: PLAY_NOTE_ARRAY was already removed in master * Add prototype for startup * Update chibiOS dac basic to disable pins on stop * Add defaults for Proton C * avoid hanging audio if note is completely missed * Don't redefine pins if they're already defined * Define A4 and A5 for CTPC support * Add license headers to keymap files * Remove figlet? comments * Add DAC config to audio driver docs * Apply suggestions from code review Co-authored-by: Jack Humbert * Add license header to py files * correct license header * Add JohSchneider's name to modified files AKA credit where credit's due * Set executable permission and change interpeter * Add 'wave' to pip requirements * Improve documentation * Add some settings I missed * Strip AUDIO_DRIVER to parse the name correctly * fix depreciated * Update util/audio_generate_dac_lut.py Co-authored-by: Jack Humbert * Fix type in clueboard config * Apply suggestions from tzarc Co-authored-by: Nick Brassel Co-authored-by: Johannes Co-authored-by: JohSchneider Co-authored-by: Nick Brassel Co-authored-by: James Young <18669334+noroadsleft@users.noreply.github.com> Co-authored-by: Joel Challis Co-authored-by: Joshua Diamond Co-authored-by: Jack Humbert --- quantum/audio/audio.c | 539 ++++++++++++++++++ quantum/audio/audio.h | 281 ++++++++-- quantum/audio/audio_avr.c | 812 ---------------------------- quantum/audio/audio_chibios.c | 721 ------------------------ quantum/audio/audio_pwm.c | 606 --------------------- quantum/audio/driver_avr_pwm.h | 17 + quantum/audio/driver_avr_pwm_hardware.c | 322 +++++++++++ quantum/audio/driver_chibios_dac.h | 126 +++++ quantum/audio/driver_chibios_dac_additive.c | 335 ++++++++++++ quantum/audio/driver_chibios_dac_basic.c | 245 +++++++++ quantum/audio/driver_chibios_pwm.h | 40 ++ quantum/audio/driver_chibios_pwm_hardware.c | 144 +++++ quantum/audio/driver_chibios_pwm_software.c | 164 ++++++ quantum/audio/musical_notes.h | 77 +-- quantum/audio/voices.c | 170 ++++-- quantum/audio/voices.h | 21 +- quantum/audio/wave.h | 36 -- 17 files changed, 2337 insertions(+), 2319 deletions(-) create mode 100644 quantum/audio/audio.c delete mode 100644 quantum/audio/audio_avr.c delete mode 100644 quantum/audio/audio_chibios.c delete mode 100644 quantum/audio/audio_pwm.c create mode 100644 quantum/audio/driver_avr_pwm.h create mode 100644 quantum/audio/driver_avr_pwm_hardware.c create mode 100644 quantum/audio/driver_chibios_dac.h create mode 100644 quantum/audio/driver_chibios_dac_additive.c create mode 100644 quantum/audio/driver_chibios_dac_basic.c create mode 100644 quantum/audio/driver_chibios_pwm.h create mode 100644 quantum/audio/driver_chibios_pwm_hardware.c create mode 100644 quantum/audio/driver_chibios_pwm_software.c delete mode 100644 quantum/audio/wave.h (limited to 'quantum/audio') diff --git a/quantum/audio/audio.c b/quantum/audio/audio.c new file mode 100644 index 0000000000..46277dd70b --- /dev/null +++ b/quantum/audio/audio.c @@ -0,0 +1,539 @@ +/* Copyright 2016-2020 Jack Humbert + * Copyright 2020 JohSchneider + + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +#include "audio.h" +#include "eeconfig.h" +#include "timer.h" +#include "wait.h" + +/* audio system: + * + * audio.[ch] takes care of all overall state, tracking the actively playing + * notes/tones; the notes a SONG consists of; + * ... + * = everything audio-related that is platform agnostic + * + * driver_[avr|chibios]_[dac|pwm] take care of the lower hardware dependent parts, + * specific to each platform and the used subsystem/driver to drive + * the output pins/channels with the calculated frequencies for each + * active tone + * as part of this, the driver has to trigger regular state updates by + * calling 'audio_update_state' through some sort of timer - be it a + * dedicated one or piggybacking on for example the timer used to + * generate a pwm signal/clock. + * + * + * A Note on terminology: + * tone, pitch and frequency are used somewhat interchangeably, in a strict Wikipedia-sense: + * "(Musical) tone, a sound characterized by its duration, pitch (=frequency), + * intensity (=volume), and timbre" + * - intensity/volume is currently not handled at all, although the 'dac_additive' driver could do so + * - timbre is handled globally (TODO: only used with the pwm drivers at the moment) + * + * in musical_note.h a 'note' is the combination of a pitch and a duration + * these are used to create SONG arrays; during playback their frequencies + * are handled as single successive tones, while the durations are + * kept track of in 'audio_update_state' + * + * 'voice' as it is used here, equates to a sort of instrument with its own + * characteristics sound and effects + * the audio system as-is deals only with (possibly multiple) tones of one + * instrument/voice at a time (think: chords). since the number of tones that + * can be reproduced depends on the hardware/driver in use: pwm can only + * reproduce one tone per output/speaker; DACs can reproduce/mix multiple + * when doing additive synthesis. + * + * 'duration' can either be in the beats-per-minute related unit found in + * musical_notes.h, OR in ms; keyboards create SONGs with the former, while + * the internal state of the audio system does its calculations with the later - ms + */ + +#ifndef AUDIO_TONE_STACKSIZE +# define AUDIO_TONE_STACKSIZE 8 +#endif +uint8_t active_tones = 0; // number of tones pushed onto the stack by audio_play_tone - might be more than the hardware is able to reproduce at any single time +musical_tone_t tones[AUDIO_TONE_STACKSIZE]; // stack of currently active tones + +bool playing_melody = false; // playing a SONG? +bool playing_note = false; // or (possibly multiple simultaneous) tones +bool state_changed = false; // global flag, which is set if anything changes with the active_tones + +// melody/SONG related state variables +float (*notes_pointer)[][2]; // SONG, an array of MUSICAL_NOTEs +uint16_t notes_count; // length of the notes_pointer array +bool notes_repeat; // PLAY_SONG or PLAY_LOOP? +uint16_t melody_current_note_duration = 0; // duration of the currently playing note from the active melody, in ms +uint8_t note_tempo = TEMPO_DEFAULT; // beats-per-minute +uint16_t current_note = 0; // index into the array at notes_pointer +bool note_resting = false; // if a short pause was introduced between two notes with the same frequency while playing a melody +uint16_t last_timestamp = 0; + +#ifdef AUDIO_ENABLE_TONE_MULTIPLEXING +# ifndef AUDIO_MAX_SIMULTANEOUS_TONES +# define AUDIO_MAX_SIMULTANEOUS_TONES 3 +# endif +uint16_t tone_multiplexing_rate = AUDIO_TONE_MULTIPLEXING_RATE_DEFAULT; +uint8_t tone_multiplexing_index_shift = 0; // offset used on active-tone array access +#endif + +// provided and used by voices.c +extern uint8_t note_timbre; +extern bool glissando; +extern bool vibrato; +extern uint16_t voices_timer; + +#ifndef STARTUP_SONG +# define STARTUP_SONG SONG(STARTUP_SOUND) +#endif +#ifndef AUDIO_ON_SONG +# define AUDIO_ON_SONG SONG(AUDIO_ON_SOUND) +#endif +#ifndef AUDIO_OFF_SONG +# define AUDIO_OFF_SONG SONG(AUDIO_OFF_SOUND) +#endif +float startup_song[][2] = STARTUP_SONG; +float audio_on_song[][2] = AUDIO_ON_SONG; +float audio_off_song[][2] = AUDIO_OFF_SONG; + +static bool audio_initialized = false; +static bool audio_driver_stopped = true; +audio_config_t audio_config; + +void audio_init() { + if (audio_initialized) { + return; + } + + // Check EEPROM +#ifdef EEPROM_ENABLE + if (!eeconfig_is_enabled()) { + eeconfig_init(); + } + audio_config.raw = eeconfig_read_audio(); +#else // EEPROM settings + audio_config.enable = true; +# ifdef AUDIO_CLICKY_ON + audio_config.clicky_enable = true; +# endif +#endif // EEPROM settings + + for (uint8_t i = 0; i < AUDIO_TONE_STACKSIZE; i++) { + tones[i] = (musical_tone_t){.time_started = 0, .pitch = -1.0f, .duration = 0}; + } + + if (!audio_initialized) { + audio_driver_initialize(); + audio_initialized = true; + } + stop_all_notes(); +} + +void audio_startup(void) { + if (audio_config.enable) { + PLAY_SONG(startup_song); + } + + last_timestamp = timer_read(); +} + +void audio_toggle(void) { + if (audio_config.enable) { + stop_all_notes(); + } + audio_config.enable ^= 1; + eeconfig_update_audio(audio_config.raw); + if (audio_config.enable) { + audio_on_user(); + } +} + +void audio_on(void) { + audio_config.enable = 1; + eeconfig_update_audio(audio_config.raw); + audio_on_user(); + PLAY_SONG(audio_on_song); +} + +void audio_off(void) { + PLAY_SONG(audio_off_song); + wait_ms(100); + audio_stop_all(); + audio_config.enable = 0; + eeconfig_update_audio(audio_config.raw); +} + +bool audio_is_on(void) { return (audio_config.enable != 0); } + +void audio_stop_all() { + if (audio_driver_stopped) { + return; + } + + active_tones = 0; + + audio_driver_stop(); + + playing_melody = false; + playing_note = false; + + melody_current_note_duration = 0; + + for (uint8_t i = 0; i < AUDIO_TONE_STACKSIZE; i++) { + tones[i] = (musical_tone_t){.time_started = 0, .pitch = -1.0f, .duration = 0}; + } + + audio_driver_stopped = true; +} + +void audio_stop_tone(float pitch) { + if (pitch < 0.0f) { + pitch = -1 * pitch; + } + + if (playing_note) { + if (!audio_initialized) { + audio_init(); + } + bool found = false; + for (int i = AUDIO_TONE_STACKSIZE - 1; i >= 0; i--) { + found = (tones[i].pitch == pitch); + if (found) { + tones[i] = (musical_tone_t){.time_started = 0, .pitch = -1.0f, .duration = 0}; + for (int j = i; (j < AUDIO_TONE_STACKSIZE - 1); j++) { + tones[j] = tones[j + 1]; + tones[j + 1] = (musical_tone_t){.time_started = 0, .pitch = -1.0f, .duration = 0}; + } + break; + } + } + if (!found) { + return; + } + + state_changed = true; + active_tones--; + if (active_tones < 0) active_tones = 0; +#ifdef AUDIO_ENABLE_TONE_MULTIPLEXING + if (tone_multiplexing_index_shift >= active_tones) { + tone_multiplexing_index_shift = 0; + } +#endif + if (active_tones == 0) { + audio_driver_stop(); + audio_driver_stopped = true; + playing_note = false; + } + } +} + +void audio_play_note(float pitch, uint16_t duration) { + if (!audio_config.enable) { + return; + } + + if (!audio_initialized) { + audio_init(); + } + + if (pitch < 0.0f) { + pitch = -1 * pitch; + } + + // round-robin: shifting out old tones, keeping only unique ones + // if the new frequency is already amongst the active tones, shift it to the top of the stack + bool found = false; + for (int i = active_tones - 1; i >= 0; i--) { + found = (tones[i].pitch == pitch); + if (found) { + for (int j = i; (j < active_tones - 1); j++) { + tones[j] = tones[j + 1]; + tones[j + 1] = (musical_tone_t){.time_started = timer_read(), .pitch = pitch, .duration = duration}; + } + return; // since this frequency played already, the hardware was already started + } + } + + // frequency/tone is actually new, so we put it on the top of the stack + active_tones++; + if (active_tones > AUDIO_TONE_STACKSIZE) { + active_tones = AUDIO_TONE_STACKSIZE; + // shift out the oldest tone to make room + for (int i = 0; i < active_tones - 1; i++) { + tones[i] = tones[i + 1]; + } + } + state_changed = true; + playing_note = true; + tones[active_tones - 1] = (musical_tone_t){.time_started = timer_read(), .pitch = pitch, .duration = duration}; + + // TODO: needs to be handled per note/tone -> use its timestamp instead? + voices_timer = timer_read(); // reset to zero, for the effects added by voices.c + + if (audio_driver_stopped) { + audio_driver_start(); + audio_driver_stopped = false; + } +} + +void audio_play_tone(float pitch) { audio_play_note(pitch, 0xffff); } + +void audio_play_melody(float (*np)[][2], uint16_t n_count, bool n_repeat) { + if (!audio_config.enable) { + audio_stop_all(); + return; + } + + if (!audio_initialized) { + audio_init(); + } + + // Cancel note if a note is playing + if (playing_note) audio_stop_all(); + + playing_melody = true; + note_resting = false; + + notes_pointer = np; + notes_count = n_count; + notes_repeat = n_repeat; + + current_note = 0; // note in the melody-array/list at note_pointer + + // start first note manually, which also starts the audio_driver + // all following/remaining notes are played by 'audio_update_state' + audio_play_note((*notes_pointer)[current_note][0], audio_duration_to_ms((*notes_pointer)[current_note][1])); + last_timestamp = timer_read(); + melody_current_note_duration = audio_duration_to_ms((*notes_pointer)[current_note][1]); +} + +float click[2][2]; +void audio_play_click(uint16_t delay, float pitch, uint16_t duration) { + uint16_t duration_tone = audio_ms_to_duration(duration); + uint16_t duration_delay = audio_ms_to_duration(delay); + + if (delay <= 0.0f) { + click[0][0] = pitch; + click[0][1] = duration_tone; + click[1][0] = 0.0f; + click[1][1] = 0.0f; + audio_play_melody(&click, 1, false); + } else { + // first note is a rest/pause + click[0][0] = 0.0f; + click[0][1] = duration_delay; + // second note is the actual click + click[1][0] = pitch; + click[1][1] = duration_tone; + audio_play_melody(&click, 2, false); + } +} + +bool audio_is_playing_note(void) { return playing_note; } + +bool audio_is_playing_melody(void) { return playing_melody; } + +uint8_t audio_get_number_of_active_tones(void) { return active_tones; } + +float audio_get_frequency(uint8_t tone_index) { + if (tone_index >= active_tones) { + return 0.0f; + } + return tones[active_tones - tone_index - 1].pitch; +} + +float audio_get_processed_frequency(uint8_t tone_index) { + if (tone_index >= active_tones) { + return 0.0f; + } + + int8_t index = active_tones - tone_index - 1; + // new tones are stacked on top (= appended at the end), so the most recent/current is MAX-1 + +#ifdef AUDIO_ENABLE_TONE_MULTIPLEXING + index = index - tone_multiplexing_index_shift; + if (index < 0) // wrap around + index += active_tones; +#endif + + if (tones[index].pitch <= 0.0f) { + return 0.0f; + } + + return voice_envelope(tones[index].pitch); +} + +bool audio_update_state(void) { + if (!playing_note && !playing_melody) { + return false; + } + + bool goto_next_note = false; + uint16_t current_time = timer_read(); + + if (playing_melody) { + goto_next_note = timer_elapsed(last_timestamp) >= melody_current_note_duration; + if (goto_next_note) { + uint16_t delta = timer_elapsed(last_timestamp) - melody_current_note_duration; + last_timestamp = current_time; + uint16_t previous_note = current_note; + current_note++; + voices_timer = timer_read(); // reset to zero, for the effects added by voices.c + + if (current_note >= notes_count) { + if (notes_repeat) { + current_note = 0; + } else { + audio_stop_all(); + return false; + } + } + + if (!note_resting && (*notes_pointer)[previous_note][0] == (*notes_pointer)[current_note][0]) { + note_resting = true; + + // special handling for successive notes of the same frequency: + // insert a short pause to separate them audibly + audio_play_note(0.0f, audio_duration_to_ms(2)); + current_note = previous_note; + melody_current_note_duration = audio_duration_to_ms(2); + + } else { + note_resting = false; + + // TODO: handle glissando here (or remember previous and current tone) + /* there would need to be a freq(here we are) -> freq(next note) + * and do slide/glissando in between problem here is to know which + * frequency on the stack relates to what other? e.g. a melody starts + * tones in a sequence, and stops expiring one, so the most recently + * stopped is the starting point for a glissando to the most recently started? + * how to detect and preserve this relation? + * and what about user input, chords, ...? + */ + + // '- delta': Skip forward in the next note's length if we've over shot + // the last, so the overall length of the song is the same + uint16_t duration = audio_duration_to_ms((*notes_pointer)[current_note][1]); + + // Skip forward past any completely missed notes + while (delta > duration && current_note < notes_count - 1) { + delta -= duration; + current_note++; + duration = audio_duration_to_ms((*notes_pointer)[current_note][1]); + } + + if (delta < duration) { + duration -= delta; + } else { + // Only way to get here is if it is the last note and + // we have completely missed it. Play it for 1ms... + duration = 1; + } + + audio_play_note((*notes_pointer)[current_note][0], duration); + melody_current_note_duration = duration; + } + } + } + + if (playing_note) { +#ifdef AUDIO_ENABLE_TONE_MULTIPLEXING + tone_multiplexing_index_shift = (int)(current_time / tone_multiplexing_rate) % MIN(AUDIO_MAX_SIMULTANEOUS_TONES, active_tones); + goto_next_note = true; +#endif + if (vibrato || glissando) { + // force update on each cycle, since vibrato shifts the frequency slightly + goto_next_note = true; + } + + // housekeeping: stop notes that have no playtime left + for (int i = 0; i < active_tones; i++) { + if ((tones[i].duration != 0xffff) // indefinitely playing notes, started by 'audio_play_tone' + && (tones[i].duration != 0) // 'uninitialized' + ) { + if (timer_elapsed(tones[i].time_started) >= tones[i].duration) { + audio_stop_tone(tones[i].pitch); // also sets 'state_changed=true' + } + } + } + } + + // state-changes have a higher priority, always triggering the hardware to update + if (state_changed) { + state_changed = false; + return true; + } + + return goto_next_note; +} + +// Tone-multiplexing functions +#ifdef AUDIO_ENABLE_TONE_MULTIPLEXING +void audio_set_tone_multiplexing_rate(uint16_t rate) { tone_multiplexing_rate = rate; } +void audio_enable_tone_multiplexing(void) { tone_multiplexing_rate = AUDIO_TONE_MULTIPLEXING_RATE_DEFAULT; } +void audio_disable_tone_multiplexing(void) { tone_multiplexing_rate = 0; } +void audio_increase_tone_multiplexing_rate(uint16_t change) { + if ((0xffff - change) > tone_multiplexing_rate) { + tone_multiplexing_rate += change; + } +} +void audio_decrease_tone_multiplexing_rate(uint16_t change) { + if (change <= tone_multiplexing_rate) { + tone_multiplexing_rate -= change; + } +} +#endif + +// Tempo functions + +void audio_set_tempo(uint8_t tempo) { + if (tempo < 10) note_tempo = 10; + // else if (tempo > 250) + // note_tempo = 250; + else + note_tempo = tempo; +} + +void audio_increase_tempo(uint8_t tempo_change) { + if (tempo_change > 255 - note_tempo) + note_tempo = 255; + else + note_tempo += tempo_change; +} + +void audio_decrease_tempo(uint8_t tempo_change) { + if (tempo_change >= note_tempo - 10) + note_tempo = 10; + else + note_tempo -= tempo_change; +} + +// TODO in the int-math version are some bugs; songs sometimes abruptly end - maybe an issue with the timer/system-tick wrapping around? +uint16_t audio_duration_to_ms(uint16_t duration_bpm) { +#if defined(__AVR__) + // doing int-math saves us some bytes in the overall firmware size, but the intermediate result is less accurate before being cast to/returned as uint + return ((uint32_t)duration_bpm * 60 * 1000) / (64 * note_tempo); + // NOTE: beware of uint16_t overflows when note_tempo is low and/or the duration is long +#else + return ((float)duration_bpm * 60) / (64 * note_tempo) * 1000; +#endif +} +uint16_t audio_ms_to_duration(uint16_t duration_ms) { +#if defined(__AVR__) + return ((uint32_t)duration_ms * 64 * note_tempo) / 60 / 1000; +#else + return ((float)duration_ms * 64 * note_tempo) / 60 / 1000; +#endif +} diff --git a/quantum/audio/audio.h b/quantum/audio/audio.h index dccf03d5f6..56b9158a1a 100644 --- a/quantum/audio/audio.h +++ b/quantum/audio/audio.h @@ -1,4 +1,5 @@ -/* Copyright 2016 Jack Humbert +/* Copyright 2016-2020 Jack Humbert + * Copyright 2020 JohSchneider * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -13,28 +14,30 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ - #pragma once #include #include -#if defined(__AVR__) -# include -#endif -#include "wait.h" #include "musical_notes.h" #include "song_list.h" #include "voices.h" #include "quantum.h" #include -// Largely untested PWM audio mode (doesn't sound as good) -// #define PWM_AUDIO - -// #define VIBRATO_ENABLE +#if defined(__AVR__) +# include +# if defined(AUDIO_DRIVER_PWM) +# include "driver_avr_pwm.h" +# endif +#endif -// Enable vibrato strength/amplitude - slows down ISR too much -// #define VIBRATO_STRENGTH_ENABLE +#if defined(PROTOCOL_CHIBIOS) +# if defined(AUDIO_DRIVER_PWM) +# include "driver_chibios_pwm.h" +# elif defined(AUDIO_DRIVER_DAC) +# include "driver_chibios_dac.h" +# endif +#endif typedef union { uint8_t raw; @@ -45,62 +48,238 @@ typedef union { }; } audio_config_t; -bool is_audio_on(void); +// AVR/LUFA has a MIN, arm/chibios does not +#ifndef MIN +# define MIN(a, b) (((a) < (b)) ? (a) : (b)) +#endif + +/* + * a 'musical note' is represented by pitch and duration; a 'musical tone' adds intensity and timbre + * https://en.wikipedia.org/wiki/Musical_tone + * "A musical tone is characterized by its duration, pitch, intensity (or loudness), and timbre (or quality)" + */ +typedef struct { + uint16_t time_started; // timestamp the tone/note was started, system time runs with 1ms resolution -> 16bit timer overflows every ~64 seconds, long enough under normal circumstances; but might be too soon for long-duration notes when the note_tempo is set to a very low value + float pitch; // aka frequency, in Hz + uint16_t duration; // in ms, converted from the musical_notes.h unit which has 64parts to a beat, factoring in the current tempo in beats-per-minute + // float intensity; // aka volume [0,1] TODO: not used at the moment; pwm drivers can't handle it + // uint8_t timbre; // range: [0,100] TODO: this currently kept track of globally, should we do this per tone instead? +} musical_tone_t; + +// public interface + +/** + * @brief one-time initialization called by quantum/quantum.c + * @details usually done lazy, when some tones are to be played + * + * @post audio system (and hardware) initialized and ready to play tones + */ +void audio_init(void); +void audio_startup(void); + +/** + * @brief en-/disable audio output, save this choice to the eeprom + */ void audio_toggle(void); +/** + * @brief enable audio output, save this choice to the eeprom + */ void audio_on(void); +/** + * @brief disable audio output, save this choice to the eeprom + */ void audio_off(void); +/** + * @brief query the if audio output is enabled + */ +bool audio_is_on(void); -// Vibrato rate functions +/** + * @brief start playback of a tone with the given frequency and duration + * + * @details starts the playback of a given note, which is automatically stopped + * at the the end of its duration = fire&forget + * + * @param[in] pitch frequency of the tone be played + * @param[in] duration in milliseconds, use 'audio_duration_to_ms' to convert + * from the musical_notes.h unit to ms + */ +void audio_play_note(float pitch, uint16_t duration); +// TODO: audio_play_note(float pitch, uint16_t duration, float intensity, float timbre); +// audio_play_note_with_instrument ifdef AUDIO_ENABLE_VOICES -#ifdef VIBRATO_ENABLE +/** + * @brief start playback of a tone with the given frequency + * + * @details the 'frequency' is put on-top the internal stack of active tones, + * as a new tone with indefinite duration. this tone is played by + * the hardware until a call to 'audio_stop_tone'. + * should a tone with that frequency already be active, its entry + * is put on the top of said internal stack - so no duplicate + * entries are kept. + * 'hardware_start' is called upon the first note. + * + * @param[in] pitch frequency of the tone be played + */ +void audio_play_tone(float pitch); -void set_vibrato_rate(float rate); -void increase_vibrato_rate(float change); -void decrease_vibrato_rate(float change); +/** + * @brief stop a given tone/frequency + * + * @details removes a tone matching the given frequency from the internal + * playback stack + * the hardware is stopped in case this was the last/only frequency + * being played. + * + * @param[in] pitch tone/frequency to be stopped + */ +void audio_stop_tone(float pitch); -# ifdef VIBRATO_STRENGTH_ENABLE +/** + * @brief play a melody + * + * @details starts playback of a melody passed in from a SONG definition - an + * array of {pitch, duration} float-tuples + * + * @param[in] np note-pointer to the SONG array + * @param[in] n_count number of MUSICAL_NOTES of the SONG + * @param[in] n_repeat false for onetime, true for looped playback + */ +void audio_play_melody(float (*np)[][2], uint16_t n_count, bool n_repeat); -void set_vibrato_strength(float strength); -void increase_vibrato_strength(float change); -void decrease_vibrato_strength(float change); +/** + * @brief play a short tone of a specific frequency to emulate a 'click' + * + * @details constructs a two-note melody (one pause plus a note) and plays it through + * audio_play_melody. very short durations might not quite work due to + * hardware limitations (DAC: added pulses from zero-crossing feature;...) + * + * @param[in] delay in milliseconds, length for the pause before the pulses, can be zero + * @param[in] pitch + * @param[in] duration in milliseconds, length of the 'click' + */ +void audio_play_click(uint16_t delay, float pitch, uint16_t duration); -# endif +/** + * @brief stops all playback + * + * @details stops playback of both a melody as well as single tones, resetting + * the internal state + */ +void audio_stop_all(void); -#endif +/** + * @brief query if one/multiple tones are playing + */ +bool audio_is_playing_note(void); -// Polyphony functions +/** + * @brief query if a melody/SONG is playing + */ +bool audio_is_playing_melody(void); -void set_polyphony_rate(float rate); -void enable_polyphony(void); -void disable_polyphony(void); -void increase_polyphony_rate(float change); -void decrease_polyphony_rate(float change); +// These macros are used to allow audio_play_melody to play an array of indeterminate +// length. This works around the limitation of C's sizeof operation on pointers. +// The global float array for the song must be used here. +#define NOTE_ARRAY_SIZE(x) ((int16_t)(sizeof(x) / (sizeof(x[0])))) -void set_timbre(float timbre); -void set_tempo(uint8_t tempo); +/** + * @brief convenience macro, to play a melody/SONG once + */ +#define PLAY_SONG(note_array) audio_play_melody(¬e_array, NOTE_ARRAY_SIZE((note_array)), false) +// TODO: a 'song' is a melody plus singing/vocals -> PLAY_MELODY +/** + * @brief convenience macro, to play a melody/SONG in a loop, until stopped by 'audio_stop_all' + */ +#define PLAY_LOOP(note_array) audio_play_melody(¬e_array, NOTE_ARRAY_SIZE((note_array)), true) -void increase_tempo(uint8_t tempo_change); -void decrease_tempo(uint8_t tempo_change); +// Tone-Multiplexing functions +// this feature only makes sense for hardware setups which can't do proper +// audio-wave synthesis = have no DAC and need to use PWM for tone generation +#ifdef AUDIO_ENABLE_TONE_MULTIPLEXING +# ifndef AUDIO_TONE_MULTIPLEXING_RATE_DEFAULT +# define AUDIO_TONE_MULTIPLEXING_RATE_DEFAULT 0 +// 0=off, good starting value is 4; the lower the value the higher the cpu-load +# endif +void audio_set_tone_multiplexing_rate(uint16_t rate); +void audio_enable_tone_multiplexing(void); +void audio_disable_tone_multiplexing(void); +void audio_increase_tone_multiplexing_rate(uint16_t change); +void audio_decrease_tone_multiplexing_rate(uint16_t change); +#endif + +// Tempo functions + +void audio_set_tempo(uint8_t tempo); +void audio_increase_tempo(uint8_t tempo_change); +void audio_decrease_tempo(uint8_t tempo_change); + +// conversion macros, from 64parts-to-a-beat to milliseconds and back +uint16_t audio_duration_to_ms(uint16_t duration_bpm); +uint16_t audio_ms_to_duration(uint16_t duration_ms); -void audio_init(void); void audio_startup(void); -#ifdef PWM_AUDIO -void play_sample(uint8_t* s, uint16_t l, bool r); -#endif -void play_note(float freq, int vol); -void stop_note(float freq); -void stop_all_notes(void); -void play_notes(float (*np)[][2], uint16_t n_count, bool n_repeat); +// hardware interface -#define SCALE \ - (int8_t[]) { 0 + (12 * 0), 2 + (12 * 0), 4 + (12 * 0), 5 + (12 * 0), 7 + (12 * 0), 9 + (12 * 0), 11 + (12 * 0), 0 + (12 * 1), 2 + (12 * 1), 4 + (12 * 1), 5 + (12 * 1), 7 + (12 * 1), 9 + (12 * 1), 11 + (12 * 1), 0 + (12 * 2), 2 + (12 * 2), 4 + (12 * 2), 5 + (12 * 2), 7 + (12 * 2), 9 + (12 * 2), 11 + (12 * 2), 0 + (12 * 3), 2 + (12 * 3), 4 + (12 * 3), 5 + (12 * 3), 7 + (12 * 3), 9 + (12 * 3), 11 + (12 * 3), 0 + (12 * 4), 2 + (12 * 4), 4 + (12 * 4), 5 + (12 * 4), 7 + (12 * 4), 9 + (12 * 4), 11 + (12 * 4), } +// implementation in the driver_avr/arm_* respective parts +void audio_driver_initialize(void); +void audio_driver_start(void); +void audio_driver_stop(void); -// These macros are used to allow play_notes to play an array of indeterminate -// length. This works around the limitation of C's sizeof operation on pointers. -// The global float array for the song must be used here. -#define NOTE_ARRAY_SIZE(x) ((int16_t)(sizeof(x) / (sizeof(x[0])))) -#define PLAY_SONG(note_array) play_notes(¬e_array, NOTE_ARRAY_SIZE((note_array)), false) -#define PLAY_LOOP(note_array) play_notes(¬e_array, NOTE_ARRAY_SIZE((note_array)), true) +/** + * @brief get the number of currently active tones + * @return number, 0=none active + */ +uint8_t audio_get_number_of_active_tones(void); + +/** + * @brief access to the raw/unprocessed frequency for a specific tone + * @details each active tone has a frequency associated with it, which + * the internal state keeps track of, and is usually influenced + * by various effects + * @param[in] tone_index, ranging from 0 to number_of_active_tones-1, with the + * first being the most recent and each increment yielding the next + * older one + * @return a positive frequency, in Hz; or zero if the tone is a pause + */ +float audio_get_frequency(uint8_t tone_index); + +/** + * @brief calculate and return the frequency for the requested tone + * @details effects like glissando, vibrato, ... are post-processed onto the + * each active tones 'base'-frequency; this function returns the + * post-processed result. + * @param[in] tone_index, ranging from 0 to number_of_active_tones-1, with the + * first being the most recent and each increment yielding the next + * older one + * @return a positive frequency, in Hz; or zero if the tone is a pause + */ +float audio_get_processed_frequency(uint8_t tone_index); + +/** + * @brief update audio internal state: currently playing and active tones,... + * @details This function is intended to be called by the audio-hardware + * specific implementation on a somewhat regular basis while a SONG + * or notes (pitch+duration) are playing to 'advance' the internal + * state (current playing notes, position in the melody, ...) + * + * @return true if something changed in the currently active tones, which the + * hardware might need to react to + */ +bool audio_update_state(void); + +// legacy and back-warts compatibility stuff + +#define is_audio_on() audio_is_on() +#define is_playing_notes() audio_is_playing_melody() +#define is_playing_note() audio_is_playing_note() +#define stop_all_notes() audio_stop_all() +#define stop_note(f) audio_stop_tone(f) +#define play_note(f, v) audio_play_tone(f) -bool is_playing_notes(void); +#define set_timbre(t) voice_set_timbre(t) +#define set_tempo(t) audio_set_tempo(t) +#define increase_tempo(t) audio_increase_tempo(t) +#define decrease_tempo(t) audio_decrease_tempo(t) +// vibrato functions are not used in any keyboards diff --git a/quantum/audio/audio_avr.c b/quantum/audio/audio_avr.c deleted file mode 100644 index 1bac43bb43..0000000000 --- a/quantum/audio/audio_avr.c +++ /dev/null @@ -1,812 +0,0 @@ -/* Copyright 2016 Jack Humbert - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -#include -#include -//#include -#if defined(__AVR__) -# include -# include -# include -#endif -#include "print.h" -#include "audio.h" -#include "keymap.h" -#include "wait.h" - -#include "eeconfig.h" - -#define CPU_PRESCALER 8 - -// ----------------------------------------------------------------------------- -// Timer Abstractions -// ----------------------------------------------------------------------------- - -// Currently we support timers 1 and 3 used at the sime time, channels A-C, -// pins PB5, PB6, PB7, PC4, PC5, and PC6 -#if defined(C6_AUDIO) -# define CPIN_AUDIO -# define CPIN_SET_DIRECTION DDRC |= _BV(PORTC6); -# define INIT_AUDIO_COUNTER_3 TCCR3A = (0 << COM3A1) | (0 << COM3A0) | (1 << WGM31) | (0 << WGM30); -# define ENABLE_AUDIO_COUNTER_3_ISR TIMSK3 |= _BV(OCIE3A) -# define DISABLE_AUDIO_COUNTER_3_ISR TIMSK3 &= ~_BV(OCIE3A) -# define ENABLE_AUDIO_COUNTER_3_OUTPUT TCCR3A |= _BV(COM3A1); -# define DISABLE_AUDIO_COUNTER_3_OUTPUT TCCR3A &= ~(_BV(COM3A1) | _BV(COM3A0)); -# define TIMER_3_PERIOD ICR3 -# define TIMER_3_DUTY_CYCLE OCR3A -# define TIMER3_AUDIO_vect TIMER3_COMPA_vect -#endif -#if defined(C5_AUDIO) -# define CPIN_AUDIO -# define CPIN_SET_DIRECTION DDRC |= _BV(PORTC5); -# define INIT_AUDIO_COUNTER_3 TCCR3A = (0 << COM3B1) | (0 << COM3B0) | (1 << WGM31) | (0 << WGM30); -# define ENABLE_AUDIO_COUNTER_3_ISR TIMSK3 |= _BV(OCIE3B) -# define DISABLE_AUDIO_COUNTER_3_ISR TIMSK3 &= ~_BV(OCIE3B) -# define ENABLE_AUDIO_COUNTER_3_OUTPUT TCCR3A |= _BV(COM3B1); -# define DISABLE_AUDIO_COUNTER_3_OUTPUT TCCR3A &= ~(_BV(COM3B1) | _BV(COM3B0)); -# define TIMER_3_PERIOD ICR3 -# define TIMER_3_DUTY_CYCLE OCR3B -# define TIMER3_AUDIO_vect TIMER3_COMPB_vect -#endif -#if defined(C4_AUDIO) -# define CPIN_AUDIO -# define CPIN_SET_DIRECTION DDRC |= _BV(PORTC4); -# define INIT_AUDIO_COUNTER_3 TCCR3A = (0 << COM3C1) | (0 << COM3C0) | (1 << WGM31) | (0 << WGM30); -# define ENABLE_AUDIO_COUNTER_3_ISR TIMSK3 |= _BV(OCIE3C) -# define DISABLE_AUDIO_COUNTER_3_ISR TIMSK3 &= ~_BV(OCIE3C) -# define ENABLE_AUDIO_COUNTER_3_OUTPUT TCCR3A |= _BV(COM3C1); -# define DISABLE_AUDIO_COUNTER_3_OUTPUT TCCR3A &= ~(_BV(COM3C1) | _BV(COM3C0)); -# define TIMER_3_PERIOD ICR3 -# define TIMER_3_DUTY_CYCLE OCR3C -# define TIMER3_AUDIO_vect TIMER3_COMPC_vect -#endif - -#if defined(B5_AUDIO) -# define BPIN_AUDIO -# define BPIN_SET_DIRECTION DDRB |= _BV(PORTB5); -# define INIT_AUDIO_COUNTER_1 TCCR1A = (0 << COM1A1) | (0 << COM1A0) | (1 << WGM11) | (0 << WGM10); -# define ENABLE_AUDIO_COUNTER_1_ISR TIMSK1 |= _BV(OCIE1A) -# define DISABLE_AUDIO_COUNTER_1_ISR TIMSK1 &= ~_BV(OCIE1A) -# define ENABLE_AUDIO_COUNTER_1_OUTPUT TCCR1A |= _BV(COM1A1); -# define DISABLE_AUDIO_COUNTER_1_OUTPUT TCCR1A &= ~(_BV(COM1A1) | _BV(COM1A0)); -# define TIMER_1_PERIOD ICR1 -# define TIMER_1_DUTY_CYCLE OCR1A -# define TIMER1_AUDIO_vect TIMER1_COMPA_vect -#endif -#if defined(B6_AUDIO) -# define BPIN_AUDIO -# define BPIN_SET_DIRECTION DDRB |= _BV(PORTB6); -# define INIT_AUDIO_COUNTER_1 TCCR1A = (0 << COM1B1) | (0 << COM1B0) | (1 << WGM11) | (0 << WGM10); -# define ENABLE_AUDIO_COUNTER_1_ISR TIMSK1 |= _BV(OCIE1B) -# define DISABLE_AUDIO_COUNTER_1_ISR TIMSK1 &= ~_BV(OCIE1B) -# define ENABLE_AUDIO_COUNTER_1_OUTPUT TCCR1A |= _BV(COM1B1); -# define DISABLE_AUDIO_COUNTER_1_OUTPUT TCCR1A &= ~(_BV(COM1B1) | _BV(COM1B0)); -# define TIMER_1_PERIOD ICR1 -# define TIMER_1_DUTY_CYCLE OCR1B -# define TIMER1_AUDIO_vect TIMER1_COMPB_vect -#endif -#if defined(B7_AUDIO) -# define BPIN_AUDIO -# define BPIN_SET_DIRECTION DDRB |= _BV(PORTB7); -# define INIT_AUDIO_COUNTER_1 TCCR1A = (0 << COM1C1) | (0 << COM1C0) | (1 << WGM11) | (0 << WGM10); -# define ENABLE_AUDIO_COUNTER_1_ISR TIMSK1 |= _BV(OCIE1C) -# define DISABLE_AUDIO_COUNTER_1_ISR TIMSK1 &= ~_BV(OCIE1C) -# define ENABLE_AUDIO_COUNTER_1_OUTPUT TCCR1A |= _BV(COM1C1); -# define DISABLE_AUDIO_COUNTER_1_OUTPUT TCCR1A &= ~(_BV(COM1C1) | _BV(COM1C0)); -# define TIMER_1_PERIOD ICR1 -# define TIMER_1_DUTY_CYCLE OCR1C -# define TIMER1_AUDIO_vect TIMER1_COMPC_vect -#endif - -#if !defined(BPIN_AUDIO) && !defined(CPIN_AUDIO) -# error "Audio feature enabled, but no suitable pin selected - see docs/feature_audio.md under the AVR settings for available options." -#endif - -// ----------------------------------------------------------------------------- - -int voices = 0; -int voice_place = 0; -float frequency = 0; -float frequency_alt = 0; -int volume = 0; -long position = 0; - -float frequencies[8] = {0, 0, 0, 0, 0, 0, 0, 0}; -int volumes[8] = {0, 0, 0, 0, 0, 0, 0, 0}; -bool sliding = false; - -float place = 0; - -uint8_t* sample; -uint16_t sample_length = 0; - -bool playing_notes = false; -bool playing_note = false; -float note_frequency = 0; -float note_length = 0; -uint8_t note_tempo = TEMPO_DEFAULT; -float note_timbre = TIMBRE_DEFAULT; -uint16_t note_position = 0; -float (*notes_pointer)[][2]; -uint16_t notes_count; -bool notes_repeat; -bool note_resting = false; - -uint16_t current_note = 0; -uint8_t rest_counter = 0; - -#ifdef VIBRATO_ENABLE -float vibrato_counter = 0; -float vibrato_strength = .5; -float vibrato_rate = 0.125; -#endif - -float polyphony_rate = 0; - -static bool audio_initialized = false; - -audio_config_t audio_config; - -uint16_t envelope_index = 0; -bool glissando = true; - -#ifndef STARTUP_SONG -# define STARTUP_SONG SONG(STARTUP_SOUND) -#endif -#ifndef AUDIO_ON_SONG -# define AUDIO_ON_SONG SONG(AUDIO_ON_SOUND) -#endif -#ifndef AUDIO_OFF_SONG -# define AUDIO_OFF_SONG SONG(AUDIO_OFF_SOUND) -#endif -float startup_song[][2] = STARTUP_SONG; -float audio_on_song[][2] = AUDIO_ON_SONG; -float audio_off_song[][2] = AUDIO_OFF_SONG; - -void audio_init() { - // Check EEPROM - if (!eeconfig_is_enabled()) { - eeconfig_init(); - } - audio_config.raw = eeconfig_read_audio(); - - if (!audio_initialized) { -// Set audio ports as output -#ifdef CPIN_AUDIO - CPIN_SET_DIRECTION - DISABLE_AUDIO_COUNTER_3_ISR; -#endif -#ifdef BPIN_AUDIO - BPIN_SET_DIRECTION - DISABLE_AUDIO_COUNTER_1_ISR; -#endif - -// TCCR3A / TCCR3B: Timer/Counter #3 Control Registers TCCR3A/TCCR3B, TCCR1A/TCCR1B -// Compare Output Mode (COM3An and COM1An) = 0b00 = Normal port operation -// OC3A -- PC6 -// OC3B -- PC5 -// OC3C -- PC4 -// OC1A -- PB5 -// OC1B -- PB6 -// OC1C -- PB7 - -// Waveform Generation Mode (WGM3n) = 0b1110 = Fast PWM Mode 14. Period = ICR3, Duty Cycle OCR3A) -// OCR3A - PC6 -// OCR3B - PC5 -// OCR3C - PC4 -// OCR1A - PB5 -// OCR1B - PB6 -// OCR1C - PB7 - -// Clock Select (CS3n) = 0b010 = Clock / 8 -#ifdef CPIN_AUDIO - INIT_AUDIO_COUNTER_3 - TCCR3B = (1 << WGM33) | (1 << WGM32) | (0 << CS32) | (1 << CS31) | (0 << CS30); - TIMER_3_PERIOD = (uint16_t)(((float)F_CPU) / (440 * CPU_PRESCALER)); - TIMER_3_DUTY_CYCLE = (uint16_t)((((float)F_CPU) / (440 * CPU_PRESCALER)) * note_timbre); -#endif -#ifdef BPIN_AUDIO - INIT_AUDIO_COUNTER_1 - TCCR1B = (1 << WGM13) | (1 << WGM12) | (0 << CS12) | (1 << CS11) | (0 << CS10);