AudioContext.cpp 14 KB

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