summaryrefslogtreecommitdiff
path: root/src/flac.rs
blob: bbb2b9def065aa98b345e47c84137d49c8a3c66e (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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
use anyhow::{Result, anyhow};
use claxon::{FlacReader, FlacReaderOptions};
use flac_bound::FlacEncoder;
use md5::{Digest, Md5};
use metaflac::{Block, Tag};
use std::{
    path::Path,
    sync::{
        Arc,
        atomic::{AtomicBool, Ordering},
    },
};

pub const CURRENT_VENDOR: &str = "reference libFLAC 1.5.0 20250211";

fn write_tags(filename: impl AsRef<Path>, hash: Vec<u8>) -> Result<()> {
    let tags = Tag::read_from_path(&filename)?;
    let temp_name = filename.as_ref().with_extension("tmp");
    let mut output = Tag::read_from_path(&temp_name)?;

    let mut streaminfo = tags.get_streaminfo().unwrap().clone();

    streaminfo.md5 = hash;
    output.set_streaminfo(streaminfo);

    for block in tags.blocks() {
        match block {
            Block::VorbisComment(comment) => {
                for (key, val) in comment.comments.clone() {
                    if key.to_lowercase() != "encoder" || key.to_lowercase() != "encoded by" {
                        output.set_vorbis(key, val);
                    }
                }
            }
            Block::StreamInfo(_) | Block::Padding(_) => {}
            _ => output.push_block(block.clone()),
        }
    }

    output.write_to_path(temp_name)?;
    Ok(())
}

fn encode_file(filename: impl AsRef<Path>, handler: Arc<AtomicBool>) -> Result<bool> {
    let temp_name = filename.as_ref().with_extension("tmp");
    if temp_name.exists() {
        std::fs::remove_file(&temp_name)?;
    }
    let mut decoder = FlacReader::open(&filename)?;
    let streaminfo = decoder.streaminfo();

    let mut encoder = if let Some(encoder) = FlacEncoder::new() {
        if let Ok(encoder) = encoder
            .channels(streaminfo.channels)
            .bits_per_sample(streaminfo.bits_per_sample)
            .sample_rate(streaminfo.sample_rate)
            .compression_level(8)
            .verify(false)
            .init_file(&temp_name)
        {
            encoder
        } else {
            return Err(anyhow!("failed to create encoder"));
        }
    } else {
        return Err(anyhow!("failed to create encoder"));
    };

    let mut hasher = Md5::new();

    for samples in decoder
        .samples()
        .map(|res| {
            let sample = res.unwrap();
            match streaminfo.bits_per_sample {
                16 => {
                    hasher.update(i16::try_from(sample).unwrap().to_le_bytes());
                }
                24 => {
                    hasher.update(i24::i24::try_from_i32(sample).unwrap().to_le_bytes());
                }
                32 => {
                    hasher.update(sample.to_le_bytes());
                }
                _ => {}
            }
            sample
        })
        .collect::<Vec<i32>>()
        .chunks(streaminfo.channels as usize)
    {
        if handler.load(Ordering::SeqCst) {
            let _ = encoder.process_interleaved(samples, 1);
        } else {
            let _ = std::fs::remove_file(temp_name);
            return Ok(true);
        }
    }

    if let Err(enc) = encoder.finish() {
        return Err(anyhow!("Encoding failed:\t{:?}", enc.state()));
    }

    let hash = hasher.finalize().to_vec();
    write_tags(&filename, hash)?;
    std::fs::rename(temp_name, filename)?;
    Ok(false)
}

pub fn handle_encode(filename: impl AsRef<Path>, handler: Arc<AtomicBool>) -> Result<bool> {
    match encode_file(&filename, handler) {
        Err(error) => {
            let _ = std::fs::remove_file(filename.as_ref().with_extension("tmp"));
            Err(error)
        }
        Ok(res) => Ok(res),
    }
}

pub fn get_vendor(file: impl AsRef<Path>) -> Result<String> {
    if let Some(vendor) = FlacReader::open_ext(
        file,
        FlacReaderOptions {
            metadata_only: true,
            read_vorbis_comment: true,
        },
    )?
    .vendor()
    {
        Ok(vendor.to_string())
    } else {
        Err(anyhow!("Vendor string not found"))
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn bit16() {
        let name = "./samples/16bit.flac";
        let tempname = "./samples/16bit.flac.temp";
        std::fs::copy(name, tempname).unwrap();
        let handler = Arc::new(AtomicBool::new(true));
        encode_file(name, handler).unwrap();
        let target_md5 = FlacReader::open(tempname).unwrap().streaminfo().md5sum;
        let temp_md5 = FlacReader::open(name).unwrap().streaminfo().md5sum;

        std::fs::rename(tempname, name).unwrap();
        assert_eq!(target_md5, temp_md5);
    }

    #[test]
    fn bit24() {
        let name = "./samples/24bit.flac";
        let tempname = "./samples/24bit.flac.temp";
        std::fs::copy(name, tempname).unwrap();
        let handler = Arc::new(AtomicBool::new(true));
        encode_file(name, handler).unwrap();
        let target_md5 = FlacReader::open(tempname).unwrap().streaminfo().md5sum;
        let temp_md5 = FlacReader::open(name).unwrap().streaminfo().md5sum;

        std::fs::rename(tempname, name).unwrap();
        assert_eq!(target_md5, temp_md5);
    }

    #[test]
    fn bit32() {
        let name = "./samples/32bit.flac";
        let tempname = "./samples/32bit.flac.temp";
        std::fs::copy(name, tempname).unwrap();
        let handler = Arc::new(AtomicBool::new(true));
        encode_file(name, handler).unwrap();
        let target_md5 = FlacReader::open(tempname).unwrap().streaminfo().md5sum;
        let temp_md5 = FlacReader::open(name).unwrap().streaminfo().md5sum;

        std::fs::rename(tempname, name).unwrap();
        assert_eq!(target_md5, temp_md5);
    }
}