BaseAudioContext.cpp 11 KB

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