AudioContext.cpp 13 KB

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