AudioContext.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  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([&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_promises);
  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<JS::Promise>> AudioContext::resume()
  89. {
  90. auto& realm = this->realm();
  91. auto& vm = realm.vm();
  92. // 1. If this's relevant global object's associated Document is not fully active then return a promise rejected with "InvalidStateError" DOMException.
  93. auto const& associated_document = verify_cast<HTML::Window>(HTML::relevant_global_object(*this)).associated_document();
  94. if (!associated_document.is_fully_active())
  95. return WebIDL::InvalidStateError::create(realm, "Document is not fully active"_fly_string);
  96. // 2. Let promise be a new Promise.
  97. auto promise = WebIDL::create_promise(realm);
  98. // 3. If the [[control thread state]] on the AudioContext is closed reject the promise with InvalidStateError, abort these steps, returning promise.
  99. if (state() == Bindings::AudioContextState::Closed) {
  100. WebIDL::reject_promise(realm, promise, WebIDL::InvalidStateError::create(realm, "Audio context is already closed."_fly_string));
  101. return JS::NonnullGCPtr { verify_cast<JS::Promise>(*promise->promise()) };
  102. }
  103. // 4. Set [[suspended by user]] to true.
  104. m_suspended_by_user = true;
  105. // 5. If the context is not allowed to start, append promise to [[pending promises]] and [[pending resume promises]] and abort these steps, returning promise.
  106. if (m_allowed_to_start) {
  107. TRY_OR_THROW_OOM(vm, m_pending_promises.try_append(promise));
  108. TRY_OR_THROW_OOM(vm, m_pending_resume_promises.try_append(promise));
  109. }
  110. // 6. Set the [[control thread state]] on the AudioContext to running.
  111. set_control_state(Bindings::AudioContextState::Running);
  112. // 7. Queue a control message to resume the AudioContext.
  113. // FIXME: Implement control message queue to run following steps on the rendering thread
  114. // FIXME: 7.1: Attempt to acquire system resources.
  115. // 7.2: Set the [[rendering thread state]] on the AudioContext to running.
  116. set_rendering_state(Bindings::AudioContextState::Running);
  117. // 7.3: Start rendering the audio graph.
  118. if (!start_rendering_audio_graph()) {
  119. // 7.4: In case of failure, queue a media element task to execute the following steps:
  120. queue_a_media_element_task([&realm, this]() {
  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. }
  125. m_pending_resume_promises.clear();
  126. // FIXME: 7.4.2: Additionally, remove those promises from [[pending promises]].
  127. });
  128. }
  129. // 7.5: queue a media element task to execute the following steps:
  130. queue_a_media_element_task([&realm, promise, this]() {
  131. // 7.5.1: Resolve all promises from [[pending resume promises]] in order.
  132. for (auto const& pending_resume_promise : m_pending_resume_promises) {
  133. *pending_resume_promise->resolve();
  134. }
  135. // 7.5.2: Clear [[pending resume promises]].
  136. m_pending_resume_promises.clear();
  137. // FIXME: Additionally, remove those promises from [[pending promises]].
  138. // 7.5.3: Resolve promise.
  139. *promise->resolve();
  140. // 7.5.4: If the state attribute of the AudioContext is not already "running":
  141. if (state() != Bindings::AudioContextState::Running) {
  142. // 7.5.4.1: Set the state attribute of the AudioContext to "running".
  143. set_control_state(Bindings::AudioContextState::Running);
  144. // 7.5.4.2: queue a media element task to fire an event named statechange at the AudioContext.
  145. queue_a_media_element_task([&realm, this]() {
  146. this->dispatch_event(DOM::Event::create(realm, HTML::EventNames::statechange));
  147. });
  148. }
  149. });
  150. // 8. Return promise.
  151. return JS::NonnullGCPtr { verify_cast<JS::Promise>(*promise->promise()) };
  152. }
  153. // https://www.w3.org/TR/webaudio/#dom-audiocontext-suspend
  154. WebIDL::ExceptionOr<JS::NonnullGCPtr<JS::Promise>> AudioContext::suspend()
  155. {
  156. auto& realm = this->realm();
  157. auto& vm = realm.vm();
  158. // 1. If this's relevant global object's associated Document is not fully active then return a promise rejected with "InvalidStateError" DOMException.
  159. auto const& associated_document = verify_cast<HTML::Window>(HTML::relevant_global_object(*this)).associated_document();
  160. if (!associated_document.is_fully_active())
  161. return WebIDL::InvalidStateError::create(realm, "Document is not fully active"_fly_string);
  162. // 2. Let promise be a new Promise.
  163. auto promise = WebIDL::create_promise(realm);
  164. // 3. If the [[control thread state]] on the AudioContext is closed reject the promise with InvalidStateError, abort these steps, returning promise.
  165. if (state() == Bindings::AudioContextState::Closed) {
  166. WebIDL::reject_promise(realm, promise, WebIDL::InvalidStateError::create(realm, "Audio context is already closed."_fly_string));
  167. return JS::NonnullGCPtr { verify_cast<JS::Promise>(*promise->promise()) };
  168. }
  169. // 4. Append promise to [[pending promises]].
  170. TRY_OR_THROW_OOM(vm, m_pending_promises.try_append(promise));
  171. // 5. Set [[suspended by user]] to true.
  172. m_suspended_by_user = true;
  173. // 6. Set the [[control thread state]] on the AudioContext to suspended.
  174. set_control_state(Bindings::AudioContextState::Suspended);
  175. // 7. Queue a control message to suspend the AudioContext.
  176. // FIXME: Implement control message queue to run following steps on the rendering thread
  177. // FIXME: 7.1: Attempt to release system resources.
  178. // 7.2: Set the [[rendering thread state]] on the AudioContext to suspended.
  179. set_rendering_state(Bindings::AudioContextState::Suspended);
  180. // 7.3: queue a media element task to execute the following steps:
  181. queue_a_media_element_task([&realm, promise, this]() {
  182. // 7.3.1: Resolve promise.
  183. *promise->resolve();
  184. // 7.3.2: If the state attribute of the AudioContext is not already "suspended":
  185. if (state() != Bindings::AudioContextState::Suspended) {
  186. // 7.3.2.1: Set the state attribute of the AudioContext to "suspended".
  187. set_control_state(Bindings::AudioContextState::Suspended);
  188. // 7.3.2.2: queue a media element task to fire an event named statechange at the AudioContext.
  189. queue_a_media_element_task([&realm, this]() {
  190. this->dispatch_event(DOM::Event::create(realm, HTML::EventNames::statechange));
  191. });
  192. }
  193. });
  194. // 8. Return promise.
  195. return JS::NonnullGCPtr { verify_cast<JS::Promise>(*promise->promise()) };
  196. }
  197. // https://www.w3.org/TR/webaudio/#dom-audiocontext-close
  198. WebIDL::ExceptionOr<JS::NonnullGCPtr<JS::Promise>> AudioContext::close()
  199. {
  200. auto& realm = this->realm();
  201. // 1. If this's relevant global object's associated Document is not fully active then return a promise rejected with "InvalidStateError" DOMException.
  202. auto const& associated_document = verify_cast<HTML::Window>(HTML::relevant_global_object(*this)).associated_document();
  203. if (!associated_document.is_fully_active())
  204. return WebIDL::InvalidStateError::create(realm, "Document is not fully active"_fly_string);
  205. // 2. Let promise be a new Promise.
  206. auto promise = WebIDL::create_promise(realm);
  207. // 3. If the [[control thread state]] flag on the AudioContext is closed reject the promise with InvalidStateError, abort these steps, returning promise.
  208. if (state() == Bindings::AudioContextState::Closed) {
  209. WebIDL::reject_promise(realm, promise, WebIDL::InvalidStateError::create(realm, "Audio context is already closed."_fly_string));
  210. return JS::NonnullGCPtr { verify_cast<JS::Promise>(*promise->promise()) };
  211. }
  212. // 4. Set the [[control thread state]] flag on the AudioContext to closed.
  213. set_control_state(Bindings::AudioContextState::Closed);
  214. // 5. Queue a control message to close the AudioContext.
  215. // FIXME: Implement control message queue to run following steps on the rendering thread
  216. // FIXME: 5.1: Attempt to release system resources.
  217. // 5.2: Set the [[rendering thread state]] to "suspended".
  218. set_rendering_state(Bindings::AudioContextState::Suspended);
  219. // FIXME: 5.3: If this control message is being run in a reaction to the document being unloaded, abort this algorithm.
  220. // 5.4: queue a media element task to execute the following steps:
  221. queue_a_media_element_task([&realm, promise, this]() {
  222. // 5.4.1: Resolve promise.
  223. *promise->resolve();
  224. // 5.4.2: If the state attribute of the AudioContext is not already "closed":
  225. if (state() != Bindings::AudioContextState::Closed) {
  226. // 5.4.2.1: Set the state attribute of the AudioContext to "closed".
  227. set_control_state(Bindings::AudioContextState::Closed);
  228. }
  229. // 5.4.2.2: queue a media element task to fire an event named statechange at the AudioContext.
  230. // FIXME: Attempting to queue another task in here causes an assertion fail at Vector.h:148
  231. this->dispatch_event(DOM::Event::create(realm, HTML::EventNames::statechange));
  232. });
  233. // 6. Return promise
  234. return JS::NonnullGCPtr { verify_cast<JS::Promise>(*promise->promise()) };
  235. }
  236. void AudioContext::queue_a_media_element_task(Function<void()> steps)
  237. {
  238. auto task = HTML::Task::create(vm(), m_media_element_event_task_source.source, HTML::current_settings_object().responsible_document(), JS::create_heap_function(heap(), move(steps)));
  239. HTML::main_thread_event_loop().task_queue().add(move(task));
  240. }
  241. // FIXME: Actually implement the rendering thread
  242. bool AudioContext::start_rendering_audio_graph()
  243. {
  244. bool render_result = true;
  245. return render_result;
  246. }
  247. }