CHGame 0.4.1
Libraries for the CHGame handheld
Loading...
Searching...
No Matches
Audio.h
Go to the documentation of this file.
1/// @file Audio.h
2/// @brief Sound and the status LED: a small sequencer for the board's
3/// buzzer (a piezo on CHGame Rev0, a magnetic buzzer switched by a MOSFET
4/// on Rev1).
5///
6/// One pin plays one note at a time, driven by TIM1 channel 2 on PB10 (on
7/// CHGame Rev1: TIM2 channel 2 on PA1, a magnetic buzzer) and stepped by the
8/// core's 1 kHz SysTick hook, so no other timer is used. It plays two kinds
9/// of thing at once:
10///
11/// - **effects**: short step lists (a pitch, the pitch it sweeps to, a
12/// length), each with a priority: a new effect is refused while one of
13/// higher priority sounds, and cuts off any other;
14/// - **music**, under the effects: a Playtune score (several voices;
15/// tools/make_music.py writes them), rendered as a lead line or an
16/// arpeggio, or a melody (one line of notes, easy to write by hand).
17///
18/// The simulator is silent: the same interface with no hardware, which
19/// remembers the last effect asked for (audio::simLast) for scripts and
20/// tests. The game's tools/audio preview renders the real thing to WAV.
21#pragma once
22#include <stdint.h>
23
24/// @defgroup chgame_audio Sound and LED
25/// @ingroup lib_chgame
26/// @brief audio::: sound effects, music and the status LED.
27///
28/// A game lists its effects once, in the order of its own enum:
29/// @code
30/// enum class Sfx : uint8_t { Cursor, Win, COUNT };
31/// AUDIO_STEPS(CURSOR) = { AUDIO_STEP(2100, 0, 10) };
32/// AUDIO_STEPS(WIN) = { AUDIO_STEP(2093, 0, 60), AUDIO_STEP(4186, 0, 170) };
33/// const audio::Effect SOUNDS[] = { AUDIO_EFFECT(CURSOR, 0), AUDIO_EFFECT(WIN, 3) };
34///
35/// audio::begin(SOUNDS, (uint8_t)Sfx::COUNT); // in setup()
36/// audio::sfx(Sfx::Win); // any time
37/// audio::update(); // once per logic tick (the LED)
38/// @endcode
39/// @{
40
41/// @brief Sound effects, music and the status LED.
42namespace audio {
43
44/// @brief An effect step in three bytes. Write them with AUDIO_STEP() and AUDIO_REST().
45/// @details 20 Hz is under half a percent of a piezo's 1-4 kHz: no ear hears
46/// it, and the tables are half the size. A step lasts at most 510 ms.
47struct Step {
48 uint8_t hz, ///< The pitch in 20 Hz units; 0 = a rest.
49 endHz, ///< The pitch it sweeps to, in 20 Hz units; 0 = none (holds hz).
50 ms; ///< The length in 2 ms units.
51};
52/// @brief An effect step: a pitch, the pitch it sweeps to, a length.
53/// @param hz Start pitch in Hz (rounded to 20 Hz).
54/// @param end The pitch to sweep to in Hz, or 0 to hold hz.
55/// @param ms Length in milliseconds (rounded to 2 ms; at most 510).
56#define AUDIO_STEP(hz, end, ms) \
57 { (uint8_t)(((hz) + 10) / 20), (uint8_t)(((end) + 10) / 20), (uint8_t)(((ms) + 1) / 2) }
58/// @brief A silent effect step.
59/// @param ms Length in milliseconds (rounded to 2 ms; at most 510).
60#define AUDIO_REST(ms) { 0, 0, (uint8_t)(((ms) + 1) / 2) }
61/// @brief Declare an effect's step table, kept in flash.
62/// @param name The table's name, for AUDIO_EFFECT().
63/// @details Use it as `AUDIO_STEPS(WIN) = { AUDIO_STEP(...), ... };`. (A plain
64/// `static const` table of 8 bytes or less is "small data" to the compiler,
65/// and this core's link script copies small data into SRAM.)
66#if defined(__riscv) && !defined(CHSIM)
67#define AUDIO_STEPS(name) static const audio::Step name[] __attribute__((section(".rodata.audio." #name)))
68#else
69#define AUDIO_STEPS(name) static const audio::Step name[]
70#endif
71
72/// @brief Flags ORed into an effect's priority (0-15).
73enum : uint8_t {
74 SOFT = 0x10, ///< A narrow pulse: quieter than everything else (clocks, ticks).
75 GLIDE = 0x20, ///< Sweeps change pitch at a cycle's end instead of restarting it.
76};
77/// @brief An effect: its steps, and its priority with flags. Write them with AUDIO_EFFECT().
78struct Effect {
79 const Step *steps; ///< The step table (AUDIO_STEPS()).
80 uint8_t n, ///< Number of steps.
81 flags; ///< Priority 0-15, ORed with SOFT and GLIDE.
82};
83/// @brief An entry of the effects table.
84/// @param steps A table declared with AUDIO_STEPS().
85/// @param flags The priority (0-15), ORed with SOFT and GLIDE if wanted.
86#define AUDIO_EFFECT(steps, flags) { steps, (uint8_t)(sizeof(steps) / sizeof((steps)[0])), (uint8_t)(flags) }
87
88/// @brief Set up the speaker, the LED pin and the timer, with the game's effects.
89/// @param effects The effects table, in the order of the game's enum (kept by pointer).
90/// @param count The number of effects.
91/// @param on Whether sound starts on (a saved option, for instance).
92void begin(const Effect *effects, uint8_t count, bool on = true);
93/// @brief Turn sound on or off.
94/// @param on false: silent, effects refused, music stopped in place (it
95/// carries on from there when sound comes back).
96void setOn(bool on); // off: silent, effects refused, music stopped in place
97/// @brief Whether sound is on.
98/// @return true after begin() with sound on, until setOn(false).
99bool on();
100
101/// @brief Play an effect.
102/// @param id An index into the effects table, or the game's enum.
103/// @details Refused while an effect of higher priority sounds; cuts off any
104/// other effect.
105void sfx(uint8_t id);
106/// @brief Play an effect raised in pitch: a combo that climbs.
107/// @param id An index into the effects table.
108/// @param semitones How far to raise the whole effect, 0-12.
109void sfx(uint8_t id, uint8_t semitones);
110/// @brief Play an effect named by the game's enum.
111/// @param e The enum value (its index into the effects table).
112template <class E> inline void sfx(E e) { sfx((uint8_t)e); }
113/// @brief Play an effect named by the game's enum, raised in pitch.
114/// @param e The enum value.
115/// @param semitones How far to raise it, 0-12.
116template <class E> inline void sfx(E e, uint8_t semitones) { sfx((uint8_t)e, semitones); }
117/// @brief One note made up on the spot (a typewriter, a click, a counter rolling).
118/// @details It cuts off effects of priority 0 and 1, is refused over anything
119/// higher, and is itself priority 0. To never play over any effect:
120/// `if (!audio::playing()) audio::blip(...)`.
121/// @param hz Pitch in Hz.
122/// @param ms Length in milliseconds.
123/// @param soft true for the quieter narrow pulse (as SOFT).
124void blip(uint16_t hz, uint16_t ms, bool soft = false);
125/// @brief One note at a priority, like an effect.
126/// @param hz Pitch in Hz.
127/// @param ms Length in milliseconds.
128/// @param priority 0-15, as an effect's.
129void note(uint16_t hz, uint16_t ms, uint8_t priority);
130/// @brief Whether an effect is sounding.
131/// @return true while an effect, blip() or note() plays.
132bool playing(); // an effect is sounding
133
134/// @brief How music is rendered on the one pin.
135/// @details The music code is linked in only by a game that calls music() or melody().
136enum MusicMode : uint8_t {
137 MUSIC_OFF, ///< No music (held where it is).
138 ARPEGGIO, ///< A score's sounding voices take 6 ms turns (the default).
139 LEAD ///< The melody (channel 0) plays; the others fill only its real rests.
141/// @brief Choose how music is rendered.
142/// @param mode A MusicMode; MUSIC_OFF holds the tune where it is.
143void setMusic(uint8_t mode); // default ARPEGGIO; MUSIC_OFF holds the tune where it is
144/// @brief Play a Playtune score under the effects.
145/// @param score The score (from tools/make_music.py), or nullptr to stop.
146/// @param loop true (default): start again at the end.
147void music(const uint8_t *score, bool loop = true); // nullptr: stop
148
149/// @brief A melody: one line of notes, easy to write by hand.
150/// @details (MIDI note, length) pairs: note 0 is a rest, a length counts
151/// units of unitMs, and each note is let go gapMs early so repeated notes
152/// stay apart. Middle C is 60; the piezo sings best from C6 (84) to C8 (108).
153/// @code
154/// static const uint8_t TUNE[] = { 84,2, 88,2, 91,4, 0,2 };
155/// static const audio::Melody TITLE = { TUNE, sizeof TUNE / 2, 105, 14 };
156/// audio::melody(TITLE);
157/// @endcode
158struct Melody {
159 const uint8_t *notes; ///< (MIDI note, length) pairs.
160 uint8_t count, ///< Number of pairs.
161 unitMs, ///< Milliseconds per length unit.
162 gapMs; ///< Silence at the end of each note, in milliseconds.
163};
164/// @brief Play a melody under the effects (it replaces any score).
165/// @param m The melody (kept by reference: it must stay valid).
166/// @param loop true (default): start again at the end.
167void melody(const Melody &m, bool loop = true); // replaces any score
168/// @brief Stop the music.
170/// @brief Whether the music repeats.
171/// @param on false: the score stops at its end instead of repeating.
172void loopMusic(bool on); // off: the score stops at its end instead of repeating
173/// @brief Whether music is playing.
174/// @return true while a score or melody plays; false once it has ended, and
175/// while sound or music is off.
176bool musicPlaying(); // false while sound or music is off
177
178/// @brief Run the LED patterns: once per logic tick.
179void update(); // once per logic tick: the LED patterns
180
181/// @brief Status LED (PB9; PB10 on CHGame Rev1) patterns, for wins. Timed in update() ticks.
182enum Led : uint8_t {
183 LED_OFF, ///< Off.
184 LED_BLINK, ///< One blink (12 ticks).
185 LED_TRIPLE, ///< Three blinks.
186 LED_PARTY ///< Fast blinking for about 4 seconds at 60 fps.
188/// @brief Start an LED pattern (replacing the one running).
189/// @param pattern The pattern.
190void led(Led pattern);
191
192#ifdef CHSIM
193extern uint8_t simLast; // the last effect played (0xFF: none yet)
194#endif
195
196} // namespace audio
197
198/// @}
Sound effects, music and the status LED.
Definition Audio.h:42
Led
Status LED (PB9; PB10 on CHGame Rev1) patterns, for wins. Timed in update() ticks.
Definition Audio.h:182
@ LED_PARTY
Fast blinking for about 4 seconds at 60 fps.
Definition Audio.h:186
@ LED_OFF
Off.
Definition Audio.h:183
@ LED_BLINK
One blink (12 ticks).
Definition Audio.h:184
@ LED_TRIPLE
Three blinks.
Definition Audio.h:185
bool on()
Whether sound is on.
@ SOFT
A narrow pulse: quieter than everything else (clocks, ticks).
Definition Audio.h:74
@ GLIDE
Sweeps change pitch at a cycle's end instead of restarting it.
Definition Audio.h:75
void blip(uint16_t hz, uint16_t ms, bool soft=false)
One note made up on the spot (a typewriter, a click, a counter rolling).
void loopMusic(bool on)
Whether the music repeats.
void melody(const Melody &m, bool loop=true)
Play a melody under the effects (it replaces any score).
void setMusic(uint8_t mode)
Choose how music is rendered.
MusicMode
How music is rendered on the one pin.
Definition Audio.h:136
@ MUSIC_OFF
No music (held where it is).
Definition Audio.h:137
@ LEAD
The melody (channel 0) plays; the others fill only its real rests.
Definition Audio.h:139
@ ARPEGGIO
A score's sounding voices take 6 ms turns (the default).
Definition Audio.h:138
void setOn(bool on)
Turn sound on or off.
void update()
Run the LED patterns: once per logic tick.
void music(const uint8_t *score, bool loop=true)
Play a Playtune score under the effects.
bool playing()
Whether an effect is sounding.
bool musicPlaying()
Whether music is playing.
void note(uint16_t hz, uint16_t ms, uint8_t priority)
One note at a priority, like an effect.
void stopMusic()
Stop the music.
void led(Led pattern)
Start an LED pattern (replacing the one running).
void sfx(uint8_t id)
Play an effect.
void begin(const Effect *effects, uint8_t count, bool on=true)
Set up the speaker, the LED pin and the timer, with the game's effects.
An effect: its steps, and its priority with flags. Write them with AUDIO_EFFECT().
Definition Audio.h:78
uint8_t n
Number of steps.
Definition Audio.h:80
const Step * steps
The step table (AUDIO_STEPS()).
Definition Audio.h:79
uint8_t flags
Priority 0-15, ORed with SOFT and GLIDE.
Definition Audio.h:81
A melody: one line of notes, easy to write by hand.
Definition Audio.h:158
uint8_t gapMs
Silence at the end of each note, in milliseconds.
Definition Audio.h:162
const uint8_t * notes
(MIDI note, length) pairs.
Definition Audio.h:159
uint8_t count
Number of pairs.
Definition Audio.h:160
uint8_t unitMs
Milliseconds per length unit.
Definition Audio.h:161
An effect step in three bytes.
Definition Audio.h:47
uint8_t ms
The length in 2 ms units.
Definition Audio.h:50
uint8_t endHz
The pitch it sweeps to, in 20 Hz units; 0 = none (holds hz).
Definition Audio.h:49
uint8_t hz
The pitch in 20 Hz units; 0 = a rest.
Definition Audio.h:48