audio.c 21 KB

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