Skip to content

Commit 3c0278f

Browse files
committed
Panic when calling suspend for problematic suspendTime, add tests
1 parent 63767d2 commit 3c0278f

File tree

1 file changed

+37
-4
lines changed

1 file changed

+37
-4
lines changed

src/context/offline.rs

Lines changed: 37 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -172,6 +172,19 @@ impl OfflineAudioContext {
172172
self.length
173173
}
174174

175+
#[track_caller]
176+
fn calculate_suspend_frame(&self, suspend_time: f64) -> usize {
177+
assert!(
178+
suspend_time >= 0.,
179+
"InvalidStateError: suspendTime cannot be negative"
180+
);
181+
assert!(
182+
suspend_time < self.length as f64 / self.sample_rate() as f64,
183+
"InvalidStateError: suspendTime cannot be greater than or equal to the total render duration"
184+
);
185+
(suspend_time * self.base.sample_rate() as f64 / RENDER_QUANTUM_SIZE as f64).ceil() as usize
186+
}
187+
175188
/// Schedules a suspension of the time progression in the audio context at the specified time
176189
/// and returns a promise
177190
///
@@ -214,8 +227,7 @@ impl OfflineAudioContext {
214227
/// assert_eq!(buffer.length(), 512);
215228
/// ```
216229
pub async fn suspend(&self, suspend_time: f64) {
217-
let quantum = (suspend_time * self.base.sample_rate() as f64 / RENDER_QUANTUM_SIZE as f64)
218-
.ceil() as usize;
230+
let quantum = self.calculate_suspend_frame(suspend_time);
219231

220232
let (sender, receiver) = oneshot::channel();
221233

@@ -284,8 +296,7 @@ impl OfflineAudioContext {
284296
suspend_time: f64,
285297
callback: F,
286298
) {
287-
let quantum = (suspend_time * self.base.sample_rate() as f64 / RENDER_QUANTUM_SIZE as f64)
288-
.ceil() as usize;
299+
let quantum = self.calculate_suspend_frame(suspend_time);
289300

290301
let mut lock = self.renderer.lock().unwrap();
291302
let renderer = match lock.as_mut() {
@@ -411,4 +422,26 @@ mod tests {
411422
abs_all <= 0.
412423
);
413424
}
425+
426+
#[test]
427+
#[should_panic]
428+
fn test_suspend_negative_panics() {
429+
let mut context = OfflineAudioContext::new(2, 128, 44_100.);
430+
context.suspend_sync(-1.0, |_| ());
431+
}
432+
433+
#[test]
434+
#[should_panic]
435+
fn test_suspend_after_duration_panics() {
436+
let mut context = OfflineAudioContext::new(2, 128, 44_100.);
437+
context.suspend_sync(1.0, |_| ());
438+
}
439+
440+
#[test]
441+
#[should_panic]
442+
fn test_suspend_after_render_panics() {
443+
let mut context = OfflineAudioContext::new(2, 128, 44_100.);
444+
let _ = context.start_rendering_sync();
445+
context.suspend_sync(0.0, |_| ());
446+
}
414447
}

0 commit comments

Comments
 (0)