Envelope.h 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. /*
  2. * Copyright (c) 2021, kleines Filmröllchen <filmroellchen@serenityos.org>.
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #pragma once
  7. #include <AK/StdLibExtras.h>
  8. namespace DSP {
  9. // For now, this cannot be optimal as clang doesn't know underlying type specifications.
  10. enum EnvelopeState {
  11. Off,
  12. Attack,
  13. Decay,
  14. Sustain,
  15. Release,
  16. };
  17. struct Envelope {
  18. constexpr Envelope() = default;
  19. constexpr Envelope(double envelope)
  20. : envelope(envelope)
  21. {
  22. }
  23. constexpr bool is_attack() const { return 0 <= envelope && envelope < 1; }
  24. constexpr double attack() const { return clamp(envelope, 0, 1); }
  25. constexpr void set_attack(double offset) { envelope = offset; }
  26. static constexpr Envelope from_attack(double attack) { return Envelope(attack); }
  27. constexpr bool is_decay() const { return 1 <= envelope && envelope < 2; }
  28. constexpr double decay() const { return clamp(envelope, 1, 2) - 1; }
  29. constexpr void set_decay(double offset) { envelope = 1 + offset; }
  30. static constexpr Envelope from_decay(double decay) { return Envelope(decay + 1); }
  31. constexpr bool is_sustain() const { return 2 <= envelope && envelope < 3; }
  32. constexpr double sustain() const { return clamp(envelope, 2, 3) - 2; }
  33. constexpr void set_sustain(double offset) { envelope = 2 + offset; }
  34. static constexpr Envelope from_sustain(double decay) { return Envelope(decay + 2); }
  35. constexpr bool is_release() const { return 3 <= envelope && envelope < 4; }
  36. constexpr double release() const { return clamp(envelope, 3, 4) - 3; }
  37. constexpr void set_release(double offset) { envelope = 3 + offset; }
  38. static constexpr Envelope from_release(double decay) { return Envelope(decay + 3); }
  39. constexpr bool is_active() const { return 0 <= envelope && envelope < 4; }
  40. constexpr void reset() { envelope = -1; }
  41. constexpr operator EnvelopeState() const
  42. {
  43. if (!is_active())
  44. return EnvelopeState::Off;
  45. if (is_attack())
  46. return EnvelopeState::Attack;
  47. if (is_decay())
  48. return EnvelopeState::Decay;
  49. if (is_sustain())
  50. return EnvelopeState::Sustain;
  51. if (is_release())
  52. return EnvelopeState::Release;
  53. VERIFY_NOT_REACHED();
  54. }
  55. double envelope { -1 };
  56. };
  57. }