13static constexpr uint8_t SONG_NAME_LENGTH_LIMIT = 64;
14static constexpr uint8_t SEMITONES_IN_OCTAVE = 12;
16static constexpr uint8_t MIN_OCTAVE = 4;
17static constexpr uint8_t MAX_OCTAVE = 7;
19static constexpr uint8_t DEFAULT_BPM = 63;
22static constexpr uint16_t NOTES[] PROGMEM = {
23 0, 262, 277, 294, 311, 330, 349, 370, 392, 415, 440, 466, 494, 523, 554, 587, 622,
24 659, 698, 740, 784, 831, 880, 932, 988, 1047, 1109, 1175, 1245, 1319, 1397, 1480, 1568, 1661,
25 1760, 1865, 1976, 2093, 2217, 2349, 2489, 2637, 2794, 2960, 3136, 3322, 3520, 3729, 3951};
26static constexpr uint8_t NOTES_COUNT =
static_cast<uint8_t
>(
sizeof(NOTES) /
sizeof(NOTES[0]));
28static constexpr uint8_t REPEATING_NOTE_GAP_MS = 10;
31static constexpr uint8_t NOTE_FADE_BITS = 5;
34static constexpr uint8_t QUARTER_SINE_BITS = 6;
35static constexpr uint16_t QUARTER_SINE[(1 << QUARTER_SINE_BITS) + 1] PROGMEM = {
36 0, 804, 1608, 2410, 3212, 4011, 4808, 5602, 6393, 7179, 7962, 8739, 9512,
37 10278, 11039, 11793, 12539, 13279, 14010, 14732, 15446, 16151, 16846, 17530, 18204, 18868,
38 19519, 20159, 20787, 21403, 22005, 22594, 23170, 23731, 24279, 24811, 25329, 25832, 26319,
39 26790, 27245, 27683, 28105, 28510, 28898, 29268, 29621, 29956, 30273, 30571, 30852, 31113,
40 31356, 31580, 31785, 31971, 32137, 32285, 32412, 32521, 32609, 32678, 32728, 32757, 32767};
43static constexpr uint16_t SAMPLE_BUFFER_SIZE = 2048;
44static constexpr uint16_t SAMPLE_RATE = 16000;
47#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERBOSE
49PROGMEM_STRING_TABLE(RtttlStateStrings,
"State::STOPPED",
"State::INIT",
"State::STARTING",
"State::RUNNING",
50 "State::STOPPING",
"UNKNOWN");
52static const LogString *state_to_string(
State state) {
53 return RtttlStateStrings::get_log_str(
static_cast<uint8_t
>(
state), RtttlStateStrings::LAST_INDEX);
57static uint8_t note_index_from_char(
char note) {
130 int16_t sample[SAMPLE_BUFFER_SIZE];
131 uint16_t sample_index = 0;
137 sample[sample_index] =
141 sample[sample_index] = 0;
146 if (sample_index > 0) {
147 size_t bytes = sample_index *
sizeof(int16_t);
148 size_t sent_bytes = this->
speaker_->
play((uint8_t *) (&sample), bytes);
149 size_t samples_sent = sent_bytes /
sizeof(int16_t);
150 if (samples_sent != sample_index) {
162 if (c !=
',' && c !=
' ')
167 if (this->
position_ >= this->song_len_) {
175 if (note_denominator) {
182 uint8_t note_index_in_octave = note_index_from_char(this->
song_at_(this->
position_));
188 note_index_in_octave++;
198 if (scale < MIN_OCTAVE || scale > MAX_OCTAVE) {
199 ESP_LOGE(TAG,
"Octave must be between %d and %d (it is %d)", MIN_OCTAVE, MAX_OCTAVE, scale);
206 this->note_duration_ += this->note_duration_ / 2;
210 bool need_note_gap =
false;
213 if (note_index_in_octave == 0) {
215 ESP_LOGVV(TAG,
"Waiting: %dms", this->note_duration_);
217 uint8_t note_index = (scale - MIN_OCTAVE) * SEMITONES_IN_OCTAVE + note_index_in_octave;
218 if (note_index >= NOTES_COUNT) {
219 ESP_LOGE(TAG,
"Note out of range (note: %d, scale: %d, index: %d, max: %d)", note_index_in_octave, scale,
220 note_index, NOTES_COUNT);
230 ESP_LOGVV(TAG,
"Playing note: %d for %dms", note_index_in_octave, this->note_duration_);
234 if (this->
output_ !=
nullptr) {
238 if (need_note_gap && this->note_duration_ > REPEATING_NOTE_GAP_MS) {
240 delay(REPEATING_NOTE_GAP_MS);
241 this->note_duration_ -= REPEATING_NOTE_GAP_MS;
256 this->
samples_gap_ = (SAMPLE_RATE * REPEATING_NOTE_GAP_MS) / 1000;
263 uint16_t division = ((this->
samples_count_ << 10) / samples_per_wave) + 1;
267 ESP_LOGVV(TAG,
"Calc play time: wish: %" PRIu32
" gets: %" PRIu32
" (div: %d spw: %" PRIu32
")", samples_wish,
278 static constexpr uint8_t QUARTER_BITS = 30;
279 static constexpr uint32_t QUARTER_MASK = (1UL << QUARTER_BITS) - 1;
281 const uint32_t position = ((phase >> QUARTER_BITS) & 1) != 0 ? ~phase & QUARTER_MASK : phase & QUARTER_MASK;
282 const uint8_t index =
position >> (QUARTER_BITS - QUARTER_SINE_BITS);
283 const int32_t fraction = (
position >> (QUARTER_BITS - QUARTER_SINE_BITS - 16)) & 0xFFFF;
286 const int32_t
value = low + (((high - low) * fraction) >> 16);
287 return static_cast<int16_t
>((phase >> 31) != 0 ? -
value :
value);
291 const uint32_t edge = std::min(from_start, to_end);
292 if (edge >= (1U << NOTE_FADE_BITS))
294 return static_cast<int16_t
>((
value *
static_cast<int32_t
>(edge)) >> NOTE_FADE_BITS);
312 const char *data =
reinterpret_cast<const char *
>(song.
rtttl);
313 this->
set_song_(data, ESPHOME_strlen_P(data));
320 this->
song_len_ =
static_cast<uint16_t
>(std::min<size_t>(
len, std::numeric_limits<uint16_t>::max()));
327 char name[SONG_NAME_LENGTH_LIMIT + 1];
329 ESP_LOGW(TAG,
"Already playing: %s", name);
352 size_t len = std::min(name_len,
size - 1);
364 uint16_t bpm = DEFAULT_BPM;
371 ESP_LOGE(TAG,
"Unable to determine name; missing ':'");
374 if (this->
position_ >= SONG_NAME_LENGTH_LIMIT) {
375 ESP_LOGE(TAG,
"Name is too long: length=%u, limit=%u",
static_cast<unsigned>(this->
position_),
376 static_cast<unsigned>(SONG_NAME_LENGTH_LIMIT));
379 char name[SONG_NAME_LENGTH_LIMIT + 1];
381 ESP_LOGD(TAG,
"Playing song %s", name);
383 size_t name_end_position = this->
position_;
386 ESP_LOGE(TAG,
"Missing second ':'");
392 if (
pos == control_end) {
397 if (num == 1 || num == 2 || num == 4 || num == 8 || num == 16 || num == 32) {
400 ESP_LOGE(TAG,
"Invalid default duration: %d", num);
407 if (
pos == control_end) {
408 ESP_LOGW(TAG,
"Missing 'o='; use default octave %d", this->
default_octave_);
412 if (num >= MIN_OCTAVE && num <= MAX_OCTAVE) {
415 ESP_LOGE(TAG,
"Invalid default octave: %d", num);
422 if (
pos == control_end) {
423 ESP_LOGW(TAG,
"Missing 'b='; use default BPM %d", bpm);
430 ESP_LOGE(TAG,
"Invalid BPM: %d", num);
445 if (this->
output_ !=
nullptr) {
461 if (this->
output_ !=
nullptr) {
481 ESP_LOGV(TAG,
"Rtttl::finish_()");
484 if (this->
output_ !=
nullptr) {
492 int16_t sample[2] = {0, 0};
493 this->
speaker_->
play((uint8_t *) (&sample),
sizeof(sample));
507 ESP_LOGV(TAG,
"State changed from %s to %s", LOG_STR_ARG(state_to_string(old_state)),
508 LOG_STR_ARG(state_to_string(
state)));
513#ifdef USE_RTTTL_FINISHED_PLAYBACK_CALLBACK
516 ESP_LOGD(TAG,
"Playback finished");
void enable_loop()
Enable this component's loop.
void disable_loop()
Disable this component's loop.
void set_level(float state)
Set the level of this float output, this is called from the front-end.
virtual void update_frequency(float frequency)
Set the frequency of the output for PWM outputs.
std::string owned_song_
Backing store for play(std::string).
size_t song_find_(char c, size_t from, size_t end) const
Index of the first c in [from, end), or end when absent.
uint32_t last_note_start_time_
The time in milliseconds since microcontroller boot when the last note was started.
uint32_t phase_step_
How far the phase moves per sample, where the full uint32_t range is one cycle; 0 for a rest.
uint8_t default_note_denominator_
The default duration of a note (e.g. 4 for a quarter note).
uint16_t position_
The current position in the song.
bool is_busy_() const
Logs and returns true when a song is still playing, so a new one must wait.
uint16_t note_duration_
The duration of the current note in milliseconds.
uint16_t song_len_
Length of the song in bytes; songs are a few hundred bytes, so 16 bits is ample.
void start_()
Parses the header and starts playback of the song the view points at.
uint32_t samples_sent_
The number of samples sent.
output::FloatOutput * output_
The output to write the sound to.
static int16_t sine_sample(uint32_t phase)
The value of a full scale sine wave at phase, where the full uint32_t range is one cycle.
void dump_config() override
void set_state_(State state)
void finish_()
Finalizes the playback of the RTTTL string.
static int16_t fade_sample(int16_t value, uint32_t from_start, uint32_t to_end)
Scales a sample near either end of a note, so the note does not click when the wave starts or stops a...
float gain_
The gain of the output.
uint8_t default_octave_
The default octave for a note.
uint32_t output_freq_
The frequency of the current note in Hz.
uint32_t samples_gap_
The number of samples for the gap between notes.
char song_at_(size_t pos) const
The byte of the song at pos, or NUL past its end; the read is flash safe for a PROGMEM song on ESP826...
uint32_t samples_count_
The total number of samples to send.
uint16_t wholenote_duration_
The duration of a whole note in milliseconds.
const char * song_
The song being played; points at owned_song_ or at static storage.
size_t song_find_control_(char key, size_t from, size_t end) const
Index of key followed by '=' in [from, end), or end when absent.
void song_name_(char *buf, size_t size, size_t name_len) const
Copies the first name_len bytes of the song, its name, into buf for logging.
State state_
The current state of the RTTTL player.
speaker::Speaker * speaker_
The speaker to write the sound to.
CallbackManager< void()> on_finished_playback_callback_
The callback to call when playback is finished.
void set_song_(const char *song, size_t len)
Points the view at a song, clamped to what song_len_ can hold.
void play(std::string rtttl)
Play a song; the string is copied so it may come from anywhere.
virtual size_t play(const uint8_t *data, size_t length)=0
Plays the provided audio data.
virtual void set_volume(float volume)
void set_audio_stream_info(const audio::AudioStreamInfo &audio_stream_info)
constexpr uint8_t DEFAULT_OCTAVE
constexpr uint8_t DEFAULT_NOTE_DENOMINATOR
ESPHOME_LOG_TAG(TAG, "rtttl")
PROGMEM_STRING_TABLE(RtttlStateStrings, "State::STOPPED", "State::INIT", "State::STARTING", "State::RUNNING", "State::STOPPING", "UNKNOWN")
uint16_t progmem_read_uint16(const uint16_t *addr)
void HOT delay(uint32_t ms)
uint32_t IRAM_ATTR HOT millis()
A song in storage that outlives playback, such as a literal from generated code; PROGMEM on ESP8266.