audio.c 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599
  1. /* Copyright 2016-2020 Jack Humbert
  2. * Copyright 2020 JohSchneider
  3. * This program is free software: you can redistribute it and/or modify
  4. * it under the terms of the GNU General Public License as published by
  5. * the Free Software Foundation, either version 2 of the License, or
  6. * (at your option) any later version.
  7. *
  8. * This program is distributed in the hope that it will be useful,
  9. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. * GNU General Public License for more details.
  12. *
  13. * You should have received a copy of the GNU General Public License
  14. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  15. */
  16. #include "audio.h"
  17. #include "eeconfig.h"
  18. #include "timer.h"
  19. #include "debug.h"
  20. #include "wait.h"
  21. #include "util.h"
  22. /* audio system:
  23. *
  24. * audio.[ch] takes care of all overall state, tracking the actively playing
  25. * notes/tones; the notes a SONG consists of;
  26. * ...
  27. * = everything audio-related that is platform agnostic
  28. *
  29. * driver_[avr|chibios]_[dac|pwm] take care of the lower hardware dependent parts,
  30. * specific to each platform and the used subsystem/driver to drive
  31. * the output pins/channels with the calculated frequencies for each
  32. * active tone
  33. * as part of this, the driver has to trigger regular state updates by
  34. * calling 'audio_update_state' through some sort of timer - be it a
  35. * dedicated one or piggybacking on for example the timer used to
  36. * generate a pwm signal/clock.
  37. *
  38. *
  39. * A Note on terminology:
  40. * tone, pitch and frequency are used somewhat interchangeably, in a strict Wikipedia-sense:
  41. * "(Musical) tone, a sound characterized by its duration, pitch (=frequency),
  42. * intensity (=volume), and timbre"
  43. * - intensity/volume is currently not handled at all, although the 'dac_additive' driver could do so
  44. * - timbre is handled globally (TODO: only used with the pwm drivers at the moment)
  45. *
  46. * in musical_note.h a 'note' is the combination of a pitch and a duration
  47. * these are used to create SONG arrays; during playback their frequencies
  48. * are handled as single successive tones, while the durations are
  49. * kept track of in 'audio_update_state'
  50. *
  51. * 'voice' as it is used here, equates to a sort of instrument with its own
  52. * characteristics sound and effects
  53. * the audio system as-is deals only with (possibly multiple) tones of one
  54. * instrument/voice at a time (think: chords). since the number of tones that
  55. * can be reproduced depends on the hardware/driver in use: pwm can only
  56. * reproduce one tone per output/speaker; DACs can reproduce/mix multiple
  57. * when doing additive synthesis.
  58. *
  59. * 'duration' can either be in the beats-per-minute related unit found in
  60. * musical_notes.h, OR in ms; keyboards create SONGs with the former, while
  61. * the internal state of the audio system does its calculations with the later - ms
  62. */
  63. #ifndef AUDIO_DEFAULT_ON
  64. # define AUDIO_DEFAULT_ON true
  65. #endif
  66. #ifndef AUDIO_DEFAULT_CLICKY_ON
  67. # define AUDIO_DEFAULT_CLICKY_ON true
  68. #endif
  69. #ifndef AUDIO_TONE_STACKSIZE
  70. # define AUDIO_TONE_STACKSIZE 8
  71. #endif
  72. 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
  73. musical_tone_t tones[AUDIO_TONE_STACKSIZE]; // stack of currently active tones
  74. bool playing_melody = false; // playing a SONG?
  75. bool playing_note = false; // or (possibly multiple simultaneous) tones
  76. bool state_changed = false; // global flag, which is set if anything changes with the active_tones
  77. // melody/SONG related state variables
  78. float (*notes_pointer)[][2]; // SONG, an array of MUSICAL_NOTEs
  79. uint16_t notes_count; // length of the notes_pointer array
  80. bool notes_repeat; // PLAY_SONG or PLAY_LOOP?
  81. uint16_t melody_current_note_duration = 0; // duration of the currently playing note from the active melody, in ms
  82. uint8_t note_tempo = TEMPO_DEFAULT; // beats-per-minute
  83. uint16_t current_note = 0; // index into the array at notes_pointer
  84. bool note_resting = false; // if a short pause was introduced between two notes with the same frequency while playing a melody
  85. uint16_t last_timestamp = 0;
  86. #ifdef AUDIO_ENABLE_TONE_MULTIPLEXING
  87. # ifndef AUDIO_MAX_SIMULTANEOUS_TONES
  88. # define AUDIO_MAX_SIMULTANEOUS_TONES 3
  89. # endif
  90. uint16_t tone_multiplexing_rate = AUDIO_TONE_MULTIPLEXING_RATE_DEFAULT;
  91. uint8_t tone_multiplexing_index_shift = 0; // offset used on active-tone array access
  92. #endif
  93. // provided and used by voices.c
  94. extern uint8_t note_timbre;
  95. extern bool glissando;
  96. extern bool vibrato;
  97. extern uint16_t voices_timer;
  98. #ifndef STARTUP_SONG
  99. # define STARTUP_SONG SONG(STARTUP_SOUND)
  100. #endif
  101. #ifndef AUDIO_ON_SONG
  102. # define AUDIO_ON_SONG SONG(AUDIO_ON_SOUND)
  103. #endif
  104. #ifndef AUDIO_OFF_SONG
  105. # define AUDIO_OFF_SONG SONG(AUDIO_OFF_SOUND)
  106. #endif
  107. float startup_song[][2] = STARTUP_SONG;
  108. float audio_on_song[][2] = AUDIO_ON_SONG;
  109. float audio_off_song[][2] = AUDIO_OFF_SONG;
  110. static bool audio_initialized = false;
  111. static bool audio_driver_stopped = true;
  112. audio_config_t audio_config;
  113. void eeconfig_update_audio_current(void) {
  114. eeconfig_update_audio(audio_config.raw);
  115. }
  116. void eeconfig_update_audio_default(void) {
  117. audio_config.valid = true;
  118. audio_config.enable = AUDIO_DEFAULT_ON;
  119. audio_config.clicky_enable = AUDIO_DEFAULT_CLICKY_ON;
  120. eeconfig_update_audio(audio_config.raw);
  121. }
  122. void audio_init(void) {
  123. if (audio_initialized) {
  124. return;
  125. }
  126. audio_config.raw = eeconfig_read_audio();
  127. if (!audio_config.valid) {
  128. dprintf("audio_init audio_config.valid = 0. Write default values to EEPROM.\n");
  129. eeconfig_update_audio_default();
  130. }
  131. for (uint8_t i = 0; i < AUDIO_TONE_STACKSIZE; i++) {
  132. tones[i] = (musical_tone_t){.time_started = 0, .pitch = -1.0f, .duration = 0};
  133. }
  134. audio_driver_initialize();
  135. audio_initialized = true;
  136. stop_all_notes();
  137. #ifndef AUDIO_INIT_DELAY
  138. audio_startup();
  139. #endif
  140. }
  141. void audio_startup(void) {
  142. if (audio_config.enable) {
  143. PLAY_SONG(startup_song);
  144. }
  145. last_timestamp = timer_read();
  146. }
  147. void audio_toggle(void) {
  148. if (audio_config.enable) {
  149. stop_all_notes();
  150. }
  151. audio_config.enable ^= 1;
  152. eeconfig_update_audio(audio_config.raw);
  153. if (audio_config.enable) {
  154. audio_on_user();
  155. } else {
  156. audio_off_user();
  157. }
  158. }
  159. void audio_on(void) {
  160. audio_config.enable = 1;
  161. eeconfig_update_audio(audio_config.raw);
  162. audio_on_user();
  163. PLAY_SONG(audio_on_song);
  164. }
  165. void audio_off(void) {
  166. PLAY_SONG(audio_off_song);
  167. audio_off_user();
  168. wait_ms(100);
  169. audio_stop_all();
  170. audio_config.enable = 0;
  171. eeconfig_update_audio(audio_config.raw);
  172. }
  173. bool audio_is_on(void) {
  174. return (audio_config.enable != 0);
  175. }
  176. void audio_stop_all(void) {
  177. if (audio_driver_stopped) {
  178. return;
  179. }
  180. active_tones = 0;
  181. audio_driver_stop();
  182. playing_melody = false;
  183. playing_note = false;
  184. melody_current_note_duration = 0;
  185. for (uint8_t i = 0; i < AUDIO_TONE_STACKSIZE; i++) {
  186. tones[i] = (musical_tone_t){.time_started = 0, .pitch = -1.0f, .duration = 0};
  187. }
  188. audio_driver_stopped = true;
  189. }
  190. void audio_stop_tone(float pitch) {
  191. if (pitch < 0.0f) {
  192. pitch = -1 * pitch;
  193. }
  194. if (playing_note) {
  195. if (!audio_initialized) {
  196. audio_init();
  197. }
  198. bool found = false;
  199. for (int i = AUDIO_TONE_STACKSIZE - 1; i >= 0; i--) {
  200. found = (tones[i].pitch == pitch);
  201. if (found) {
  202. tones[i] = (musical_tone_t){.time_started = 0, .pitch = -1.0f, .duration = 0};
  203. for (int j = i; (j < AUDIO_TONE_STACKSIZE - 1); j++) {
  204. tones[j] = tones[j + 1];
  205. tones[j + 1] = (musical_tone_t){.time_started = 0, .pitch = -1.0f, .duration = 0};
  206. }
  207. break;
  208. }
  209. }
  210. if (!found) {
  211. return;
  212. }
  213. state_changed = true;
  214. active_tones--;
  215. if (active_tones < 0) active_tones = 0;
  216. #ifdef AUDIO_ENABLE_TONE_MULTIPLEXING
  217. if (tone_multiplexing_index_shift >= active_tones) {
  218. tone_multiplexing_index_shift = 0;
  219. }
  220. #endif
  221. if (active_tones == 0) {
  222. audio_driver_stop();
  223. audio_driver_stopped = true;
  224. playing_note = false;
  225. }
  226. }
  227. }
  228. void audio_play_note(float pitch, uint16_t duration) {
  229. if (!audio_config.enable) {
  230. return;
  231. }
  232. if (!audio_initialized) {
  233. audio_init();
  234. }
  235. if (pitch < 0.0f) {
  236. pitch = -1 * pitch;
  237. }
  238. // round-robin: shifting out old tones, keeping only unique ones
  239. // if the new frequency is already amongst the active tones, shift it to the top of the stack
  240. bool found = false;
  241. for (int i = active_tones - 1; i >= 0; i--) {
  242. found = (tones[i].pitch == pitch);
  243. if (found) {
  244. for (int j = i; (j < active_tones - 1); j++) {
  245. tones[j] = tones[j + 1];
  246. tones[j + 1] = (musical_tone_t){.time_started = timer_read(), .pitch = pitch, .duration = duration};
  247. }
  248. return; // since this frequency played already, the hardware was already started
  249. }
  250. }
  251. // frequency/tone is actually new, so we put it on the top of the stack
  252. active_tones++;
  253. if (active_tones > AUDIO_TONE_STACKSIZE) {
  254. active_tones = AUDIO_TONE_STACKSIZE;
  255. // shift out the oldest tone to make room
  256. for (int i = 0; i < active_tones - 1; i++) {
  257. tones[i] = tones[i + 1];
  258. }
  259. }
  260. state_changed = true;
  261. playing_note = true;
  262. tones[active_tones - 1] = (musical_tone_t){.time_started = timer_read(), .pitch = pitch, .duration = duration};
  263. // TODO: needs to be handled per note/tone -> use its timestamp instead?
  264. voices_timer = timer_read(); // reset to zero, for the effects added by voices.c
  265. if (audio_driver_stopped) {
  266. audio_driver_start();
  267. audio_driver_stopped = false;
  268. }
  269. }
  270. void audio_play_tone(float pitch) {
  271. audio_play_note(pitch, 0xffff);
  272. }
  273. void audio_play_melody(float (*np)[][2], uint16_t n_count, bool n_repeat) {
  274. if (!audio_config.enable) {
  275. audio_stop_all();
  276. return;
  277. }
  278. if (n_count == 0) {
  279. return;
  280. }
  281. if (!audio_initialized) {
  282. audio_init();
  283. }
  284. // Cancel note if a note is playing
  285. if (playing_note) audio_stop_all();
  286. playing_melody = true;
  287. note_resting = false;
  288. notes_pointer = np;
  289. notes_count = n_count;
  290. notes_repeat = n_repeat;
  291. current_note = 0; // note in the melody-array/list at note_pointer
  292. // start first note manually, which also starts the audio_driver
  293. // all following/remaining notes are played by 'audio_update_state'
  294. audio_play_note((*notes_pointer)[current_note][0], audio_duration_to_ms((*notes_pointer)[current_note][1]));
  295. last_timestamp = timer_read();
  296. melody_current_note_duration = audio_duration_to_ms((*notes_pointer)[current_note][1]);
  297. }
  298. float click[2][2];
  299. void audio_play_click(uint16_t delay, float pitch, uint16_t duration) {
  300. uint16_t duration_tone = audio_ms_to_duration(duration);
  301. uint16_t duration_delay = audio_ms_to_duration(delay);
  302. if (delay <= 0.0f) {
  303. click[0][0] = pitch;
  304. click[0][1] = duration_tone;
  305. click[1][0] = 0.0f;
  306. click[1][1] = 0.0f;
  307. audio_play_melody(&click, 1, false);
  308. } else {
  309. // first note is a rest/pause
  310. click[0][0] = 0.0f;
  311. click[0][1] = duration_delay;
  312. // second note is the actual click
  313. click[1][0] = pitch;
  314. click[1][1] = duration_tone;
  315. audio_play_melody(&click, 2, false);
  316. }
  317. }
  318. bool audio_is_playing_note(void) {
  319. return playing_note;
  320. }
  321. bool audio_is_playing_melody(void) {
  322. return playing_melody;
  323. }
  324. uint8_t audio_get_number_of_active_tones(void) {
  325. return active_tones;
  326. }
  327. float audio_get_frequency(uint8_t tone_index) {
  328. if (tone_index >= active_tones) {
  329. return 0.0f;
  330. }
  331. return tones[active_tones - tone_index - 1].pitch;
  332. }
  333. float audio_get_processed_frequency(uint8_t tone_index) {
  334. if (tone_index >= active_tones) {
  335. return 0.0f;
  336. }
  337. int8_t index = active_tones - tone_index - 1;
  338. // new tones are stacked on top (= appended at the end), so the most recent/current is MAX-1
  339. #ifdef AUDIO_ENABLE_TONE_MULTIPLEXING
  340. index = index - tone_multiplexing_index_shift;
  341. if (index < 0) // wrap around
  342. index += active_tones;
  343. #endif
  344. if (tones[index].pitch <= 0.0f) {
  345. return 0.0f;
  346. }
  347. return voice_envelope(tones[index].pitch);
  348. }
  349. bool audio_update_state(void) {
  350. if (!playing_note && !playing_melody) {
  351. return false;
  352. }
  353. bool goto_next_note = false;
  354. uint16_t current_time = timer_read();
  355. if (playing_melody) {
  356. goto_next_note = timer_elapsed(last_timestamp) >= melody_current_note_duration;
  357. if (goto_next_note) {
  358. uint16_t delta = timer_elapsed(last_timestamp) - melody_current_note_duration;
  359. last_timestamp = current_time;
  360. uint16_t previous_note = current_note;
  361. current_note++;
  362. voices_timer = timer_read(); // reset to zero, for the effects added by voices.c
  363. if (current_note >= notes_count) {
  364. if (notes_repeat) {
  365. current_note = 0;
  366. } else {
  367. audio_stop_all();
  368. return false;
  369. }
  370. }
  371. if (!note_resting && (*notes_pointer)[previous_note][0] == (*notes_pointer)[current_note][0]) {
  372. note_resting = true;
  373. // special handling for successive notes of the same frequency:
  374. // insert a short pause to separate them audibly
  375. audio_play_note(0.0f, audio_duration_to_ms(2));
  376. current_note = previous_note;
  377. melody_current_note_duration = audio_duration_to_ms(2);
  378. } else {
  379. note_resting = false;
  380. // TODO: handle glissando here (or remember previous and current tone)
  381. /* there would need to be a freq(here we are) -> freq(next note)
  382. * and do slide/glissando in between problem here is to know which
  383. * frequency on the stack relates to what other? e.g. a melody starts
  384. * tones in a sequence, and stops expiring one, so the most recently
  385. * stopped is the starting point for a glissando to the most recently started?
  386. * how to detect and preserve this relation?
  387. * and what about user input, chords, ...?
  388. */
  389. // '- delta': Skip forward in the next note's length if we've over shot
  390. // the last, so the overall length of the song is the same
  391. uint16_t duration = audio_duration_to_ms((*notes_pointer)[current_note][1]);
  392. // Skip forward past any completely missed notes
  393. while (delta > duration && current_note < notes_count - 1) {
  394. delta -= duration;
  395. current_note++;
  396. duration = audio_duration_to_ms((*notes_pointer)[current_note][1]);
  397. }
  398. if (delta < duration) {
  399. duration -= delta;
  400. } else {
  401. // Only way to get here is if it is the last note and
  402. // we have completely missed it. Play it for 1ms...
  403. duration = 1;
  404. }
  405. audio_play_note((*notes_pointer)[current_note][0], duration);
  406. melody_current_note_duration = duration;
  407. }
  408. }
  409. }
  410. if (playing_note) {
  411. #ifdef AUDIO_ENABLE_TONE_MULTIPLEXING
  412. tone_multiplexing_index_shift = (int)(current_time / tone_multiplexing_rate) % MIN(AUDIO_MAX_SIMULTANEOUS_TONES, active_tones);
  413. goto_next_note = true;
  414. #endif
  415. if (vibrato || glissando) {
  416. // force update on each cycle, since vibrato shifts the frequency slightly
  417. goto_next_note = true;
  418. }
  419. // housekeeping: stop notes that have no playtime left
  420. for (int i = 0; i < active_tones; i++) {
  421. if ((tones[i].duration != 0xffff) // indefinitely playing notes, started by 'audio_play_tone'
  422. && (tones[i].duration != 0) // 'uninitialized'
  423. ) {
  424. if (timer_elapsed(tones[i].time_started) >= tones[i].duration) {
  425. audio_stop_tone(tones[i].pitch); // also sets 'state_changed=true'
  426. }
  427. }
  428. }
  429. }
  430. // state-changes have a higher priority, always triggering the hardware to update
  431. if (state_changed) {
  432. state_changed = false;
  433. return true;
  434. }
  435. return goto_next_note;
  436. }
  437. // Tone-multiplexing functions
  438. #ifdef AUDIO_ENABLE_TONE_MULTIPLEXING
  439. void audio_set_tone_multiplexing_rate(uint16_t rate) {
  440. tone_multiplexing_rate = rate;
  441. }
  442. void audio_enable_tone_multiplexing(void) {
  443. tone_multiplexing_rate = AUDIO_TONE_MULTIPLEXING_RATE_DEFAULT;
  444. }
  445. void audio_disable_tone_multiplexing(void) {
  446. tone_multiplexing_rate = 0;
  447. }
  448. void audio_increase_tone_multiplexing_rate(uint16_t change) {
  449. if ((0xffff - change) > tone_multiplexing_rate) {
  450. tone_multiplexing_rate += change;
  451. }
  452. }
  453. void audio_decrease_tone_multiplexing_rate(uint16_t change) {
  454. if (change <= tone_multiplexing_rate) {
  455. tone_multiplexing_rate -= change;
  456. }
  457. }
  458. #endif
  459. // Tempo functions
  460. void audio_set_tempo(uint8_t tempo) {
  461. if (tempo < 10) note_tempo = 10;
  462. // else if (tempo > 250)
  463. // note_tempo = 250;
  464. else
  465. note_tempo = tempo;
  466. }
  467. void audio_increase_tempo(uint8_t tempo_change) {
  468. if (tempo_change > 255 - note_tempo)
  469. note_tempo = 255;
  470. else
  471. note_tempo += tempo_change;
  472. }
  473. void audio_decrease_tempo(uint8_t tempo_change) {
  474. if (tempo_change >= note_tempo - 10)
  475. note_tempo = 10;
  476. else
  477. note_tempo -= tempo_change;
  478. }
  479. /**
  480. * Converts from units of 1/64ths of a beat to milliseconds.
  481. *
  482. * Round-off error is at most 1 millisecond.
  483. *
  484. * Conversion will never overflow for duration_bpm <= 699, provided that
  485. * note_tempo is at least 10. This is quite a long duration, over ten beats.
  486. *
  487. * Beware that for duration_bpm > 699, the result may overflow uint16_t range
  488. * when duration_bpm is large compared to note_tempo:
  489. *
  490. * duration_bpm * 60 * 1000 / (64 * note_tempo) > UINT16_MAX
  491. *
  492. * duration_bpm > (2 * 65535 / 1875) * note_tempo
  493. * = 69.904 * note_tempo.
  494. */
  495. uint16_t audio_duration_to_ms(uint16_t duration_bpm) {
  496. return ((uint32_t)duration_bpm * 1875) / ((uint_fast16_t)note_tempo * 2);
  497. }
  498. /**
  499. * Converts from units of milliseconds to 1/64ths of a beat.
  500. *
  501. * Round-off error is at most 1/64th of a beat.
  502. *
  503. * This conversion never overflows: since duration_ms <= UINT16_MAX = 65535
  504. * and note_tempo <= 255, the result is always in uint16_t range:
  505. *
  506. * duration_ms * 64 * note_tempo / 60 / 1000
  507. * <= 65535 * 2 * 255 / 1875
  508. * = 17825.52
  509. * <= UINT16_MAX.
  510. */
  511. uint16_t audio_ms_to_duration(uint16_t duration_ms) {
  512. return ((uint32_t)duration_ms * 2 * note_tempo) / 1875;
  513. }
  514. __attribute__((weak)) void audio_on_user(void) {}
  515. __attribute__((weak)) void audio_off_user(void) {}