Keyboard.cpp 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. /*
  2. * Copyright (c) 2021-2022, kleines Filmröllchen <filmroellchen@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include "Keyboard.h"
  7. #include "Music.h"
  8. #include <AK/Error.h>
  9. #include <AK/NumericLimits.h>
  10. namespace DSP {
  11. void Keyboard::set_keyboard_note(u8 pitch, Keyboard::Switch note_switch)
  12. {
  13. VERIFY(pitch < note_frequencies.size());
  14. if (note_switch == Switch::Off) {
  15. m_pressed_notes.remove(pitch);
  16. return;
  17. }
  18. auto fake_note = RollNote {
  19. .on_sample = m_transport->time(),
  20. .off_sample = NumericLimits<u32>::max(),
  21. .pitch = pitch,
  22. .velocity = NumericLimits<i8>::max(),
  23. };
  24. m_pressed_notes.set(pitch, fake_note);
  25. }
  26. void Keyboard::set_keyboard_note_in_active_octave(i8 octave_offset, Switch note_switch)
  27. {
  28. u8 real_note = octave_offset + (m_virtual_keyboard_octave - 1) * notes_per_octave;
  29. set_keyboard_note(real_note, note_switch);
  30. }
  31. void Keyboard::change_virtual_keyboard_octave(Direction direction)
  32. {
  33. if (direction == Direction::Up) {
  34. if (m_virtual_keyboard_octave < octave_max)
  35. ++m_virtual_keyboard_octave;
  36. } else {
  37. if (m_virtual_keyboard_octave > octave_min)
  38. --m_virtual_keyboard_octave;
  39. }
  40. }
  41. ErrorOr<void> Keyboard::set_virtual_keyboard_octave(u8 octave)
  42. {
  43. if (octave <= octave_max && octave >= octave_min) {
  44. m_virtual_keyboard_octave = octave;
  45. return {};
  46. }
  47. return Error::from_string_literal("Octave out of range");
  48. }
  49. bool Keyboard::is_pressed(u8 pitch) const
  50. {
  51. return m_pressed_notes.get(pitch).has_value() && m_pressed_notes.get(pitch)->is_playing(m_transport->time());
  52. }
  53. bool Keyboard::is_pressed_in_active_octave(i8 octave_offset) const
  54. {
  55. return is_pressed(octave_offset + virtual_keyboard_octave_base());
  56. }
  57. }