summaryrefslogtreecommitdiff
path: root/src/flac.rs
blob: 86538811020880db1889a6f85d871b033f12dbf8 (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
use anyhow::{Result, anyhow};
use claxon::FlacReader;
use flac_bound::{FlacEncoder, WriteWrapper};
use i24::i24;
use md5::{Digest, Md5};
use metaflac::Tag;
use std::fs::File;

struct StreamConfig {
    channels: u32,
    bits_per_sample: Bps,
    sample_rate: u32,
    total_samples_estimate: u64,
}

enum Bps {
    _16,
    _24,
    _32,
}

impl Bps {
    fn new(num: u32) -> Result<Self> {
        match num {
            16 => Ok(Bps::_16),
            24 => Ok(Bps::_24),
            32 => Ok(Bps::_32),
            _ => Err(anyhow!("Invalid BPS")),
        }
    }

    fn value(&self) -> u32 {
        match self {
            Bps::_16 => 16,
            Bps::_24 => 24,
            Bps::_32 => 32,
        }
    }
}

fn process_samples_i16(
    hasher: &mut impl Digest,
    mut reader: FlacReader<File>,
    enc: &mut FlacEncoder,
    config: &StreamConfig,
) -> Result<()> {
    for samples in reader
        .samples()
        .map(|sample| sample.unwrap())
        .collect::<Vec<_>>()
        .chunks(4096)
    {
        enc.process_interleaved(samples, 4096 / config.channels)
            .unwrap();
        let _ = samples
            .iter()
            .map(|sample| hasher.update((i16::try_from(*sample)).unwrap().to_le_bytes()))
            .collect::<Vec<_>>();
    }
    Ok(())
}

fn process_samples_i24(
    hasher: &mut impl Digest,
    mut reader: FlacReader<File>,
    enc: &mut FlacEncoder,
    config: &StreamConfig,
) -> Result<()> {
    for samples in reader
        .samples()
        .map(|sample| sample.unwrap())
        .collect::<Vec<_>>()
        .chunks(4096)
    {
        enc.process_interleaved(samples, 4096 / config.channels)
            .unwrap();
        let _ = samples
            .iter()
            .map(|sample| hasher.update((i24::try_from(*sample)).unwrap().to_le_bytes()))
            .collect::<Vec<_>>();
    }
    Ok(())
}

fn process_samples_i32(
    hasher: &mut impl Digest,
    mut reader: FlacReader<File>,
    enc: &mut FlacEncoder,
    config: &StreamConfig,
) -> Result<()> {
    for samples in reader
        .samples()
        .map(|sample| sample.unwrap())
        .collect::<Vec<_>>()
        .chunks(4096)
    {
        enc.process_interleaved(samples, 4096 / config.channels)
            .unwrap();
        let _ = samples
            .iter()
            .map(|sample| hasher.update(sample.to_le_bytes()))
            .collect::<Vec<_>>();
    }
    Ok(())
}

pub fn encode_file(file: &std::path::Path) -> Result<()> {
    let reader = claxon::FlacReader::open(file)?;
    let config = StreamConfig {
        channels: reader.streaminfo().channels,
        bits_per_sample: Bps::new(reader.streaminfo().bits_per_sample)?,
        sample_rate: reader.streaminfo().sample_rate,
        total_samples_estimate: reader.streaminfo().samples.unwrap(),
    };

    let tempname = format!("{}.{}", file.display(), "tmp");

    let mut outf = File::create(&tempname)?;
    let mut outw = WriteWrapper(&mut outf);
    let mut enc = FlacEncoder::new()
        .unwrap()
        .channels(config.channels)
        .bits_per_sample(config.bits_per_sample.value())
        .sample_rate(config.sample_rate)
        .total_samples_estimate(config.total_samples_estimate)
        .compression_level(8)
        .verify(false)
        .init_write(&mut outw)
        .unwrap();

    let mut hasher = Md5::new();

    match config.bits_per_sample {
        Bps::_16 => process_samples_i16(&mut hasher, reader, &mut enc, &config)?,
        Bps::_24 => process_samples_i24(&mut hasher, reader, &mut enc, &config)?,
        Bps::_32 => process_samples_i32(&mut hasher, reader, &mut enc, &config)?,
    };

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

    /* let source_tags = Tag::read_from_path(file)?;
    let mut target_tags = Tag::read_from_path(tempname)?;


    for block in source_tags.blocks() {
        todo!()
    } */
    let mut tags = Tag::read_from_path(tempname)?;
    let mut streaminfo = tags.get_streaminfo().unwrap().clone();
    streaminfo.md5 = hasher.finalize()[..].to_vec();
    tags.set_streaminfo(streaminfo);
    tags.save()?;

    Ok(())
}