BaseAudioContext.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  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-createchannelsplitter
  81. WebIDL::ExceptionOr<GC::Ref<ChannelSplitterNode>> BaseAudioContext::create_channel_splitter(WebIDL::UnsignedLong number_of_outputs)
  82. {
  83. ChannelSplitterOptions options;
  84. options.number_of_outputs = number_of_outputs;
  85. return ChannelSplitterNode::create(realm(), *this, options);
  86. }
  87. // https://webaudio.github.io/web-audio-api/#dom-baseaudiocontext-createoscillator
  88. WebIDL::ExceptionOr<GC::Ref<OscillatorNode>> BaseAudioContext::create_oscillator()
  89. {
  90. // Factory method for an OscillatorNode.
  91. return OscillatorNode::create(realm(), *this);
  92. }
  93. // https://webaudio.github.io/web-audio-api/#dom-baseaudiocontext-createdynamicscompressor
  94. WebIDL::ExceptionOr<GC::Ref<DynamicsCompressorNode>> BaseAudioContext::create_dynamics_compressor()
  95. {
  96. // Factory method for a DynamicsCompressorNode.
  97. return DynamicsCompressorNode::create(realm(), *this);
  98. }
  99. // https://webaudio.github.io/web-audio-api/#dom-baseaudiocontext-creategain
  100. WebIDL::ExceptionOr<GC::Ref<GainNode>> BaseAudioContext::create_gain()
  101. {
  102. // Factory method for GainNode.
  103. return GainNode::create(realm(), *this);
  104. }
  105. // https://webaudio.github.io/web-audio-api/#dom-baseaudiocontext-createpanner
  106. WebIDL::ExceptionOr<GC::Ref<PannerNode>> BaseAudioContext::create_panner()
  107. {
  108. // Factory method for a PannerNode.
  109. return PannerNode::create(realm(), *this);
  110. }
  111. // https://webaudio.github.io/web-audio-api/#dom-baseaudiocontext-createbuffer
  112. WebIDL::ExceptionOr<void> BaseAudioContext::verify_audio_options_inside_nominal_range(JS::Realm& realm, WebIDL::UnsignedLong number_of_channels, WebIDL::UnsignedLong length, float sample_rate)
  113. {
  114. // A NotSupportedError exception MUST be thrown if any of the arguments is negative, zero, or outside its nominal range.
  115. if (number_of_channels == 0)
  116. return WebIDL::NotSupportedError::create(realm, "Number of channels must not be '0'"_string);
  117. if (number_of_channels > MAX_NUMBER_OF_CHANNELS)
  118. return WebIDL::NotSupportedError::create(realm, "Number of channels is greater than allowed range"_string);
  119. if (length == 0)
  120. return WebIDL::NotSupportedError::create(realm, "Length of buffer must be at least 1"_string);
  121. if (sample_rate < MIN_SAMPLE_RATE || sample_rate > MAX_SAMPLE_RATE)
  122. return WebIDL::NotSupportedError::create(realm, "Sample rate is outside of allowed range"_string);
  123. return {};
  124. }
  125. void BaseAudioContext::queue_a_media_element_task(GC::Ref<GC::Function<void()>> steps)
  126. {
  127. auto task = HTML::Task::create(vm(), m_media_element_event_task_source.source, HTML::current_principal_settings_object().responsible_document(), steps);
  128. HTML::main_thread_event_loop().task_queue().add(task);
  129. }
  130. // https://webaudio.github.io/web-audio-api/#dom-baseaudiocontext-decodeaudiodata
  131. 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)
  132. {
  133. auto& realm = this->realm();
  134. // FIXME: When decodeAudioData is called, the following steps MUST be performed on the control thread:
  135. // 1. If this's relevant global object's associated Document is not fully active then return a
  136. // promise rejected with "InvalidStateError" DOMException.
  137. auto const& associated_document = verify_cast<HTML::Window>(HTML::relevant_global_object(*this)).associated_document();
  138. if (!associated_document.is_fully_active()) {
  139. auto error = WebIDL::InvalidStateError::create(realm, "The document is not fully active."_string);
  140. return WebIDL::create_rejected_promise_from_exception(realm, error);
  141. }
  142. // 2. Let promise be a new Promise.
  143. auto promise = WebIDL::create_promise(realm);
  144. // FIXME: 3. If audioData is detached, execute the following steps:
  145. if (true) {
  146. // 3.1. Append promise to [[pending promises]].
  147. m_pending_promises.append(promise);
  148. // FIXME: 3.2. Detach the audioData ArrayBuffer. If this operations throws, jump to the step 3.
  149. // 3.3. Queue a decoding operation to be performed on another thread.
  150. queue_a_decoding_operation(promise, move(audio_data), success_callback, error_callback);
  151. }
  152. // 4. Else, execute the following error steps:
  153. else {
  154. // 4.1. Let error be a DataCloneError.
  155. auto error = WebIDL::DataCloneError::create(realm, "Audio data is not detached."_string);
  156. // 4.2. Reject promise with error, and remove it from [[pending promises]].
  157. WebIDL::reject_promise(realm, promise, error);
  158. m_pending_promises.remove_first_matching([&promise](auto& pending_promise) {
  159. return pending_promise == promise;
  160. });
  161. // 4.3. Queue a media element task to invoke errorCallback with error.
  162. if (error_callback) {
  163. queue_a_media_element_task(GC::create_function(heap(), [&realm, error_callback, error] {
  164. auto completion = WebIDL::invoke_callback(*error_callback, {}, error);
  165. if (completion.is_abrupt())
  166. HTML::report_exception(completion, realm);
  167. }));
  168. }
  169. }
  170. // 5. Return promise.
  171. return promise;
  172. }
  173. // https://webaudio.github.io/web-audio-api/#dom-baseaudiocontext-decodeaudiodata
  174. 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)
  175. {
  176. auto& realm = this->realm();
  177. // FIXME: When queuing a decoding operation to be performed on another thread, the following steps
  178. // MUST happen on a thread that is not the control thread nor the rendering thread, called
  179. // the decoding thread.
  180. // 1. Let can decode be a boolean flag, initially set to true.
  181. auto can_decode { true };
  182. // FIXME: 2. Attempt to determine the MIME type of audioData, using MIME Sniffing § 6.2 Matching an
  183. // audio or video type pattern. If the audio or video type pattern matching algorithm returns
  184. // undefined, set can decode to false.
  185. // 3. If can decode is true,
  186. if (can_decode) {
  187. // FIXME: attempt to decode the encoded audioData into linear PCM. In case of
  188. // failure, set can decode to false.
  189. // FIXME: If the media byte-stream contains multiple audio tracks, only decode the first track to linear pcm.
  190. }
  191. // 4. If can decode is false,
  192. if (!can_decode) {
  193. // queue a media element task to execute the following steps:
  194. queue_a_media_element_task(GC::create_function(heap(), [this, &realm, promise, error_callback] {
  195. // 4.1. Let error be a DOMException whose name is EncodingError.
  196. auto error = WebIDL::EncodingError::create(realm, "Unable to decode."_string);
  197. // 4.1.2. Reject promise with error, and remove it from [[pending promises]].
  198. WebIDL::reject_promise(realm, promise, error);
  199. m_pending_promises.remove_first_matching([&promise](auto& pending_promise) {
  200. return pending_promise == promise;
  201. });
  202. // 4.2. If errorCallback is not missing, invoke errorCallback with error.
  203. if (error_callback) {
  204. auto completion = WebIDL::invoke_callback(*error_callback, {}, error);
  205. if (completion.is_abrupt())
  206. HTML::report_exception(completion, realm);
  207. }
  208. }));
  209. }
  210. // 5. Otherwise:
  211. else {
  212. // FIXME: 5.1. Take the result, representing the decoded linear PCM audio data, and resample it to the
  213. // sample-rate of the BaseAudioContext if it is different from the sample-rate of
  214. // audioData.
  215. // FIXME: 5.2. queue a media element task to execute the following steps:
  216. // FIXME: 5.2.1. Let buffer be an AudioBuffer containing the final result (after possibly performing
  217. // sample-rate conversion).
  218. auto buffer = MUST(create_buffer(2, 1, 44100));
  219. // 5.2.2. Resolve promise with buffer.
  220. WebIDL::resolve_promise(realm, promise, buffer);
  221. // 5.2.3. If successCallback is not missing, invoke successCallback with buffer.
  222. if (success_callback) {
  223. auto completion = WebIDL::invoke_callback(*success_callback, {}, buffer);
  224. if (completion.is_abrupt())
  225. HTML::report_exception(completion, realm);
  226. }
  227. }
  228. }
  229. }