flac/
lib.rs

1#![allow(unused_imports)]
2pub mod flac;
3
4use flac::*;
5
6pub use flac::{FlacCompression, FlacEncoderParams};
7pub use flac::{FlacAudioForm, SamplesInfo};
8pub use flac::{FlacReadStatus, FlacInternalDecoderError};
9pub use flac::FlacError;
10pub use flac::{FlacEncoderError, FlacDecoderError};
11pub use flac::{FlacEncoderErrorCode, FlacDecoderErrorCode};
12pub use flac::{FlacEncoderInitError, FlacDecoderInitError};
13pub use flac::{FlacEncoderInitErrorCode, FlacDecoderInitErrorCode};
14pub use flac::{FlacEncoderUnmovable, FlacEncoder};
15pub use flac::{FlacDecoderUnmovable, FlacDecoder};
16
17#[test]
18fn test() {
19    use std::{io::{self, Read, Write, Seek, SeekFrom, BufReader, BufWriter}, cmp::Ordering, fs::File};
20
21    // Open the FLAC file for decoding using the `BufReader`
22    type ReaderType = BufReader<File>;
23    let mut reader: ReaderType = BufReader::new(File::open("test.flac").unwrap());
24
25    // Retrieve the file length
26    let length = {
27        reader.seek(SeekFrom::End(0)).unwrap();
28        let ret = reader.stream_position().unwrap();
29        reader.seek(SeekFrom::Start(0)).unwrap();
30        ret
31    };
32
33    // Open the FLAC file for encoding using the `BufWriter`
34    type WriterType = BufWriter<File>;
35    let mut writer: WriterType = BufWriter::new(File::create("output.flac").unwrap());
36
37    // Prepare to get the samples
38    let mut pcm_frames = Vec::<Vec<i16>>::new();
39
40    // There is an encoder to save samples to another FLAC file
41    // But currently we don't know the source FLAC file spec (channels, sample rate, etc.)
42    // So we just guess it.
43    // Let's create the encoder now
44    let mut encoder = FlacEncoder::new(
45        &mut writer,
46        // on_write
47        Box::new(|writer: &mut WriterType, data: &[u8]| -> Result<(), io::Error> {
48            writer.write_all(data)
49        }),
50        // on_seek
51        Box::new(|writer: &mut WriterType, position: u64| -> Result<(), io::Error> {
52            writer.seek(SeekFrom::Start(position))?;
53            Ok(())
54        }),
55        // on_tell
56        Box::new(|writer: &mut WriterType| -> Result<u64, io::Error> {
57            writer.stream_position()
58        }),
59        &FlacEncoderParams {
60            verify_decoded: false,
61            compression: FlacCompression::Level8,
62            channels: 2,
63            sample_rate: 44100,
64            bits_per_sample: 16,
65            total_samples_estimate: 0
66        }
67    ).unwrap();
68    encoder.initialize().unwrap();
69
70    // Create a decoder to decode the test file.
71    let mut decoder = FlacDecoder::new(
72        &mut reader,
73        // on_read
74        Box::new(|reader: &mut ReaderType, data: &mut [u8]| -> (usize, FlacReadStatus) {
75            let to_read = data.len();
76            match reader.read(data) {
77                Ok(size) => {
78                    match size.cmp(&to_read) {
79                        Ordering::Equal => (size, FlacReadStatus::GoOn),
80                        Ordering::Less => (size, FlacReadStatus::Eof),
81                        Ordering::Greater => panic!("`reader.read()` returns a size greater than the desired size."),
82                    }
83                },
84                Err(e) => {
85                    eprintln!("on_read(): {:?}", e);
86                    (0, FlacReadStatus::Abort)
87                }
88            }
89        }),
90        // on_seek
91        Box::new(|reader: &mut ReaderType, position: u64| -> Result<(), io::Error> {
92            reader.seek(SeekFrom::Start(position))?;
93            Ok(())
94        }),
95        // on_tell
96        Box::new(|reader: &mut ReaderType| -> Result<u64, io::Error> {
97            reader.stream_position()
98        }),
99        // on_length
100        Box::new(|_reader: &mut ReaderType| -> Result<u64, io::Error>{
101            Ok(length)
102        }),
103        // on_eof
104        Box::new(|reader: &mut ReaderType| -> bool {
105            reader.stream_position().unwrap() >= length
106        }),
107        // on_write
108        Box::new(|samples: &[Vec<i32>], sample_info: &SamplesInfo| -> Result<(), io::Error>{
109            if sample_info.bits_per_sample != 16 {
110                panic!("The test function only tests 16-bit per sample FLAC files.")
111            }
112            let pcm_converted: Vec<Vec<i16>> = samples.iter().map(|frame: &Vec<i32>|{
113                frame.into_iter().map(|x32|{*x32 as i16}).collect()
114            }).collect();
115            pcm_frames.extend(pcm_converted);
116
117            // The encoder wants the `i32` for samples to be encoded so we convert the PCM samples back to `i32` format for the encoder.
118            let i32pcm: Vec::<Vec<i32>> = pcm_frames.iter().map(|frame: &Vec<i16>|{
119                frame.into_iter().map(|x16|{*x16 as i32}).collect()
120            }).collect();
121            encoder.write_frames(&i32pcm).unwrap();
122            pcm_frames.clear();
123
124            Ok(())
125        }),
126        // on_error
127        Box::new(|error: FlacInternalDecoderError| {
128            panic!("{error}");
129        }),
130        true, // md5_checking
131        false, // scale_to_i32_range
132        FlacAudioForm::FrameArray
133    ).unwrap();
134
135    decoder.decode_all().unwrap();
136    decoder.finalize();
137    encoder.finalize();
138}
139