-
Notifications
You must be signed in to change notification settings - Fork 317
Add Source::loudness via ebur128 #895
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
4waan
wants to merge
3
commits into
RustAudio:master
Choose a base branch
from
4waan:feature/loudness
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+391
−0
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,27 @@ | ||
| use rodio::source::Source; | ||
| use std::error::Error; | ||
| use std::time::Duration; | ||
|
|
||
| fn main() -> Result<(), Box<dyn Error>> { | ||
| let stream_handle = rodio::DeviceSinkBuilder::open_default_sink()?; | ||
| let player = rodio::Player::connect_new(stream_handle.mixer()); | ||
|
|
||
| // Generate a 440 Hz sine wave and wrap it in the loudness meter. | ||
| let source = rodio::source::SineWave::new(440.0) | ||
| .take_duration(Duration::from_secs(10)) | ||
| .loudness(); | ||
|
|
||
| // periodic_access lets us read loudness readings while the audio plays. | ||
| let metered = source.periodic_access(Duration::from_millis(500), |src| { | ||
| println!( | ||
| "momentary: {:.1} LUFS short-term: {:.1} LUFS integrated: {:.1} LUFS", | ||
| src.momentary_lufs(), | ||
| src.short_term_lufs(), | ||
| src.integrated_lufs(), | ||
| ); | ||
| }); | ||
|
|
||
| player.append(metered); | ||
| player.sleep_until_end(); | ||
| Ok(()) | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,204 @@ | ||
| //! Perceptual loudness measurement (EBU R128 / ITU-R BS.1770). | ||
| //! | ||
| //! This source will pass audio through unchanged while measuring its loudness with the ebur128 crate. | ||
| //! This crate is a port of `libebur128` which produces results identical to the C reference (including K-weighting and gating). | ||
| //! | ||
| //! Read the current loudness in LUFS (Loudness Units relative to Full Scale) at any point via Loudness::momentary_lufs (in 400 ms window), | ||
| //! Loudness::short_term_lufs (in 3 s window) or Loudness::integrated_lufs (gated, whole-program). | ||
| //! | ||
| //! # Limitation right now: | ||
| //! The analyzer is configured for the stream's channel count and sample rate at the construction time. | ||
| //! Sources whose parameters change mid-stream (e.g. a queue of files with differing sample rates) | ||
| //! are not yet reconfigured; that would need the analyzer to be rebuilt at span boundaries. | ||
|
|
||
| use std::time::Duration; | ||
|
|
||
| use ebur128::{EbuR128, Mode}; | ||
|
|
||
| use super::SeekError; | ||
| use crate::common::{ChannelCount, Float, SampleRate}; | ||
| use crate::Source; | ||
|
|
||
| // ebu r128 measurement modes: momentary, short term and integrated loudness. | ||
| fn measurement_mode() -> Mode { | ||
| Mode::M | Mode::S | Mode::I | ||
| } | ||
|
|
||
| /// passthrough source that measures perceptual loudness or LUFS. | ||
| /// | ||
| /// The audio is forwarded unchanged. Read the current loudness via momentary_lufs, short_term_lufs or integrated_lufs | ||
| pub struct Loudness<I> { | ||
| input: I, | ||
| analyzer: EbuR128, | ||
| channels: usize, | ||
| // Accumulates one interleaved frame before handing it to the analyzer since ebur128 consumes whole frames! | ||
| frame: Vec<Float>, | ||
| } | ||
|
|
||
| // construct a loudness passthrough source. | ||
| pub(crate) fn loudness<I>(input: I) -> Loudness<I> | ||
| where | ||
| I: Source, | ||
| { | ||
| let channels = input.channels(); | ||
| let sample_rate = input.sample_rate(); | ||
|
|
||
| let analyzer = EbuR128::new(channels.get() as u32, sample_rate.get(), measurement_mode()) | ||
| .expect("EbuR128 accepts any non-zero channel count and sample rate"); | ||
|
|
||
| Loudness { | ||
| input, | ||
| analyzer, | ||
| channels: channels.get() as usize, | ||
| frame: Vec::with_capacity(channels.get() as usize), | ||
| } | ||
| } | ||
|
|
||
| impl<I> Loudness<I> | ||
| where | ||
| I: Source, | ||
| { | ||
| /// momentary loudness (in 400 ms window) in LUFS. | ||
| /// will return f64::NEG_INFINITY until enough audio has been measured. | ||
| #[inline] | ||
| pub fn momentary_lufs(&self) -> f64 { | ||
| self.analyzer | ||
| .loudness_momentary() | ||
| .unwrap_or(f64::NEG_INFINITY) | ||
| } | ||
|
|
||
| /// short term loudness (in 3 s window) in LUFS. | ||
| #[inline] | ||
| pub fn short_term_lufs(&self) -> f64 { | ||
| self.analyzer | ||
| .loudness_shortterm() | ||
| .unwrap_or(f64::NEG_INFINITY) | ||
| } | ||
|
|
||
| /// integrated loudness in LUFS: gated, whole program. | ||
| #[inline] | ||
| pub fn integrated_lufs(&self) -> f64 { | ||
| self.analyzer.loudness_global().unwrap_or(f64::NEG_INFINITY) | ||
| } | ||
|
|
||
| /// this returns a reference to inner source. | ||
| #[inline] | ||
| pub fn inner(&self) -> &I { | ||
| &self.input | ||
| } | ||
|
|
||
| /// returns a mutable reference to inner source. | ||
| #[inline] | ||
| pub fn inner_mut(&mut self) -> &mut I { | ||
| &mut self.input | ||
| } | ||
|
|
||
| /// to unwrap this adapter, returning the inner source. | ||
| #[inline] | ||
| pub fn into_inner(self) -> I { | ||
| self.input | ||
| } | ||
|
|
||
| // function to feed the buffered interleaved frame into the analyzer once complete. | ||
| #[inline] | ||
| fn feed(&mut self, temp: Float) { | ||
| self.frame.push(temp); | ||
|
|
||
| if self.frame.len() == self.channels { | ||
| #[cfg(not(feature = "64bit"))] | ||
| let result = self.analyzer.add_frames_f32(&self.frame); | ||
|
|
||
| #[cfg(feature = "64bit")] | ||
| let result = self.analyzer.add_frames_f64(&self.frame); | ||
|
|
||
| // error will occur here only on allocation failure. | ||
| // if we drop the frame the measurement just degrades slightly | ||
| // otherwise it could break the playback. | ||
| let _ = result; | ||
| self.frame.clear(); | ||
| } | ||
| } | ||
| } | ||
|
|
||
| impl<I> Iterator for Loudness<I> | ||
| where | ||
| I: Source, | ||
| { | ||
| type Item = I::Item; | ||
|
|
||
| #[inline] | ||
| fn next(&mut self) -> Option<Self::Item> { | ||
| let sample = self.input.next()?; | ||
| self.feed(sample); | ||
| Some(sample) | ||
| } | ||
|
|
||
| #[inline] | ||
| fn size_hint(&self) -> (usize, Option<usize>) { | ||
| self.input.size_hint() | ||
| } | ||
| } | ||
|
|
||
| impl<I> ExactSizeIterator for Loudness<I> where I: Source + ExactSizeIterator {} | ||
|
|
||
| impl<I> Source for Loudness<I> | ||
| where | ||
| I: Source, | ||
| { | ||
| #[inline] | ||
| fn current_span_len(&self) -> Option<usize> { | ||
| self.input.current_span_len() | ||
| } | ||
|
|
||
| #[inline] | ||
| fn channels(&self) -> ChannelCount { | ||
| self.input.channels() | ||
| } | ||
|
|
||
| #[inline] | ||
| fn sample_rate(&self) -> SampleRate { | ||
| self.input.sample_rate() | ||
| } | ||
|
|
||
| #[inline] | ||
| fn total_duration(&self) -> Option<Duration> { | ||
| self.input.total_duration() | ||
| } | ||
|
|
||
| #[inline] | ||
| fn try_seek(&mut self, pos: Duration) -> Result<(), SeekError> { | ||
| self.input.try_seek(pos)?; | ||
| // since loudness history is position-dependent, we restart the analyzer. | ||
| if let Ok(fresh) = EbuR128::new( | ||
| self.channels as u32, | ||
| self.input.sample_rate().get(), | ||
| measurement_mode(), | ||
| ) { | ||
| self.analyzer = fresh; | ||
| } | ||
| self.frame.clear(); | ||
| Ok(()) | ||
| } | ||
| } | ||
|
|
||
| impl<I: std::fmt::Debug> std::fmt::Debug for Loudness<I> { | ||
| fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { | ||
| f.debug_struct("Loudness") | ||
| .field("input", &self.input) | ||
| .field("channels", &self.channels) | ||
| .finish_non_exhaustive() | ||
| } | ||
| } | ||
|
|
||
| #[cfg(test)] | ||
| mod tests { | ||
| use super::*; | ||
| use crate::source::SineWave; | ||
|
|
||
| #[test] | ||
| fn passes_samples_through_unchanged() { | ||
| let original: Vec<Float> = SineWave::new(440.0).take(500).collect(); | ||
| let measured: Vec<Float> = loudness(SineWave::new(440.0)).take(500).collect(); | ||
| assert_eq!(original, measured); | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
we should soon (I've got time again) merge sources that cannot change parameters mid-stream. How do you feel about postponing this addition until we have those? Most users will probably move over to those (their API is nicer).
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
That makes total sense. the loudness source would be built cleaner on top of them!