audio.c 19 KB

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