Synthesizers.cpp 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166
  1. /*
  2. * Copyright (c) 2021-2022, kleines Filmröllchen <filmroellchen@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/HashMap.h>
  7. #include <AK/Math.h>
  8. #include <AK/Random.h>
  9. #include <AK/RefPtr.h>
  10. #include <AK/StdLibExtras.h>
  11. #include <LibAudio/Sample.h>
  12. #include <LibDSP/Envelope.h>
  13. #include <LibDSP/Processor.h>
  14. #include <LibDSP/Synthesizers.h>
  15. namespace DSP::Synthesizers {
  16. Classic::Classic(NonnullRefPtr<Transport> transport)
  17. : DSP::SynthesizerProcessor(transport)
  18. , m_waveform("Waveform"sv, Waveform::Saw)
  19. , m_attack("Attack"sv, 0.01, 2000, 5, Logarithmic::Yes)
  20. , m_decay("Decay"sv, 0.01, 20'000, 80, Logarithmic::Yes)
  21. , m_sustain("Sustain"sv, 0.001, 1, 0.725, Logarithmic::No)
  22. , m_release("Release", 0.01, 6'000, 120, Logarithmic::Yes)
  23. {
  24. m_parameters.append(m_waveform);
  25. m_parameters.append(m_attack);
  26. m_parameters.append(m_decay);
  27. m_parameters.append(m_sustain);
  28. m_parameters.append(m_release);
  29. }
  30. void Classic::process_impl(Signal const& input_signal, [[maybe_unused]] Signal& output_signal)
  31. {
  32. auto const& in = input_signal.get<RollNotes>();
  33. auto& output_samples = output_signal.get<FixedArray<Sample>>();
  34. // Do this for every time step and set the signal accordingly.
  35. for (size_t sample_index = 0; sample_index < output_samples.size(); ++sample_index) {
  36. Sample& out = output_samples[sample_index];
  37. u32 sample_time = m_transport->time() + sample_index;
  38. SinglyLinkedList<PitchedEnvelope> playing_envelopes;
  39. // "Press" the necessary notes in the internal representation,
  40. // and "release" all of the others
  41. for (u8 i = 0; i < note_frequencies.size(); ++i) {
  42. if (auto maybe_note = in.get(i); maybe_note.has_value())
  43. m_playing_notes.set(i, maybe_note.value());
  44. if (m_playing_notes.contains(i)) {
  45. Envelope note_envelope = m_playing_notes.get(i)->to_envelope(sample_time, m_attack * m_transport->ms_sample_rate(), m_decay * m_transport->ms_sample_rate(), m_release * m_transport->ms_sample_rate());
  46. // There are two conditions for removing notes:
  47. // 1. The envelope has expired, regardless of whether the note was still given to us in the input.
  48. if (!note_envelope.is_active()) {
  49. m_playing_notes.remove(i);
  50. continue;
  51. }
  52. // 2. The envelope has not expired, but the note was not given to us.
  53. // This means that the note abruptly stopped playing; i.e. the audio infrastructure didn't know the length of the notes initially.
  54. // That basically means we're dealing with a keyboard note. Chop its end time to end now.
  55. if (!note_envelope.is_release() && !in.get(i).has_value()) {
  56. // dbgln("note {} not released, setting release phase, envelope={}", i, note_envelope.envelope);
  57. note_envelope.set_release(0);
  58. auto real_note = *m_playing_notes.get(i);
  59. real_note.off_sample = sample_time;
  60. m_playing_notes.set(i, real_note);
  61. }
  62. playing_envelopes.append(PitchedEnvelope { note_envelope, i });
  63. }
  64. }
  65. for (auto envelope : playing_envelopes) {
  66. double volume = volume_from_envelope(envelope);
  67. double wave = wave_position(envelope.note);
  68. out += volume * wave;
  69. }
  70. }
  71. }
  72. // Linear ADSR envelope with no peak adjustment.
  73. double Classic::volume_from_envelope(Envelope const& envelope) const
  74. {
  75. switch (static_cast<EnvelopeState>(envelope)) {
  76. case EnvelopeState::Off:
  77. return 0;
  78. case EnvelopeState::Attack:
  79. return envelope.attack();
  80. case EnvelopeState::Decay:
  81. // As we fade from high (1) to low (headroom above the sustain level) here, use 1-decay as the interpolation.
  82. return (1. - envelope.decay()) * (1. - m_sustain) + m_sustain;
  83. case EnvelopeState::Sustain:
  84. return m_sustain;
  85. case EnvelopeState::Release:
  86. // Same goes for the release fade from high to low.
  87. return (1. - envelope.release()) * m_sustain;
  88. }
  89. VERIFY_NOT_REACHED();
  90. }
  91. double Classic::wave_position(u8 note)
  92. {
  93. switch (m_waveform) {
  94. case Sine:
  95. return sin_position(note);
  96. case Triangle:
  97. return triangle_position(note);
  98. case Square:
  99. return square_position(note);
  100. case Saw:
  101. return saw_position(note);
  102. case Noise:
  103. return noise_position(note);
  104. }
  105. VERIFY_NOT_REACHED();
  106. }
  107. double Classic::samples_per_cycle(u8 note) const
  108. {
  109. return m_transport->sample_rate() / note_frequencies[note];
  110. }
  111. double Classic::sin_position(u8 note) const
  112. {
  113. double spc = samples_per_cycle(note);
  114. double cycle_pos = m_transport->time() / spc;
  115. return AK::sin(cycle_pos * 2 * AK::Pi<double>);
  116. }
  117. // Absolute value of the saw wave "flips" the negative portion into the positive, creating a ramp up and down.
  118. double Classic::triangle_position(u8 note) const
  119. {
  120. double saw = saw_position(note);
  121. return AK::fabs(saw) * 2 - 1;
  122. }
  123. // The first half of the cycle period is 1, the other half -1.
  124. double Classic::square_position(u8 note) const
  125. {
  126. double spc = samples_per_cycle(note);
  127. double progress = AK::fmod(static_cast<double>(m_transport->time()), spc) / spc;
  128. return progress >= 0.5 ? -1 : 1;
  129. }
  130. // Modulus creates inverse saw, which we need to flip and scale.
  131. double Classic::saw_position(u8 note) const
  132. {
  133. double spc = samples_per_cycle(note);
  134. double unscaled = spc - AK::fmod(static_cast<double>(m_transport->time()), spc);
  135. return unscaled / (samples_per_cycle(note) / 2.) - 1;
  136. }
  137. // We resample the noise twenty times per cycle.
  138. double Classic::noise_position(u8 note)
  139. {
  140. double spc = samples_per_cycle(note);
  141. u32 getrandom_interval = max(static_cast<u32>(spc / 2), 1);
  142. // Note that this code only works well if the processor is called for every increment of time.
  143. if (m_transport->time() % getrandom_interval == 0)
  144. last_random[note] = (get_random<u16>() / static_cast<double>(NumericLimits<u16>::max()) - .5) * 2;
  145. return last_random[note];
  146. }
  147. }