Skip to content

Commit 338d0d8

Browse files
committed
better-limit-buffersize
1 parent cdbbeba commit 338d0d8

2 files changed

Lines changed: 17 additions & 3 deletions

File tree

src/math.rs

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -126,6 +126,20 @@ pub(crate) fn duration_to_float(duration: Duration) -> Float {
126126
}
127127
}
128128

129+
#[must_use]
130+
pub(crate) fn nearest_multiple_of_two(n: u32) -> u32 {
131+
if n <= 1 {
132+
return 1;
133+
}
134+
let next = n.next_power_of_two();
135+
let prev = next >> 1;
136+
if n - prev <= next - n {
137+
prev
138+
} else {
139+
next
140+
}
141+
}
142+
129143
/// Utility macro for getting a `NonZero` from a literal. Especially
130144
/// useful for passing in `ChannelCount` and `Samplerate`.
131145
/// Equivalent to: `const { core::num::NonZero::new($n).unwrap() }`

src/stream.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
//! There is also a convenience function `play` for using that output mixer to
77
//! play a single sound.
88
use crate::common::{assert_error_traits, ChannelCount, SampleRate};
9-
use crate::math::nz;
9+
use crate::math::{nearest_multiple_of_two, nz};
1010
use crate::mixer::{mixer, Mixer};
1111
use crate::player::Player;
1212
use crate::{decoder, Source};
@@ -191,9 +191,9 @@ impl DeviceSinkBuilder {
191191
.with_device(device)
192192
.with_supported_config(&default_config);
193193

194-
// minimum 40ms of audio
194+
// aim for 50ms of audio
195195
let sample_rate = device.config.sample_rate().get();
196-
let safe_buffer_size = (sample_rate / (1000 / 40)).next_power_of_two();
196+
let safe_buffer_size = nearest_multiple_of_two(sample_rate / (1000 / 50));
197197

198198
// This is suboptimal, the builder might still change the sample rate or
199199
// channel count which would throw the buffer size off. We have fixed

0 commit comments

Comments
 (0)