Skip to main content

script/dom/audio/
audiocontext.rs

1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
4
5use dom_struct::dom_struct;
6use js::context::JSContext;
7use js::realm::CurrentRealm;
8use js::rust::HandleObject;
9use script_bindings::codegen::GenericBindings::MediaElementAudioSourceNodeBinding::{
10    MediaElementAudioSourceNodeMethods, MediaElementAudioSourceOptions,
11};
12use script_bindings::codegen::GenericBindings::MediaStreamAudioDestinationNodeBinding::MediaStreamAudioDestinationNodeMethods;
13use script_bindings::codegen::GenericBindings::MediaStreamAudioSourceNodeBinding::{
14    MediaStreamAudioSourceNodeMethods, MediaStreamAudioSourceOptions,
15};
16use script_bindings::codegen::GenericBindings::MediaStreamTrackAudioSourceNodeBinding::{
17    MediaStreamTrackAudioSourceNodeMethods, MediaStreamTrackAudioSourceOptions,
18};
19use script_bindings::reflector::reflect_dom_object_with_proto;
20use script_bindings::trace::RootedTraceableBox;
21use servo_base::id::PipelineId;
22use servo_media::audio::context::{LatencyCategory, ProcessingState, RealTimeAudioContextOptions};
23
24use crate::conversions::Convert;
25use crate::dom::audio::baseaudiocontext::{BaseAudioContext, BaseAudioContextOptions};
26use crate::dom::audio::mediaelementaudiosourcenode::MediaElementAudioSourceNode;
27use crate::dom::audio::mediastreamaudiodestinationnode::MediaStreamAudioDestinationNode;
28use crate::dom::audio::mediastreamaudiosourcenode::MediaStreamAudioSourceNode;
29use crate::dom::audio::mediastreamtrackaudiosourcenode::MediaStreamTrackAudioSourceNode;
30use crate::dom::bindings::codegen::Bindings::AudioContextBinding::{
31    AudioContextLatencyCategory, AudioContextMethods, AudioContextOptions, AudioTimestamp,
32};
33use crate::dom::bindings::codegen::Bindings::AudioNodeBinding::AudioNodeOptions;
34use crate::dom::bindings::codegen::Bindings::BaseAudioContextBinding::AudioContextState;
35use crate::dom::bindings::codegen::Bindings::BaseAudioContextBinding::BaseAudioContext_Binding::BaseAudioContextMethods;
36use crate::dom::bindings::codegen::UnionTypes::AudioContextLatencyCategoryOrDouble;
37use crate::dom::bindings::error::{Error, Fallible};
38use crate::dom::bindings::inheritance::Castable;
39use crate::dom::bindings::num::Finite;
40use crate::dom::bindings::refcounted::{Trusted, TrustedPromise};
41use crate::dom::bindings::reflector::DomGlobal;
42use crate::dom::bindings::root::{Dom, DomRoot};
43use crate::dom::html::htmlmediaelement::HTMLMediaElement;
44use crate::dom::mediastream::MediaStream;
45use crate::dom::mediastreamtrack::MediaStreamTrack;
46use crate::dom::promise::{Promise, RootedPromise};
47use crate::dom::window::Window;
48
49#[dom_struct]
50pub(crate) struct AudioContext {
51    context: BaseAudioContext,
52    latency_hint: AudioContextLatencyCategory,
53    /// <https://webaudio.github.io/web-audio-api/#dom-audiocontext-baselatency>
54    base_latency: f64,
55    /// <https://webaudio.github.io/web-audio-api/#dom-audiocontext-outputlatency>
56    output_latency: f64,
57}
58
59impl AudioContext {
60    #[cfg_attr(crown, expect(crown::unrooted_must_root))]
61    /// <https://webaudio.github.io/web-audio-api/#AudioContext-constructors>
62    fn new_inherited(
63        options: &AudioContextOptions,
64        pipeline_id: PipelineId,
65    ) -> Fallible<AudioContext> {
66        // Steps 1-3.
67        let context = BaseAudioContext::new_inherited(
68            BaseAudioContextOptions::AudioContext(options.convert()),
69            pipeline_id,
70        )?;
71
72        // Step 4.1.
73        let latency_hint = match options.latencyHint {
74            AudioContextLatencyCategoryOrDouble::AudioContextLatencyCategory(category) => category,
75            AudioContextLatencyCategoryOrDouble::Double(_) => {
76                AudioContextLatencyCategory::Interactive
77            }, // TODO
78        };
79
80        // Step 4.2. The sample rate is set during the creation of the BaseAudioContext.
81        // servo-media takes care of setting the default sample rate of the output device
82        // and of resampling the audio output if needed.
83
84        // Steps 5 and 6 of the construction algorithm will happen in `resume`,
85        // after reflecting dom object.
86
87        Ok(AudioContext {
88            context,
89            latency_hint,
90            base_latency: 0.,   // TODO
91            output_latency: 0., // TODO
92        })
93    }
94
95    #[cfg_attr(crown, expect(crown::unrooted_must_root))]
96    fn new(
97        cx: &mut js::context::JSContext,
98        window: &Window,
99        proto: Option<HandleObject>,
100        options: &AudioContextOptions,
101    ) -> Fallible<DomRoot<AudioContext>> {
102        let pipeline_id = window.pipeline_id();
103        let context = AudioContext::new_inherited(options, pipeline_id)?;
104        let context = reflect_dom_object_with_proto(cx, Box::new(context), window, proto);
105        context.resume();
106        Ok(context)
107    }
108
109    fn resume(&self) {
110        // Step 5.
111        if self.context.is_allowed_to_start() {
112            // Step 6.
113            self.context.resume();
114        }
115    }
116
117    pub(crate) fn base(&self) -> DomRoot<BaseAudioContext> {
118        DomRoot::from_ref(&self.context)
119    }
120}
121
122impl AudioContextMethods<crate::DomTypeHolder> for AudioContext {
123    /// <https://webaudio.github.io/web-audio-api/#AudioContext-constructors>
124    fn Constructor(
125        cx: &mut js::context::JSContext,
126        window: &Window,
127        proto: Option<HandleObject>,
128        options: &AudioContextOptions,
129    ) -> Fallible<DomRoot<AudioContext>> {
130        AudioContext::new(cx, window, proto, options)
131    }
132
133    /// <https://webaudio.github.io/web-audio-api/#dom-audiocontext-baselatency>
134    fn BaseLatency(&self) -> Finite<f64> {
135        Finite::wrap(self.base_latency)
136    }
137
138    /// <https://webaudio.github.io/web-audio-api/#dom-audiocontext-outputlatency>
139    fn OutputLatency(&self) -> Finite<f64> {
140        Finite::wrap(self.output_latency)
141    }
142
143    /// <https://webaudio.github.io/web-audio-api/#dom-audiocontext-outputlatency>
144    fn GetOutputTimestamp(&self) -> AudioTimestamp {
145        // TODO
146        AudioTimestamp {
147            contextTime: Some(Finite::wrap(0.)),
148            performanceTime: Some(Finite::wrap(0.)),
149        }
150    }
151
152    /// <https://webaudio.github.io/web-audio-api/#dom-audiocontext-suspend>
153    fn Suspend(&self, cx: &mut CurrentRealm) -> RootedPromise {
154        // Step 1.
155        let promise = Promise::new_in_realm(cx);
156
157        // Step 2.
158        if self.context.control_thread_state() == ProcessingState::Closed {
159            promise.reject_error(
160                cx,
161                Error::InvalidState(Some("Cannot suspend a closed AudioContext".into())),
162            );
163            return promise;
164        }
165
166        // Step 3.
167        if self.context.State() == AudioContextState::Suspended {
168            promise.resolve_native(cx, &());
169            return promise;
170        }
171
172        // Steps 4 and 5.
173        let trusted_promise = TrustedPromise::from(&promise);
174        match self.context.audio_context_impl().lock().unwrap().suspend() {
175            Some(_) => {
176                let base_context = Trusted::new(&self.context);
177                let context = Trusted::new(self);
178                self.global().task_manager().dom_manipulation_task_source().queue(
179                    task!(suspend_ok: move |cx| {
180                        let base_context = base_context.root();
181                        let context = context.root();
182                        let promise = trusted_promise.root(cx);
183                        promise.resolve_native(cx, &());
184                        if base_context.State() != AudioContextState::Suspended {
185                            base_context.set_state_attribute(AudioContextState::Suspended);
186                            context.global().task_manager().dom_manipulation_task_source().queue_simple_event(
187                                context.upcast(),
188                                atom!("statechange"),
189                            );
190                        }
191                    })
192                );
193            },
194            None => {
195                // The spec does not define the error case and `suspend` should
196                // never fail, but we handle the case here for completion.
197                self.global()
198                    .task_manager()
199                    .dom_manipulation_task_source()
200                    .queue(task!(suspend_error: move |cx| {
201                        let promise = trusted_promise.root(cx);
202                        promise.reject_error(cx, Error::Type(c"Something went wrong".to_owned()));
203                    }));
204            },
205        };
206
207        // Step 6.
208        promise
209    }
210
211    /// <https://webaudio.github.io/web-audio-api/#dom-audiocontext-close>
212    fn Close(&self, cx: &mut CurrentRealm) -> RootedPromise {
213        // Step 1.
214        let promise = Promise::new_in_realm(cx);
215
216        // Step 2.
217        if self.context.control_thread_state() == ProcessingState::Closed {
218            promise.reject_error(
219                cx,
220                Error::InvalidState(Some("AudioContext is already closed".into())),
221            );
222            return promise;
223        }
224
225        // Step 3.
226        if self.context.State() == AudioContextState::Closed {
227            promise.resolve_native(cx, &());
228            return promise;
229        }
230
231        // Steps 4 and 5.
232        let trusted_promise = TrustedPromise::from(&promise);
233        match self.context.audio_context_impl().lock().unwrap().close() {
234            Some(_) => {
235                let base_context = Trusted::new(&self.context);
236                let context = Trusted::new(self);
237                self.global().task_manager().dom_manipulation_task_source().queue(
238                    task!(suspend_ok: move |cx| {
239                        let base_context = base_context.root();
240                        let context = context.root();
241                        let promise = trusted_promise.root(cx);
242                        promise.resolve_native(cx, &());
243                        if base_context.State() != AudioContextState::Closed {
244                            base_context.set_state_attribute(AudioContextState::Closed);
245                            context.global().task_manager().dom_manipulation_task_source().queue_simple_event(
246                                context.upcast(),
247                                atom!("statechange"),
248                            );
249                        }
250                    })
251                );
252            },
253            None => {
254                // The spec does not define the error case and `suspend` should
255                // never fail, but we handle the case here for completion.
256                self.global()
257                    .task_manager()
258                    .dom_manipulation_task_source()
259                    .queue(task!(suspend_error: move |cx| {
260                        let promise = trusted_promise.root(cx);
261                        promise.reject_error(cx, Error::Type(c"Something went wrong".to_owned()));
262                    }));
263            },
264        };
265
266        // Step 6.
267        promise
268    }
269
270    /// <https://webaudio.github.io/web-audio-api/#dom-audiocontext-createmediaelementsource>
271    fn CreateMediaElementSource(
272        &self,
273        cx: &mut JSContext,
274        media_element: &HTMLMediaElement,
275    ) -> Fallible<DomRoot<MediaElementAudioSourceNode>> {
276        let global = self.global();
277        let window = global.as_window();
278        let options = RootedTraceableBox::new(MediaElementAudioSourceOptions {
279            mediaElement: Dom::from_ref(media_element),
280        });
281        MediaElementAudioSourceNode::Constructor(cx, window, None, self, &options)
282    }
283
284    /// <https://webaudio.github.io/web-audio-api/#dom-audiocontext-createmediastreamsource>
285    fn CreateMediaStreamSource(
286        &self,
287        cx: &mut JSContext,
288        stream: &MediaStream,
289    ) -> Fallible<DomRoot<MediaStreamAudioSourceNode>> {
290        let global = self.global();
291        let window = global.as_window();
292        let options = RootedTraceableBox::new(MediaStreamAudioSourceOptions {
293            mediaStream: Dom::from_ref(stream),
294        });
295        MediaStreamAudioSourceNode::Constructor(cx, window, None, self, &options)
296    }
297
298    /// <https://webaudio.github.io/web-audio-api/#dom-audiocontext-createmediastreamtracksource>
299    fn CreateMediaStreamTrackSource(
300        &self,
301        cx: &mut JSContext,
302        track: &MediaStreamTrack,
303    ) -> Fallible<DomRoot<MediaStreamTrackAudioSourceNode>> {
304        let global = self.global();
305        let window = global.as_window();
306        let options = RootedTraceableBox::new(MediaStreamTrackAudioSourceOptions {
307            mediaStreamTrack: Dom::from_ref(track),
308        });
309        MediaStreamTrackAudioSourceNode::Constructor(cx, window, None, self, &options)
310    }
311
312    /// <https://webaudio.github.io/web-audio-api/#dom-audiocontext-createmediastreamdestination>
313    fn CreateMediaStreamDestination(
314        &self,
315        cx: &mut JSContext,
316    ) -> Fallible<DomRoot<MediaStreamAudioDestinationNode>> {
317        let global = self.global();
318        let window = global.as_window();
319        MediaStreamAudioDestinationNode::Constructor(
320            cx,
321            window,
322            None,
323            self,
324            &AudioNodeOptions::empty(),
325        )
326    }
327}
328
329impl Convert<LatencyCategory> for AudioContextLatencyCategory {
330    fn convert(self) -> LatencyCategory {
331        match self {
332            AudioContextLatencyCategory::Balanced => LatencyCategory::Balanced,
333            AudioContextLatencyCategory::Interactive => LatencyCategory::Interactive,
334            AudioContextLatencyCategory::Playback => LatencyCategory::Playback,
335        }
336    }
337}
338
339impl Convert<RealTimeAudioContextOptions> for &AudioContextOptions {
340    fn convert(self) -> RealTimeAudioContextOptions {
341        RealTimeAudioContextOptions {
342            sample_rate: *self.sampleRate.unwrap_or(Finite::wrap(44100.)),
343            latency_hint: match self.latencyHint {
344                AudioContextLatencyCategoryOrDouble::AudioContextLatencyCategory(category) => {
345                    category.convert()
346                },
347                AudioContextLatencyCategoryOrDouble::Double(_) => LatencyCategory::Interactive, // TODO
348            },
349        }
350    }
351}