audio_visualizer/waveform/
png_file.rs

1/*
2MIT License
3
4Copyright (c) 2021 Philipp Schuster
5
6Permission is hereby granted, free of charge, to any person obtaining a copy
7of this software and associated documentation files (the "Software"), to deal
8in the Software without restriction, including without limitation the rights
9to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10copies of the Software, and to permit persons to whom the Software is
11furnished to do so, subject to the following conditions:
12
13The above copyright notice and this permission notice shall be included in all
14copies or substantial portions of the Software.
15
16THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22SOFTWARE.
23*/
24//! Static waveform visualization which exports the waveform to a PNG file.
25
26use crate::util::png::write_png_file_rgb_tuples;
27use crate::Channels;
28use std::path::PathBuf;
29
30/// Visualizes audio as a waveform in a png file in the most simple way.
31/// There are no axes. If the audio data is mono, it creates one file.
32/// If the data is stereo, it creates two files (with "left_" and "right_" prefix).
33pub fn waveform_static_png_visualize(
34    samples: &[i16],
35    channels: Channels,
36    directory: &str,
37    filename: &str,
38) {
39    let image_width = 1500;
40    let image_height = 200;
41    if channels.is_stereo() {
42        assert_eq!(
43            0,
44            samples.len() % 2,
45            "If stereo is provided, the length of the audio data must be even!"
46        );
47        let (left, right) = channels.stereo_interleavement().to_channel_data(samples);
48        waveform_static_png_visualize(
49            &left,
50            Channels::Mono,
51            directory,
52            &format!("left_{}", filename),
53        );
54        waveform_static_png_visualize(
55            &right,
56            Channels::Mono,
57            directory,
58            &format!("right_{}", filename),
59        );
60        return;
61    }
62
63    // needed for offset calculation; width per sample
64    let width_per_sample = image_width as f64 / samples.len() as f64;
65    // height in pixel per possible value of a sample; counts in that the y axis lays in the middle
66    let height_per_max_amplitude = image_height as f64 / 2_f64 / i16::max_value() as f64;
67
68    // RGB image data
69    let mut image = vec![vec![(255, 255, 255); image_width]; image_height];
70    for (sample_index, sample_value) in samples.iter().enumerate() {
71        // x offset; from left
72        let x = (sample_index as f64 * width_per_sample) as usize;
73        // y offset; from top
74        // image_height/2: there is our y-axis
75        let sample_value = *sample_value as f64 * -1.0; // y axis grows downwards
76        let mut y = ((image_height / 2) as f64 + sample_value * height_per_max_amplitude) as usize;
77
78        // due to rounding it can happen that we get out of bounds
79        if y == image_height {
80            y -= 1;
81        }
82
83        image[y][x] = (0, 0, 0);
84    }
85
86    let mut path = PathBuf::new();
87    path.push(directory);
88    path.push(filename);
89    write_png_file_rgb_tuples(&path, &image);
90}
91
92#[cfg(test)]
93mod tests {
94    use super::*;
95    use crate::tests::testutil::{TEST_OUT_DIR, TEST_SAMPLES_DIR};
96    use crate::ChannelInterleavement;
97    use minimp3::{Decoder as Mp3Decoder, Error as Mp3Error, Frame as Mp3Frame};
98    use std::fs::File;
99
100    /// This test works, if it doesn't panic.
101    #[test]
102    fn test_no_out_of_bounds_panic() {
103        let audio_data = vec![i16::MAX, i16::MIN];
104        waveform_static_png_visualize(
105            &audio_data,
106            Channels::Mono,
107            TEST_OUT_DIR,
108            "sample_1_waveform-test-out-of-bounds-check.png",
109        );
110    }
111
112    #[test]
113    fn test_visualize_png_output() {
114        let mut path = PathBuf::new();
115        path.push(TEST_SAMPLES_DIR);
116        path.push("sample_1.mp3");
117        let mut decoder = Mp3Decoder::new(File::open(path).unwrap());
118
119        let mut lrlr_mp3_samples = vec![];
120        loop {
121            match decoder.next_frame() {
122                Ok(Mp3Frame {
123                    data: samples_of_frame,
124                    ..
125                }) => {
126                    for sample in samples_of_frame {
127                        lrlr_mp3_samples.push(sample);
128                    }
129                }
130                Err(Mp3Error::Eof) => break,
131                Err(e) => panic!("{:?}", e),
132            }
133        }
134
135        waveform_static_png_visualize(
136            &lrlr_mp3_samples,
137            Channels::Stereo(ChannelInterleavement::LRLR),
138            TEST_OUT_DIR,
139            "waveform_static_png_visualize_example.png",
140        );
141    }
142}