mecomp_analysis/decoder/
mod.rs

1#![allow(clippy::missing_inline_in_public_items)]
2
3use std::{
4    clone::Clone,
5    marker::Send,
6    num::NonZeroUsize,
7    path::{Path, PathBuf},
8    sync::mpsc,
9    thread,
10};
11
12use log::info;
13use rayon::iter::{IntoParallelIterator, ParallelIterator};
14
15use crate::{Analysis, ResampledAudio, errors::AnalysisResult};
16
17mod mecomp;
18#[allow(clippy::module_name_repetitions)]
19pub use mecomp::{MecompDecoder, SymphoniaSource};
20
21/// Trait used to implement your own decoder.
22///
23/// The `decode` function should be implemented so that it
24/// decodes and resample a song to one channel with a sampling rate of 22050 Hz
25/// and a f32le layout.
26/// Once it is implemented, several functions
27/// to perform analysis from path(s) are available, such as
28/// [`song_from_path`](Decoder::song_from_path) and
29/// [`analyze_paths`](Decoder::analyze_paths).
30#[allow(clippy::module_name_repetitions)]
31pub trait Decoder {
32    /// A function that should decode and resample a song, optionally
33    /// extracting the song's metadata such as the artist, the album, etc.
34    ///
35    /// The output sample array should be resampled to f32le, one channel, with a sampling rate
36    /// of 22050 Hz. Anything other than that will yield wrong results.
37    ///
38    /// # Errors
39    ///
40    /// This function will return an error if the file path is invalid, if
41    /// the file path points to a file containing no or corrupted audio stream,
42    /// or if the analysis could not be conducted to the end for some reason.
43    ///
44    /// The error type returned should give a hint as to whether it was a
45    /// decoding or an analysis error.
46    fn decode(&self, path: &Path) -> AnalysisResult<ResampledAudio>;
47
48    /// Returns a decoded song's `Analysis` given a file path, or an error if the song
49    /// could not be analyzed for some reason.
50    ///
51    /// # Arguments
52    ///
53    /// * `path` - A [`Path`] holding a valid file path to a valid audio file.
54    ///
55    /// # Errors
56    ///
57    /// This function will return an error if the file path is invalid, if
58    /// the file path points to a file containing no or corrupted audio stream,
59    /// or if the analysis could not be conducted to the end for some reason.
60    ///
61    /// The error type returned should give a hint as to whether it was a
62    /// decoding or an analysis error.
63    #[inline]
64    fn analyze_path<P: AsRef<Path>>(&self, path: P) -> AnalysisResult<Analysis> {
65        self.decode(path.as_ref())?.try_into()
66    }
67
68    /// Analyze songs in `paths`, and return the `Analysis` objects through an
69    /// [`mpsc::IntoIter`].
70    ///
71    /// Returns an iterator, whose items are a tuple made of
72    /// the song path (to display to the user in case the analysis failed),
73    /// and a `Result<Analysis>`.
74    #[inline]
75    fn analyze_paths<P: Into<PathBuf>, F: IntoIterator<Item = P>>(
76        &self,
77        paths: F,
78    ) -> mpsc::IntoIter<(PathBuf, AnalysisResult<Analysis>)>
79    where
80        Self: Sync + Send,
81    {
82        let cores = thread::available_parallelism().unwrap_or(NonZeroUsize::new(1).unwrap());
83        self.analyze_paths_with_cores(paths, cores)
84    }
85
86    /// Analyze songs in `paths`, and return the `Analysis` objects through an
87    /// [`mpsc::IntoIter`]. `number_cores` sets the number of cores the analysis
88    /// will use, capped by your system's capacity. Most of the time, you want to
89    /// use the simpler `analyze_paths` functions, which autodetects the number
90    /// of cores in your system.
91    ///
92    /// Return an iterator, whose items are a tuple made of
93    /// the song path (to display to the user in case the analysis failed),
94    /// and a `Result<Analysis>`.
95    fn analyze_paths_with_cores<P: Into<PathBuf>, F: IntoIterator<Item = P>>(
96        &self,
97        paths: F,
98        number_cores: NonZeroUsize,
99    ) -> mpsc::IntoIter<(PathBuf, AnalysisResult<Analysis>)>
100    where
101        Self: Sync + Send,
102    {
103        let (tx, rx) = mpsc::channel::<(PathBuf, AnalysisResult<Analysis>)>();
104        self.analyze_paths_with_cores_with_callback(paths, number_cores, tx);
105        rx.into_iter()
106    }
107
108    /// Returns a decoded song's `Analysis` given a file path, or an error if the song
109    /// could not be analyzed for some reason.
110    ///
111    /// # Arguments
112    ///
113    /// * `path` - A [`Path`] holding a valid file path to a valid audio file.
114    /// * `callback` - A function that will be called with the path and the result of the analysis.
115    ///
116    /// # Errors
117    ///
118    /// This function will return an error if the file path is invalid, if
119    /// the file path points to a file containing no or corrupted audio stream,
120    /// or if the analysis could not be conducted to the end for some reason.
121    ///
122    /// The error type returned should give a hint as to whether it was a
123    /// decoding or an analysis error.
124    #[inline]
125    fn analyze_path_with_callback<P: AsRef<Path>>(
126        &self,
127        path: P,
128        callback: mpsc::Sender<(P, AnalysisResult<Analysis>)>,
129    ) {
130        let song = self.analyze_path(&path);
131        callback.send((path, song)).unwrap();
132
133        // We don't need to return the result of the send, as the receiver will
134    }
135
136    /// Analyze songs in `paths`, and return the `Analysis` objects through an
137    /// [`mpsc::IntoIter`].
138    ///
139    /// Returns an iterator, whose items are a tuple made of
140    /// the song path (to display to the user in case the analysis failed),
141    /// and a `Result<Analysis>`.
142    #[inline]
143    fn analyze_paths_with_callback<P: Into<PathBuf>, I: Send + IntoIterator<Item = P>>(
144        &self,
145        paths: I,
146        callback: mpsc::Sender<(PathBuf, AnalysisResult<Analysis>)>,
147    ) where
148        Self: Sync + Send,
149    {
150        let cores = thread::available_parallelism().unwrap_or(NonZeroUsize::new(1).unwrap());
151        self.analyze_paths_with_cores_with_callback(paths, cores, callback);
152    }
153
154    /// Analyze songs in `paths`, and return the `Analysis` objects through an
155    /// [`mpsc::IntoIter`]. `number_cores` sets the number of cores the analysis
156    /// will use, capped by your system's capacity. Most of the time, you want to
157    /// use the simpler `analyze_paths_with_callback` functions, which autodetects the number
158    /// of cores in your system.
159    ///
160    /// Return an iterator, whose items are a tuple made of
161    /// the song path (to display to the user in case the analysis failed),
162    /// and a `Result<Analysis>`.
163    fn analyze_paths_with_cores_with_callback<P: Into<PathBuf>, I: IntoIterator<Item = P>>(
164        &self,
165        paths: I,
166        number_cores: NonZeroUsize,
167        callback: mpsc::Sender<(PathBuf, AnalysisResult<Analysis>)>,
168    ) where
169        Self: Sync + Send,
170    {
171        let mut cores = thread::available_parallelism().unwrap_or(NonZeroUsize::new(1).unwrap());
172        if cores > number_cores {
173            cores = number_cores;
174        }
175        let paths: Vec<PathBuf> = paths.into_iter().map(Into::into).collect();
176
177        if paths.is_empty() {
178            return;
179        }
180
181        let pool = rayon::ThreadPoolBuilder::new()
182            .num_threads(cores.get())
183            .build()
184            .unwrap();
185
186        pool.install(|| {
187            paths.into_par_iter().for_each(|path| {
188                info!("Analyzing file '{path:?}'");
189                self.analyze_path_with_callback(path, callback.clone());
190            });
191        });
192    }
193}