BaseAudioContext.h 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. /*
  2. * Copyright (c) 2023, Luke Wilde <lukew@serenityos.org>
  3. * Copyright (c) 2024, Shannon Booth <shannon@serenityos.org>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #pragma once
  8. #include <LibWeb/Bindings/BaseAudioContextPrototype.h>
  9. #include <LibWeb/DOM/EventTarget.h>
  10. #include <LibWeb/WebIDL/Types.h>
  11. namespace Web::WebAudio {
  12. // https://webaudio.github.io/web-audio-api/#BaseAudioContext
  13. class BaseAudioContext : public DOM::EventTarget {
  14. WEB_PLATFORM_OBJECT(BaseAudioContext, DOM::EventTarget);
  15. public:
  16. virtual ~BaseAudioContext() override;
  17. // https://webaudio.github.io/web-audio-api/#dom-baseaudiocontext-createbuffer-numberofchannels
  18. // > An implementation MUST support at least 32 channels.
  19. // Other browsers appear to only allow 32 channels - so let's limit ourselves to that too.
  20. static constexpr WebIDL::UnsignedLong MAX_NUMBER_OF_CHANNELS { 32 };
  21. // https://webaudio.github.io/web-audio-api/#dom-baseaudiocontext-createbuffer-samplerate
  22. // > An implementation MUST support sample rates in at least the range 8000 to 96000.
  23. // This doesn't seem consistent between browsers. We use what firefox accepts from testing BaseAudioContext.createAudioBuffer.
  24. static constexpr float MIN_SAMPLE_RATE { 8000 };
  25. static constexpr float MAX_SAMPLE_RATE { 192000 };
  26. float sample_rate() const { return m_sample_rate; }
  27. double current_time() const { return m_current_time; }
  28. Bindings::AudioContextState state() const { return m_control_thread_state; }
  29. // https://webaudio.github.io/web-audio-api/#--nyquist-frequency
  30. float nyquist_frequency() const { return m_sample_rate / 2; }
  31. void set_onstatechange(WebIDL::CallbackType*);
  32. WebIDL::CallbackType* onstatechange();
  33. void set_sample_rate(float sample_rate) { m_sample_rate = sample_rate; }
  34. void set_control_state(Bindings::AudioContextState state) { m_control_thread_state = state; }
  35. void set_rendering_state(Bindings::AudioContextState state) { m_rendering_thread_state = state; }
  36. static WebIDL::ExceptionOr<void> verify_audio_options_inside_nominal_range(JS::Realm&, WebIDL::UnsignedLong number_of_channels, WebIDL::UnsignedLong length, float sample_rate);
  37. WebIDL::ExceptionOr<JS::NonnullGCPtr<OscillatorNode>> create_oscillator();
  38. protected:
  39. explicit BaseAudioContext(JS::Realm&);
  40. virtual void initialize(JS::Realm&) override;
  41. private:
  42. float m_sample_rate { 0 };
  43. double m_current_time { 0 };
  44. Bindings::AudioContextState m_control_thread_state = Bindings::AudioContextState::Suspended;
  45. Bindings::AudioContextState m_rendering_thread_state = Bindings::AudioContextState::Suspended;
  46. };
  47. }