1use std::cell::Cell;
6
7use dom_struct::dom_struct;
8use js::context::JSContext;
9use js::rust::HandleObject;
10use script_bindings::codegen::GenericBindings::BaseAudioContextBinding::BaseAudioContextMethods;
11use script_bindings::reflector::reflect_dom_object_with_proto;
12use servo_media::audio::audio_node::{AudioNodeInit, AudioNodeMessage, AudioNodeType};
13use servo_media::audio::graph::NodeId;
14use servo_media::audio::oscillator_node::{
15 OscillatorNodeMessage, OscillatorNodeOptions as ServoMediaOscillatorOptions,
16 OscillatorType as ServoMediaOscillatorType,
17};
18use servo_media::audio::param::ParamType;
19use servo_media::audio::periodic_wave::PeriodicWave as ServoMediaPeriodicWave;
20
21use crate::conversions::Convert;
22use crate::dom::audio::audionode::{AudioNode, AudioNodeOptionsHelper};
23use crate::dom::audio::audioparam::AudioParam;
24use crate::dom::audio::audioscheduledsourcenode::AudioScheduledSourceNode;
25use crate::dom::audio::baseaudiocontext::BaseAudioContext;
26use crate::dom::audionode::UnwrappedAudioNodeOptions;
27use crate::dom::bindings::codegen::Bindings::AudioNodeBinding::{
28 ChannelCountMode, ChannelInterpretation,
29};
30use crate::dom::bindings::codegen::Bindings::AudioParamBinding::AutomationRate;
31use crate::dom::bindings::codegen::Bindings::OscillatorNodeBinding::{
32 OscillatorNodeMethods, OscillatorOptions, OscillatorType,
33};
34use crate::dom::bindings::error::{Error, ErrorResult, Fallible};
35use crate::dom::bindings::root::{Dom, DomRoot};
36use crate::dom::types::PeriodicWave;
37use crate::dom::window::Window;
38
39#[dom_struct]
40pub(crate) struct OscillatorNode {
41 source_node: AudioScheduledSourceNode,
42 detune: Dom<AudioParam>,
43 frequency: Dom<AudioParam>,
44 oscillator_type: Cell<OscillatorType>,
45}
46
47impl OscillatorNode {
48 fn new_inherited(
49 node_id: Option<NodeId>,
50 context: &BaseAudioContext,
51 node_options: UnwrappedAudioNodeOptions,
52 oscillator_type: OscillatorType,
53 frequency: &AudioParam,
54 detune: &AudioParam,
55 ) -> Self {
56 OscillatorNode {
57 source_node: AudioScheduledSourceNode::new_inherited(
58 node_id,
59 context,
60 node_options,
61 0, 1, ),
64 oscillator_type: Cell::new(oscillator_type),
65 frequency: Dom::from_ref(frequency),
66 detune: Dom::from_ref(detune),
67 }
68 }
69}
70
71impl OscillatorNodeMethods<crate::DomTypeHolder> for OscillatorNode {
72 fn Constructor(
74 cx: &mut JSContext,
75 window: &Window,
76 proto: Option<HandleObject>,
77 context: &BaseAudioContext,
78 options: &OscillatorOptions,
79 ) -> Fallible<DomRoot<OscillatorNode>> {
80 if matches!(options.type_, OscillatorType::Custom) && options.periodicWave.is_none() {
81 return Err(Error::InvalidState(Some(String::from(
82 "Can not set oscillator type to custom without providing a periodic wave",
83 ))));
84 }
85
86 let oscillator_type = if options.periodicWave.is_some() {
87 OscillatorType::Custom
88 } else {
89 options.type_
90 };
91
92 let node_options =
93 options
94 .parent
95 .unwrap_or(2, ChannelCountMode::Max, ChannelInterpretation::Speakers);
96 if AudioNode::channel_count_check(node_options.count) {
97 return Err(Error::NotSupported(Some(String::from(
98 "Channel count not supported",
99 ))));
100 }
101
102 let maybe_periodic_wave = options.periodicWave.as_deref().map(|x| x.convert());
103
104 let options = ServoMediaOscillatorOptions {
105 oscillator_type: convert_oscillator_options(oscillator_type, maybe_periodic_wave)?,
106 freq: *options.frequency,
107 detune: *options.detune,
108 };
109 let audio_node_init = AudioNodeInit::OscillatorNode(options);
110 let node_id =
111 AudioNode::generate_audio_node_id(cx, &node_options, audio_node_init, context);
112
113 let nyquist = (*context.SampleRate()) / 2.;
114 let frequency = AudioParam::new(
116 cx,
117 window,
118 context,
119 node_id,
120 AudioNodeType::OscillatorNode,
121 ParamType::Frequency,
122 AutomationRate::A_rate,
123 440.,
124 -nyquist,
125 nyquist,
126 );
127 let detune_max = 1200. * f32::MAX.log2();
129 let detune = AudioParam::new(
130 cx,
131 window,
132 context,
133 node_id,
134 AudioNodeType::OscillatorNode,
135 ParamType::Detune,
136 AutomationRate::A_rate,
137 0.,
138 -detune_max,
139 detune_max,
140 );
141 Ok(reflect_dom_object_with_proto(
142 cx,
143 Box::new(OscillatorNode::new_inherited(
144 node_id,
145 context,
146 node_options,
147 oscillator_type,
148 &frequency,
149 &detune,
150 )),
151 window,
152 proto,
153 ))
154 }
155
156 fn SetPeriodicWave(&self, periodic_wave: &PeriodicWave) -> ErrorResult {
158 self.oscillator_type.set(OscillatorType::Custom);
159 self.source_node
160 .node()
161 .message(AudioNodeMessage::OscillatorNode(
162 OscillatorNodeMessage::SetPeriodicWave(periodic_wave.convert()),
163 ));
164 Ok(())
165 }
166
167 fn Frequency(&self) -> DomRoot<AudioParam> {
169 DomRoot::from_ref(&self.frequency)
170 }
171
172 fn Detune(&self) -> DomRoot<AudioParam> {
174 DomRoot::from_ref(&self.detune)
175 }
176
177 fn Type(&self) -> OscillatorType {
179 self.oscillator_type.get()
180 }
181
182 fn SetType(&self, type_: OscillatorType) -> ErrorResult {
184 if type_ == OscillatorType::Custom {
185 return Err(Error::InvalidState(Some(
186 "Use setPeriodicWave() to set a custom type".into(),
187 )));
188 }
189 self.oscillator_type.set(type_);
190 self.source_node
191 .node()
192 .message(AudioNodeMessage::OscillatorNode(
193 OscillatorNodeMessage::SetOscillatorType(convert_oscillator_options(type_, None)?),
194 ));
195 Ok(())
196 }
197}
198
199fn convert_oscillator_options(
201 oscillator_type: OscillatorType,
202 maybe_periodic_wave: Option<ServoMediaPeriodicWave>,
203) -> Fallible<ServoMediaOscillatorType> {
204 match oscillator_type {
205 OscillatorType::Sine => Ok(ServoMediaOscillatorType::Sine),
206 OscillatorType::Square => Ok(ServoMediaOscillatorType::Square),
207 OscillatorType::Sawtooth => Ok(ServoMediaOscillatorType::Sawtooth),
208 OscillatorType::Triangle => Ok(ServoMediaOscillatorType::Triangle),
209 OscillatorType::Custom => {
210 let Some(periodic_wave) = maybe_periodic_wave else {
211 return Err(Error::InvalidState(Some(String::from(
212 "Can not have oscillator type custom without a periodic wave",
213 ))));
214 };
215 Ok(ServoMediaOscillatorType::Custom(periodic_wave))
216 },
217 }
218}