AudioEngine.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2019-2020, William McPherson <willmcpherson2@gmail.com>
  4. * All rights reserved.
  5. *
  6. * Redistribution and use in source and binary forms, with or without
  7. * modification, are permitted provided that the following conditions are met:
  8. *
  9. * 1. Redistributions of source code must retain the above copyright notice, this
  10. * list of conditions and the following disclaimer.
  11. *
  12. * 2. Redistributions in binary form must reproduce the above copyright notice,
  13. * this list of conditions and the following disclaimer in the documentation
  14. * and/or other materials provided with the distribution.
  15. *
  16. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  17. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  18. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  19. * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  20. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  21. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  22. * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  23. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  24. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  25. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  26. */
  27. #include "AudioEngine.h"
  28. #include <LibAudio/WavLoader.h>
  29. #include <limits>
  30. #include <math.h>
  31. AudioEngine::AudioEngine()
  32. {
  33. set_sustain_impl(1000);
  34. set_attack(5);
  35. set_decay(1000);
  36. set_release(5);
  37. }
  38. AudioEngine::~AudioEngine()
  39. {
  40. }
  41. void AudioEngine::fill_buffer(FixedArray<Sample>& buffer)
  42. {
  43. memset(buffer.data(), 0, buffer_size);
  44. if (m_time == 0)
  45. set_notes_from_roll();
  46. for (size_t i = 0; i < buffer.size(); ++i) {
  47. for (size_t note = 0; note < note_count; ++note) {
  48. switch (m_envelope[note]) {
  49. case Done:
  50. continue;
  51. case Attack:
  52. m_power[note] += m_attack_step;
  53. if (m_power[note] >= 1) {
  54. m_power[note] = 1;
  55. m_envelope[note] = Decay;
  56. }
  57. break;
  58. case Decay:
  59. m_power[note] -= m_decay_step;
  60. if (m_power[note] < m_sustain_level)
  61. m_power[note] = m_sustain_level;
  62. break;
  63. case Release:
  64. m_power[note] -= m_release_step[note];
  65. if (m_power[note] <= 0) {
  66. m_power[note] = 0;
  67. m_envelope[note] = Done;
  68. continue;
  69. }
  70. break;
  71. default:
  72. ASSERT_NOT_REACHED();
  73. }
  74. Audio::Sample sample;
  75. switch (m_wave) {
  76. case Wave::Sine:
  77. sample = sine(note);
  78. break;
  79. case Wave::Saw:
  80. sample = saw(note);
  81. break;
  82. case Wave::Square:
  83. sample = square(note);
  84. break;
  85. case Wave::Triangle:
  86. sample = triangle(note);
  87. break;
  88. case Wave::Noise:
  89. sample = noise();
  90. break;
  91. case Wave::RecordedSample:
  92. sample = recorded_sample(note);
  93. break;
  94. default:
  95. ASSERT_NOT_REACHED();
  96. }
  97. buffer[i].left += sample.left * m_power[note] * volume;
  98. buffer[i].right += sample.right * m_power[note] * volume;
  99. }
  100. }
  101. if (m_delay) {
  102. if (m_delay_buffers.size() >= m_delay) {
  103. auto to_blend = m_delay_buffers.dequeue();
  104. for (size_t i = 0; i < to_blend->size(); ++i) {
  105. buffer[i].left += (*to_blend)[i].left * 0.333333;
  106. buffer[i].right += (*to_blend)[i].right * 0.333333;
  107. }
  108. }
  109. auto delay_buffer = make<FixedArray<Sample>>(buffer.size());
  110. memcpy(delay_buffer->data(), buffer.data(), buffer_size);
  111. m_delay_buffers.enqueue(move(delay_buffer));
  112. }
  113. if (++m_time == m_tick) {
  114. m_time = 0;
  115. update_roll();
  116. }
  117. memcpy(m_back_buffer_ptr->data(), buffer.data(), buffer_size);
  118. swap(m_front_buffer_ptr, m_back_buffer_ptr);
  119. }
  120. void AudioEngine::reset()
  121. {
  122. memset(m_front_buffer.data(), 0, buffer_size);
  123. memset(m_back_buffer.data(), 0, buffer_size);
  124. m_front_buffer_ptr = &m_front_buffer;
  125. m_back_buffer_ptr = &m_back_buffer;
  126. m_delay_buffers.clear();
  127. memset(m_note_on, 0, sizeof(m_note_on));
  128. memset(m_power, 0, sizeof(m_power));
  129. memset(m_envelope, 0, sizeof(m_envelope));
  130. m_time = 0;
  131. m_current_column = 0;
  132. m_previous_column = horizontal_notes - 1;
  133. }
  134. String AudioEngine::set_recorded_sample(const StringView& path)
  135. {
  136. Audio::WavLoader wav_loader(path);
  137. if (wav_loader.has_error())
  138. return String(wav_loader.error_string());
  139. auto wav_buffer = wav_loader.get_more_samples(60 * sample_rate * sizeof(Sample)); // 1 minute maximum
  140. if (!m_recorded_sample.is_empty())
  141. m_recorded_sample.clear();
  142. m_recorded_sample.resize(wav_buffer->sample_count());
  143. double peak = 0;
  144. for (int i = 0; i < wav_buffer->sample_count(); ++i) {
  145. double left_abs = fabs(wav_buffer->samples()[i].left);
  146. double right_abs = fabs(wav_buffer->samples()[i].right);
  147. if (left_abs > peak)
  148. peak = left_abs;
  149. if (right_abs > peak)
  150. peak = right_abs;
  151. }
  152. if (peak) {
  153. for (int i = 0; i < wav_buffer->sample_count(); ++i) {
  154. m_recorded_sample[i].left = wav_buffer->samples()[i].left / peak;
  155. m_recorded_sample[i].right = wav_buffer->samples()[i].right / peak;
  156. }
  157. }
  158. return String::empty();
  159. }
  160. // All of the information for these waves is on Wikipedia.
  161. Audio::Sample AudioEngine::sine(size_t note)
  162. {
  163. double pos = note_frequencies[note] / sample_rate;
  164. double sin_step = pos * 2 * M_PI;
  165. double w = sin(m_pos[note]);
  166. m_pos[note] += sin_step;
  167. return w;
  168. }
  169. Audio::Sample AudioEngine::saw(size_t note)
  170. {
  171. double saw_step = note_frequencies[note] / sample_rate;
  172. double t = m_pos[note];
  173. double w = (0.5 - (t - floor(t))) * 2;
  174. m_pos[note] += saw_step;
  175. return w;
  176. }
  177. Audio::Sample AudioEngine::square(size_t note)
  178. {
  179. double pos = note_frequencies[note] / sample_rate;
  180. double square_step = pos * 2 * M_PI;
  181. double w = sin(m_pos[note]) >= 0 ? 1 : -1;
  182. m_pos[note] += square_step;
  183. return w;
  184. }
  185. Audio::Sample AudioEngine::triangle(size_t note)
  186. {
  187. double triangle_step = note_frequencies[note] / sample_rate;
  188. double t = m_pos[note];
  189. double w = fabs(fmod((4 * t) + 1, 4) - 2) - 1;
  190. m_pos[note] += triangle_step;
  191. return w;
  192. }
  193. Audio::Sample AudioEngine::noise() const
  194. {
  195. double random_percentage = static_cast<double>(rand()) / RAND_MAX;
  196. double w = (random_percentage * 2) - 1;
  197. return w;
  198. }
  199. Audio::Sample AudioEngine::recorded_sample(size_t note)
  200. {
  201. int t = m_pos[note];
  202. if (t >= static_cast<int>(m_recorded_sample.size()))
  203. return 0;
  204. double w_left = m_recorded_sample[t].left;
  205. double w_right = m_recorded_sample[t].right;
  206. if (t + 1 < static_cast<int>(m_recorded_sample.size())) {
  207. double t_fraction = m_pos[note] - t;
  208. w_left += (m_recorded_sample[t + 1].left - m_recorded_sample[t].left) * t_fraction;
  209. w_right += (m_recorded_sample[t + 1].right - m_recorded_sample[t].right) * t_fraction;
  210. }
  211. double recorded_sample_step = note_frequencies[note] / middle_c;
  212. m_pos[note] += recorded_sample_step;
  213. return { w_left, w_right };
  214. }
  215. static inline double calculate_step(double distance, int milliseconds)
  216. {
  217. if (milliseconds == 0)
  218. return distance;
  219. constexpr double samples_per_millisecond = sample_rate / 1000.0;
  220. double samples = milliseconds * samples_per_millisecond;
  221. double step = distance / samples;
  222. return step;
  223. }
  224. void AudioEngine::set_note(int note, Switch switch_note)
  225. {
  226. ASSERT(note >= 0 && note < note_count);
  227. if (switch_note == On) {
  228. if (m_note_on[note] == 0) {
  229. m_pos[note] = 0;
  230. m_envelope[note] = Attack;
  231. }
  232. ++m_note_on[note];
  233. } else {
  234. if (m_note_on[note] >= 1) {
  235. if (m_note_on[note] == 1) {
  236. m_release_step[note] = calculate_step(m_power[note], m_release);
  237. m_envelope[note] = Release;
  238. }
  239. --m_note_on[note];
  240. }
  241. }
  242. ASSERT(m_note_on[note] != std::numeric_limits<u8>::max());
  243. ASSERT(m_power[note] >= 0);
  244. }
  245. void AudioEngine::set_note_current_octave(int note, Switch switch_note)
  246. {
  247. set_note(note + octave_base(), switch_note);
  248. }
  249. void AudioEngine::set_roll_note(int y, int x, Switch switch_note)
  250. {
  251. ASSERT(x >= 0 && x < horizontal_notes);
  252. ASSERT(y >= 0 && y < note_count);
  253. m_roll_notes[y][x] = switch_note;
  254. if (x == m_current_column && switch_note == Off) // If you turn off a note that is playing.
  255. set_note((note_count - 1) - y, Off);
  256. }
  257. void AudioEngine::update_roll()
  258. {
  259. if (++m_current_column == horizontal_notes)
  260. m_current_column = 0;
  261. if (++m_previous_column == horizontal_notes)
  262. m_previous_column = 0;
  263. }
  264. void AudioEngine::set_notes_from_roll()
  265. {
  266. for (int note = 0; note < note_count; ++note) {
  267. if (m_roll_notes[note][m_previous_column] == On)
  268. set_note((note_count - 1) - note, Off);
  269. if (m_roll_notes[note][m_current_column] == On)
  270. set_note((note_count - 1) - note, On);
  271. }
  272. }
  273. void AudioEngine::set_octave(Direction direction)
  274. {
  275. if (direction == Up) {
  276. if (m_octave < octave_max)
  277. ++m_octave;
  278. } else {
  279. if (m_octave > octave_min)
  280. --m_octave;
  281. }
  282. }
  283. void AudioEngine::set_wave(int wave)
  284. {
  285. ASSERT(wave >= first_wave && wave <= last_wave);
  286. m_wave = wave;
  287. }
  288. void AudioEngine::set_wave(Direction direction)
  289. {
  290. if (direction == Up) {
  291. if (++m_wave > last_wave)
  292. m_wave = first_wave;
  293. } else {
  294. if (--m_wave < first_wave)
  295. m_wave = last_wave;
  296. }
  297. }
  298. void AudioEngine::set_attack(int attack)
  299. {
  300. ASSERT(attack >= 0);
  301. m_attack = attack;
  302. m_attack_step = calculate_step(1, m_attack);
  303. }
  304. void AudioEngine::set_decay(int decay)
  305. {
  306. ASSERT(decay >= 0);
  307. m_decay = decay;
  308. m_decay_step = calculate_step(1 - m_sustain_level, m_decay);
  309. }
  310. void AudioEngine::set_sustain_impl(int sustain)
  311. {
  312. ASSERT(sustain >= 0);
  313. m_sustain = sustain;
  314. m_sustain_level = sustain / 1000.0;
  315. }
  316. void AudioEngine::set_sustain(int sustain)
  317. {
  318. set_sustain_impl(sustain);
  319. set_decay(m_decay);
  320. }
  321. void AudioEngine::set_release(int release)
  322. {
  323. ASSERT(release >= 0);
  324. m_release = release;
  325. }
  326. void AudioEngine::set_delay(int delay)
  327. {
  328. ASSERT(delay >= 0);
  329. m_delay_buffers.clear();
  330. m_delay = delay;
  331. }