AudioContext.cpp 13 KB

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