BaseAudioContext.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  1. /*
  2. * Copyright (c) 2023, Luke Wilde <lukew@serenityos.org>
  3. * Copyright (c) 2024, Shannon Booth <shannon@serenityos.org>
  4. * Copyright (c) 2024, Jelle Raaijmakers <jelle@ladybird.org>
  5. *
  6. * SPDX-License-Identifier: BSD-2-Clause
  7. */
  8. #include <LibWeb/Bindings/BaseAudioContextPrototype.h>
  9. #include <LibWeb/Bindings/Intrinsics.h>
  10. #include <LibWeb/HTML/EventNames.h>
  11. #include <LibWeb/HTML/Scripting/ExceptionReporter.h>
  12. #include <LibWeb/HTML/Window.h>
  13. #include <LibWeb/WebAudio/AudioBuffer.h>
  14. #include <LibWeb/WebAudio/AudioBufferSourceNode.h>
  15. #include <LibWeb/WebAudio/AudioDestinationNode.h>
  16. #include <LibWeb/WebAudio/BaseAudioContext.h>
  17. #include <LibWeb/WebAudio/BiquadFilterNode.h>
  18. #include <LibWeb/WebAudio/ChannelMergerNode.h>
  19. #include <LibWeb/WebAudio/DynamicsCompressorNode.h>
  20. #include <LibWeb/WebAudio/GainNode.h>
  21. #include <LibWeb/WebAudio/OscillatorNode.h>
  22. #include <LibWeb/WebIDL/AbstractOperations.h>
  23. #include <LibWeb/WebIDL/Promise.h>
  24. namespace Web::WebAudio {
  25. BaseAudioContext::BaseAudioContext(JS::Realm& realm, float sample_rate)
  26. : DOM::EventTarget(realm)
  27. , m_destination(AudioDestinationNode::construct_impl(realm, *this))
  28. , m_sample_rate(sample_rate)
  29. , m_listener(AudioListener::create(realm))
  30. {
  31. }
  32. BaseAudioContext::~BaseAudioContext() = default;
  33. void BaseAudioContext::initialize(JS::Realm& realm)
  34. {
  35. Base::initialize(realm);
  36. WEB_SET_PROTOTYPE_FOR_INTERFACE(BaseAudioContext);
  37. }
  38. void BaseAudioContext::visit_edges(Cell::Visitor& visitor)
  39. {
  40. Base::visit_edges(visitor);
  41. visitor.visit(m_destination);
  42. visitor.visit(m_pending_promises);
  43. visitor.visit(m_listener);
  44. }
  45. void BaseAudioContext::set_onstatechange(WebIDL::CallbackType* event_handler)
  46. {
  47. set_event_handler_attribute(HTML::EventNames::statechange, event_handler);
  48. }
  49. WebIDL::CallbackType* BaseAudioContext::onstatechange()
  50. {
  51. return event_handler_attribute(HTML::EventNames::statechange);
  52. }
  53. // https://webaudio.github.io/web-audio-api/#dom-baseaudiocontext-createbiquadfilter
  54. WebIDL::ExceptionOr<GC::Ref<BiquadFilterNode>> BaseAudioContext::create_biquad_filter()
  55. {
  56. // Factory method for a BiquadFilterNode representing a second order filter which can be configured as one of several common filter types.
  57. return BiquadFilterNode::create(realm(), *this);
  58. }
  59. // https://webaudio.github.io/web-audio-api/#dom-baseaudiocontext-createbuffer
  60. WebIDL::ExceptionOr<GC::Ref<AudioBuffer>> BaseAudioContext::create_buffer(WebIDL::UnsignedLong number_of_channels, WebIDL::UnsignedLong length, float sample_rate)
  61. {
  62. // Creates an AudioBuffer of the given size. The audio data in the buffer will be zero-initialized (silent).
  63. // A NotSupportedError exception MUST be thrown if any of the arguments is negative, zero, or outside its nominal range.
  64. return AudioBuffer::create(realm(), number_of_channels, length, sample_rate);
  65. }
  66. // https://webaudio.github.io/web-audio-api/#dom-baseaudiocontext-createbuffersource
  67. WebIDL::ExceptionOr<GC::Ref<AudioBufferSourceNode>> BaseAudioContext::create_buffer_source()
  68. {
  69. // Factory method for a AudioBufferSourceNode.
  70. return AudioBufferSourceNode::create(realm(), *this);
  71. }
  72. // https://webaudio.github.io/web-audio-api/#dom-baseaudiocontext-createchannelmerger
  73. WebIDL::ExceptionOr<GC::Ref<ChannelMergerNode>> BaseAudioContext::create_channel_merger(WebIDL::UnsignedLong number_of_inputs)
  74. {
  75. ChannelMergerOptions options;
  76. options.number_of_inputs = number_of_inputs;
  77. return ChannelMergerNode::create(realm(), *this, options);
  78. }
  79. // https://webaudio.github.io/web-audio-api/#dom-baseaudiocontext-createoscillator
  80. WebIDL::ExceptionOr<GC::Ref<OscillatorNode>> BaseAudioContext::create_oscillator()
  81. {
  82. // Factory method for an OscillatorNode.
  83. return OscillatorNode::create(realm(), *this);
  84. }
  85. // https://webaudio.github.io/web-audio-api/#dom-baseaudiocontext-createdynamicscompressor
  86. WebIDL::ExceptionOr<GC::Ref<DynamicsCompressorNode>> BaseAudioContext::create_dynamics_compressor()
  87. {
  88. // Factory method for a DynamicsCompressorNode.
  89. return DynamicsCompressorNode::create(realm(), *this);
  90. }
  91. // https://webaudio.github.io/web-audio-api/#dom-baseaudiocontext-creategain
  92. WebIDL::ExceptionOr<GC::Ref<GainNode>> BaseAudioContext::create_gain()
  93. {
  94. // Factory method for GainNode.
  95. return GainNode::create(realm(), *this);
  96. }
  97. // https://webaudio.github.io/web-audio-api/#dom-baseaudiocontext-createbuffer
  98. WebIDL::ExceptionOr<void> BaseAudioContext::verify_audio_options_inside_nominal_range(JS::Realm& realm, WebIDL::UnsignedLong number_of_channels, WebIDL::UnsignedLong length, float sample_rate)
  99. {
  100. // A NotSupportedError exception MUST be thrown if any of the arguments is negative, zero, or outside its nominal range.
  101. if (number_of_channels == 0)
  102. return WebIDL::NotSupportedError::create(realm, "Number of channels must not be '0'"_string);
  103. if (number_of_channels > MAX_NUMBER_OF_CHANNELS)
  104. return WebIDL::NotSupportedError::create(realm, "Number of channels is greater than allowed range"_string);
  105. if (length == 0)
  106. return WebIDL::NotSupportedError::create(realm, "Length of buffer must be at least 1"_string);
  107. if (sample_rate < MIN_SAMPLE_RATE || sample_rate > MAX_SAMPLE_RATE)
  108. return WebIDL::NotSupportedError::create(realm, "Sample rate is outside of allowed range"_string);
  109. return {};
  110. }
  111. void BaseAudioContext::queue_a_media_element_task(GC::Ref<GC::Function<void()>> steps)
  112. {
  113. auto task = HTML::Task::create(vm(), m_media_element_event_task_source.source, HTML::current_principal_settings_object().responsible_document(), steps);
  114. HTML::main_thread_event_loop().task_queue().add(task);
  115. }
  116. // https://webaudio.github.io/web-audio-api/#dom-baseaudiocontext-decodeaudiodata
  117. GC::Ref<WebIDL::Promise> BaseAudioContext::decode_audio_data(GC::Root<WebIDL::BufferSource> audio_data, GC::Ptr<WebIDL::CallbackType> success_callback, GC::Ptr<WebIDL::CallbackType> error_callback)
  118. {
  119. auto& realm = this->realm();
  120. // FIXME: When decodeAudioData is called, the following steps MUST be performed on the control thread:
  121. // 1. If this's relevant global object's associated Document is not fully active then return a
  122. // promise rejected with "InvalidStateError" DOMException.
  123. auto const& associated_document = verify_cast<HTML::Window>(HTML::relevant_global_object(*this)).associated_document();
  124. if (!associated_document.is_fully_active()) {
  125. auto error = WebIDL::InvalidStateError::create(realm, "The document is not fully active."_string);
  126. return WebIDL::create_rejected_promise_from_exception(realm, error);
  127. }
  128. // 2. Let promise be a new Promise.
  129. auto promise = WebIDL::create_promise(realm);
  130. // FIXME: 3. If audioData is detached, execute the following steps:
  131. if (true) {
  132. // 3.1. Append promise to [[pending promises]].
  133. m_pending_promises.append(promise);
  134. // FIXME: 3.2. Detach the audioData ArrayBuffer. If this operations throws, jump to the step 3.
  135. // 3.3. Queue a decoding operation to be performed on another thread.
  136. queue_a_decoding_operation(promise, move(audio_data), success_callback, error_callback);
  137. }
  138. // 4. Else, execute the following error steps:
  139. else {
  140. // 4.1. Let error be a DataCloneError.
  141. auto error = WebIDL::DataCloneError::create(realm, "Audio data is not detached."_string);
  142. // 4.2. Reject promise with error, and remove it from [[pending promises]].
  143. WebIDL::reject_promise(realm, promise, error);
  144. m_pending_promises.remove_first_matching([&promise](auto& pending_promise) {
  145. return pending_promise == promise;
  146. });
  147. // 4.3. Queue a media element task to invoke errorCallback with error.
  148. if (error_callback) {
  149. queue_a_media_element_task(GC::create_function(heap(), [&realm, error_callback, error] {
  150. auto completion = WebIDL::invoke_callback(*error_callback, {}, error);
  151. if (completion.is_abrupt())
  152. HTML::report_exception(completion, realm);
  153. }));
  154. }
  155. }
  156. // 5. Return promise.
  157. return promise;
  158. }
  159. // https://webaudio.github.io/web-audio-api/#dom-baseaudiocontext-decodeaudiodata
  160. void BaseAudioContext::queue_a_decoding_operation(GC::Ref<JS::PromiseCapability> promise, [[maybe_unused]] GC::Root<WebIDL::BufferSource> audio_data, GC::Ptr<WebIDL::CallbackType> success_callback, GC::Ptr<WebIDL::CallbackType> error_callback)
  161. {
  162. auto& realm = this->realm();
  163. // FIXME: When queuing a decoding operation to be performed on another thread, the following steps
  164. // MUST happen on a thread that is not the control thread nor the rendering thread, called
  165. // the decoding thread.
  166. // 1. Let can decode be a boolean flag, initially set to true.
  167. auto can_decode { true };
  168. // FIXME: 2. Attempt to determine the MIME type of audioData, using MIME Sniffing § 6.2 Matching an
  169. // audio or video type pattern. If the audio or video type pattern matching algorithm returns
  170. // undefined, set can decode to false.
  171. // 3. If can decode is true,
  172. if (can_decode) {
  173. // FIXME: attempt to decode the encoded audioData into linear PCM. In case of
  174. // failure, set can decode to false.
  175. // FIXME: If the media byte-stream contains multiple audio tracks, only decode the first track to linear pcm.
  176. }
  177. // 4. If can decode is false,
  178. if (!can_decode) {
  179. // queue a media element task to execute the following steps:
  180. queue_a_media_element_task(GC::create_function(heap(), [this, &realm, promise, error_callback] {
  181. // 4.1. Let error be a DOMException whose name is EncodingError.
  182. auto error = WebIDL::EncodingError::create(realm, "Unable to decode."_string);
  183. // 4.1.2. Reject promise with error, and remove it from [[pending promises]].
  184. WebIDL::reject_promise(realm, promise, error);
  185. m_pending_promises.remove_first_matching([&promise](auto& pending_promise) {
  186. return pending_promise == promise;
  187. });
  188. // 4.2. If errorCallback is not missing, invoke errorCallback with error.
  189. if (error_callback) {
  190. auto completion = WebIDL::invoke_callback(*error_callback, {}, error);
  191. if (completion.is_abrupt())
  192. HTML::report_exception(completion, realm);
  193. }
  194. }));
  195. }
  196. // 5. Otherwise:
  197. else {
  198. // FIXME: 5.1. Take the result, representing the decoded linear PCM audio data, and resample it to the
  199. // sample-rate of the BaseAudioContext if it is different from the sample-rate of
  200. // audioData.
  201. // FIXME: 5.2. queue a media element task to execute the following steps:
  202. // FIXME: 5.2.1. Let buffer be an AudioBuffer containing the final result (after possibly performing
  203. // sample-rate conversion).
  204. auto buffer = MUST(create_buffer(2, 1, 44100));
  205. // 5.2.2. Resolve promise with buffer.
  206. WebIDL::resolve_promise(realm, promise, buffer);
  207. // 5.2.3. If successCallback is not missing, invoke successCallback with buffer.
  208. if (success_callback) {
  209. auto completion = WebIDL::invoke_callback(*success_callback, {}, buffer);
  210. if (completion.is_abrupt())
  211. HTML::report_exception(completion, realm);
  212. }
  213. }
  214. }
  215. }