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