summaryrefslogtreecommitdiff
path: root/src/output/mod.rs
blob: 520a500f3275f52e6e57d9f972037a58fe2ff893 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
//! This file implements the interface to save waves into a file.

use std::{
    error::Error,
    fmt::{self, Display, Formatter},
    io::{self, Write},
};

use super::*;

#[derive(Debug)]
pub enum OutputError {
    Io(std::io::Error),
    FFMpeg(String),
    EmptyWaves,
}

impl Display for OutputError {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        match self {
            Self::Io(e) => write!(f, "io: {e}"),
            Self::EmptyWaves => write!(f, "empty waves"),
            OutputError::FFMpeg(s) => write!(f, "FFMPEG error: {s}"),
        }
    }
}

impl Error for OutputError {}

impl From<io::Error> for OutputError {
    fn from(io: io::Error) -> Self {
        Self::Io(io)
    }
}

/// A type that implements this trait implements a generic function
/// for saving waves into files.
pub trait Output {
    /// Save waves DATA with RATE samples per second into a file with
    /// NAME.
    fn save(&self, data: Wave, rate: Samples, name: &str) -> Result<(), OutputError>;
}

/// A dummy struct to hold a generic function for saving waves.
#[derive(Default)]
pub struct PlainOutput {}

impl Output for PlainOutput {
    fn save(&self, data: Wave, _rate: Samples, name: &str) -> Result<(), OutputError> {
        if data.is_empty() {
            return Err(OutputError::EmptyWaves);
        }

        let bytes: Vec<u8> = data.iter().flat_map(|pulse| pulse.to_le_bytes()).collect();

        let mut file = std::fs::OpenOptions::new()
            .create(true)
            .write(true)
            .open(name)?;

        file.write_all(&bytes)?;

        Ok(())
    }
}

#[cfg(feature = "ffmpeg")]
pub mod ffmpeg_output;