BaseAudioContext.cpp 12 KB

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