AudioContext.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  1. /*
  2. * Copyright (c) 2023, Luke Wilde <lukew@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <LibWeb/Bindings/AudioContextPrototype.h>
  7. #include <LibWeb/Bindings/Intrinsics.h>
  8. #include <LibWeb/DOM/Event.h>
  9. #include <LibWeb/HTML/HTMLMediaElement.h>
  10. #include <LibWeb/HTML/Scripting/TemporaryExecutionContext.h>
  11. #include <LibWeb/HTML/Window.h>
  12. #include <LibWeb/WebAudio/AudioContext.h>
  13. #include <LibWeb/WebIDL/Promise.h>
  14. namespace Web::WebAudio {
  15. JS_DEFINE_ALLOCATOR(AudioContext);
  16. // https://webaudio.github.io/web-audio-api/#dom-audiocontext-audiocontext
  17. WebIDL::ExceptionOr<JS::NonnullGCPtr<AudioContext>> AudioContext::construct_impl(JS::Realm& realm, AudioContextOptions const& context_options)
  18. {
  19. return realm.heap().allocate<AudioContext>(realm, realm, context_options);
  20. }
  21. AudioContext::AudioContext(JS::Realm& realm, AudioContextOptions const& context_options)
  22. : BaseAudioContext(realm)
  23. {
  24. // FIXME: If the current settings object’s responsible document is NOT fully active, throw an InvalidStateError and abort these steps.
  25. // 1: Set a [[control thread state]] to suspended on the AudioContext.
  26. BaseAudioContext::set_control_state(Bindings::AudioContextState::Suspended);
  27. // 2: Set a [[rendering thread state]] to suspended on the AudioContext.
  28. BaseAudioContext::set_rendering_state(Bindings::AudioContextState::Suspended);
  29. // 3: Let [[pending resume promises]] be a slot on this AudioContext, that is an initially empty ordered list of promises.
  30. // 4: If contextOptions is given, apply the options:
  31. // 4.1: Set the internal latency of this AudioContext according to contextOptions.latencyHint, as described in latencyHint.
  32. switch (context_options.latency_hint) {
  33. case Bindings::AudioContextLatencyCategory::Balanced:
  34. // FIXME: Determine optimal settings for balanced.
  35. break;
  36. case Bindings::AudioContextLatencyCategory::Interactive:
  37. // FIXME: Determine optimal settings for interactive.
  38. break;
  39. case Bindings::AudioContextLatencyCategory::Playback:
  40. // FIXME: Determine optimal settings for playback.
  41. break;
  42. default:
  43. VERIFY_NOT_REACHED();
  44. }
  45. // 4.2: If contextOptions.sampleRate is specified, set the sampleRate of this AudioContext to this value. Otherwise,
  46. // use the sample rate of the default output device. If the selected sample rate differs from the sample rate of the output device,
  47. // this AudioContext MUST resample the audio output to match the sample rate of the output device.
  48. if (context_options.sample_rate.has_value()) {
  49. BaseAudioContext::set_sample_rate(context_options.sample_rate.value());
  50. } else {
  51. // FIXME: This would ideally be coming from the default output device, but we can only get this on Serenity
  52. // For now we'll just have to resample
  53. BaseAudioContext::set_sample_rate(44100);
  54. }
  55. // FIXME: 5: If the context is allowed to start, send a control message to start processing.
  56. // FIXME: Implement control message queue to run following steps on the rendering thread
  57. if (m_allowed_to_start) {
  58. // FIXME: 5.1: Attempt to acquire system resources. In case of failure, abort the following steps.
  59. // 5.2: Set the [[rendering thread state]] to "running" on the AudioContext.
  60. BaseAudioContext::set_rendering_state(Bindings::AudioContextState::Running);
  61. // 5.3: queue a media element task to execute the following steps:
  62. queue_a_media_element_task(JS::create_heap_function(heap(), [&realm, this]() {
  63. // 5.3.1: Set the state attribute of the AudioContext to "running".
  64. BaseAudioContext::set_control_state(Bindings::AudioContextState::Running);
  65. // 5.3.2: queue a media element task to fire an event named statechange at the AudioContext.
  66. this->dispatch_event(DOM::Event::create(realm, HTML::EventNames::statechange));
  67. }));
  68. }
  69. }
  70. AudioContext::~AudioContext() = default;
  71. void AudioContext::initialize(JS::Realm& realm)
  72. {
  73. Base::initialize(realm);
  74. WEB_SET_PROTOTYPE_FOR_INTERFACE(AudioContext);
  75. }
  76. void AudioContext::visit_edges(Cell::Visitor& visitor)
  77. {
  78. Base::visit_edges(visitor);
  79. visitor.visit(m_pending_resume_promises);
  80. }
  81. // https://www.w3.org/TR/webaudio/#dom-audiocontext-getoutputtimestamp
  82. AudioTimestamp AudioContext::get_output_timestamp()
  83. {
  84. dbgln("(STUBBED) getOutputTimestamp()");
  85. return {};
  86. }
  87. // https://www.w3.org/TR/webaudio/#dom-audiocontext-resume
  88. WebIDL::ExceptionOr<JS::NonnullGCPtr<WebIDL::Promise>> AudioContext::resume()
  89. {
  90. auto& realm = this->realm();
  91. // 1. If this's relevant global object's associated Document is not fully active then return a promise rejected with "InvalidStateError" DOMException.
  92. auto const& associated_document = verify_cast<HTML::Window>(HTML::relevant_global_object(*this)).associated_document();
  93. if (!associated_document.is_fully_active())
  94. return WebIDL::InvalidStateError::create(realm, "Document is not fully active"_string);
  95. // 2. Let promise be a new Promise.
  96. auto promise = WebIDL::create_promise(realm);
  97. // 3. If the [[control thread state]] on the AudioContext is closed reject the promise with InvalidStateError, abort these steps, returning promise.
  98. if (state() == Bindings::AudioContextState::Closed) {
  99. WebIDL::reject_promise(realm, promise, WebIDL::InvalidStateError::create(realm, "Audio context is already closed."_string));
  100. return promise;
  101. }
  102. // 4. Set [[suspended by user]] to true.
  103. m_suspended_by_user = true;
  104. // 5. If the context is not allowed to start, append promise to [[pending promises]] and [[pending resume promises]] and abort these steps, returning promise.
  105. if (m_allowed_to_start) {
  106. m_pending_promises.append(promise);
  107. m_pending_resume_promises.append(promise);
  108. }
  109. // 6. Set the [[control thread state]] on the AudioContext to running.
  110. set_control_state(Bindings::AudioContextState::Running);
  111. // 7. Queue a control message to resume the AudioContext.
  112. // FIXME: Implement control message queue to run following steps on the rendering thread
  113. // FIXME: 7.1: Attempt to acquire system resources.
  114. // 7.2: Set the [[rendering thread state]] on the AudioContext to running.
  115. set_rendering_state(Bindings::AudioContextState::Running);
  116. // 7.3: Start rendering the audio graph.
  117. if (!start_rendering_audio_graph()) {
  118. // 7.4: In case of failure, queue a media element task to execute the following steps:
  119. queue_a_media_element_task(JS::create_heap_function(heap(), [&realm, this]() {
  120. HTML::TemporaryExecutionContext context(realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes);
  121. // 7.4.1: Reject all promises from [[pending resume promises]] in order, then clear [[pending resume promises]].
  122. for (auto const& promise : m_pending_resume_promises) {
  123. WebIDL::reject_promise(realm, promise, JS::js_null());
  124. // 7.4.2: Additionally, remove those promises from [[pending promises]].
  125. m_pending_promises.remove_first_matching([&promise](auto& pending_promise) {
  126. return pending_promise == promise;
  127. });
  128. }
  129. m_pending_resume_promises.clear();
  130. }));
  131. }
  132. // 7.5: queue a media element task to execute the following steps:
  133. queue_a_media_element_task(JS::create_heap_function(heap(), [&realm, promise, this]() {
  134. HTML::TemporaryExecutionContext context(realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes);
  135. // 7.5.1: Resolve all promises from [[pending resume promises]] in order.
  136. // 7.5.2: Clear [[pending resume promises]]. Additionally, remove those promises from
  137. // [[pending promises]].
  138. for (auto const& pending_resume_promise : m_pending_resume_promises) {
  139. WebIDL::resolve_promise(realm, pending_resume_promise, JS::js_undefined());
  140. m_pending_promises.remove_first_matching([&pending_resume_promise](auto& pending_promise) {
  141. return pending_promise == pending_resume_promise;
  142. });
  143. }
  144. m_pending_resume_promises.clear();
  145. // 7.5.3: Resolve promise.
  146. WebIDL::resolve_promise(realm, promise, JS::js_undefined());
  147. // 7.5.4: If the state attribute of the AudioContext is not already "running":
  148. if (state() != Bindings::AudioContextState::Running) {
  149. // 7.5.4.1: Set the state attribute of the AudioContext to "running".
  150. set_control_state(Bindings::AudioContextState::Running);
  151. // 7.5.4.2: queue a media element task to fire an event named statechange at the AudioContext.
  152. queue_a_media_element_task(JS::create_heap_function(heap(), [&realm, this]() {
  153. this->dispatch_event(DOM::Event::create(realm, HTML::EventNames::statechange));
  154. }));
  155. }
  156. }));
  157. // 8. Return promise.
  158. return promise;
  159. }
  160. // https://www.w3.org/TR/webaudio/#dom-audiocontext-suspend
  161. WebIDL::ExceptionOr<JS::NonnullGCPtr<WebIDL::Promise>> AudioContext::suspend()
  162. {
  163. auto& realm = this->realm();
  164. // 1. If this's relevant global object's associated Document is not fully active then return a promise rejected with "InvalidStateError" DOMException.
  165. auto const& associated_document = verify_cast<HTML::Window>(HTML::relevant_global_object(*this)).associated_document();
  166. if (!associated_document.is_fully_active())
  167. return WebIDL::InvalidStateError::create(realm, "Document is not fully active"_string);
  168. // 2. Let promise be a new Promise.
  169. auto promise = WebIDL::create_promise(realm);
  170. // 3. If the [[control thread state]] on the AudioContext is closed reject the promise with InvalidStateError, abort these steps, returning promise.
  171. if (state() == Bindings::AudioContextState::Closed) {
  172. WebIDL::reject_promise(realm, promise, WebIDL::InvalidStateError::create(realm, "Audio context is already closed."_string));
  173. return promise;
  174. }
  175. // 4. Append promise to [[pending promises]].
  176. m_pending_promises.append(promise);
  177. // 5. Set [[suspended by user]] to true.
  178. m_suspended_by_user = true;
  179. // 6. Set the [[control thread state]] on the AudioContext to suspended.
  180. set_control_state(Bindings::AudioContextState::Suspended);
  181. // 7. Queue a control message to suspend the AudioContext.
  182. // FIXME: Implement control message queue to run following steps on the rendering thread
  183. // FIXME: 7.1: Attempt to release system resources.
  184. // 7.2: Set the [[rendering thread state]] on the AudioContext to suspended.
  185. set_rendering_state(Bindings::AudioContextState::Suspended);
  186. // 7.3: queue a media element task to execute the following steps:
  187. queue_a_media_element_task(JS::create_heap_function(heap(), [&realm, promise, this]() {
  188. HTML::TemporaryExecutionContext context(realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes);
  189. // 7.3.1: Resolve promise.
  190. WebIDL::resolve_promise(realm, promise, JS::js_undefined());
  191. // 7.3.2: If the state attribute of the AudioContext is not already "suspended":
  192. if (state() != Bindings::AudioContextState::Suspended) {
  193. // 7.3.2.1: Set the state attribute of the AudioContext to "suspended".
  194. set_control_state(Bindings::AudioContextState::Suspended);
  195. // 7.3.2.2: queue a media element task to fire an event named statechange at the AudioContext.
  196. queue_a_media_element_task(JS::create_heap_function(heap(), [&realm, this]() {
  197. this->dispatch_event(DOM::Event::create(realm, HTML::EventNames::statechange));
  198. }));
  199. }
  200. }));
  201. // 8. Return promise.
  202. return promise;
  203. }
  204. // https://www.w3.org/TR/webaudio/#dom-audiocontext-close
  205. WebIDL::ExceptionOr<JS::NonnullGCPtr<WebIDL::Promise>> AudioContext::close()
  206. {
  207. auto& realm = this->realm();
  208. // 1. If this's relevant global object's associated Document is not fully active then return a promise rejected with "InvalidStateError" DOMException.
  209. auto const& associated_document = verify_cast<HTML::Window>(HTML::relevant_global_object(*this)).associated_document();
  210. if (!associated_document.is_fully_active())
  211. return WebIDL::InvalidStateError::create(realm, "Document is not fully active"_string);
  212. // 2. Let promise be a new Promise.
  213. auto promise = WebIDL::create_promise(realm);
  214. // 3. If the [[control thread state]] flag on the AudioContext is closed reject the promise with InvalidStateError, abort these steps, returning promise.
  215. if (state() == Bindings::AudioContextState::Closed) {
  216. WebIDL::reject_promise(realm, promise, WebIDL::InvalidStateError::create(realm, "Audio context is already closed."_string));
  217. return promise;
  218. }
  219. // 4. Set the [[control thread state]] flag on the AudioContext to closed.
  220. set_control_state(Bindings::AudioContextState::Closed);
  221. // 5. Queue a control message to close the AudioContext.
  222. // FIXME: Implement control message queue to run following steps on the rendering thread
  223. // FIXME: 5.1: Attempt to release system resources.
  224. // 5.2: Set the [[rendering thread state]] to "suspended".
  225. set_rendering_state(Bindings::AudioContextState::Suspended);
  226. // FIXME: 5.3: If this control message is being run in a reaction to the document being unloaded, abort this algorithm.
  227. // 5.4: queue a media element task to execute the following steps:
  228. queue_a_media_element_task(JS::create_heap_function(heap(), [&realm, promise, this]() {
  229. HTML::TemporaryExecutionContext context(realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes);
  230. // 5.4.1: Resolve promise.
  231. WebIDL::resolve_promise(realm, promise, JS::js_undefined());
  232. // 5.4.2: If the state attribute of the AudioContext is not already "closed":
  233. if (state() != Bindings::AudioContextState::Closed) {
  234. // 5.4.2.1: Set the state attribute of the AudioContext to "closed".
  235. set_control_state(Bindings::AudioContextState::Closed);
  236. }
  237. // 5.4.2.2: queue a media element task to fire an event named statechange at the AudioContext.
  238. // FIXME: Attempting to queue another task in here causes an assertion fail at Vector.h:148
  239. this->dispatch_event(DOM::Event::create(realm, HTML::EventNames::statechange));
  240. }));
  241. // 6. Return promise
  242. return promise;
  243. }
  244. // FIXME: Actually implement the rendering thread
  245. bool AudioContext::start_rendering_audio_graph()
  246. {
  247. bool render_result = true;
  248. return render_result;
  249. }
  250. }