-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstream_info.rs
More file actions
159 lines (137 loc) · 6.12 KB
/
stream_info.rs
File metadata and controls
159 lines (137 loc) · 6.12 KB
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
use super::blocks::get_header;
use std::io::{self, Read};
#[derive(Debug)]
pub struct StreamInfo {
pub min_block_size: u16,
pub max_block_size: u16,
pub min_frame_size: u32,
pub max_frame_size: u32,
pub sample_rate: u64,
pub channels: u8,
pub bps: u8,
pub total_samples: u64,
pub checksum_combined: [u8; 16],
}
impl StreamInfo {
pub fn process_stream_info_block<R: Read>(reader: &mut R) -> StreamInfo {
let streaminfo_header = get_header(reader).expect("Error get_header!");
// первый всегда идет STREAMINFO
// поменять потом с индексов на именованные поля
if streaminfo_header.1 != 0 {
panic!("Expect STREAMINFO (type 0)");
}
// создаю вектор в длину блока и читаю его содержимое
let mut streaminfo = vec![0u8; streaminfo_header.2 as usize];
reader.read_exact(&mut streaminfo).unwrap();
// чтение информация из STREAMINFO
// собираю значения из байт массива согласно докам
// TODO: переписать на from_be_bytes где возможно
let min_block_size = u16::from_be_bytes(streaminfo[0..2].try_into().unwrap());
let max_block_size = u16::from_be_bytes(streaminfo[2..4].try_into().unwrap());
let min_frame_size = u32::from_be_bytes([0, streaminfo[4], streaminfo[5], streaminfo[6]]);
let max_frame_size = u32::from_be_bytes([0, streaminfo[7], streaminfo[8], streaminfo[9]]);
// беру сразу 8 байт с 10 по 17 и комбинирую в одно 64 битное число
// так как дальше идут значения которые занимают биты в этих байтах
// так удобнее всего двигаться внутри байтов
let combinated = u64::from_be_bytes(streaminfo[10..18].try_into().unwrap());
// получение 16 байт контрольной суммы MD5
let checksum_combined: [u8; 16] = streaminfo[18..34].try_into().unwrap();
// так как значение занимает 20 то сдвигаю на 44 бита вправо и маской беру 20 бит
let sample_rate = (combinated >> 44) & 0xFFFFF; // 20 bit
// сдвигаю на 41 бит и маской беру 3 бита
let channels = (combinated >> 41) & 0x7; // 3 bit
// сдвигаю на 36 бит и маской беру 5 бит
let bps = (combinated >> 36) & 0x1F; // 5 bit
// все что осталось забираю маской - 0xF_FFFF_FFFF
let total_samples = combinated & 0xF_FFFF_FFFF; // 36 bit
Self {
min_block_size,
max_block_size,
min_frame_size,
max_frame_size,
sample_rate,
channels: (channels + 1) as u8,
bps: (bps + 1) as u8,
total_samples,
checksum_combined,
}
}
}
pub fn check_flac_header<R: Read>(reader: &mut R) -> io::Result<()> {
let mut format_part = [0u8; 4];
reader.read_exact(&mut format_part)?;
if &format_part != b"fLaC" {
return Err(io::Error::new(
io::ErrorKind::InvalidData,
"Not a FLAC file",
));
}
Ok(())
}
#[cfg(test)]
mod tests {
use std::io::Cursor;
use super::*;
#[test]
#[should_panic(expected = "Expect STREAMINFO (type 0)")] // должна случиться паника
fn test_process_stream_info_block_invalid_header() {
// данные -> [неправильный тип padding 1, длина 0, 0, 1]
let mut data = Cursor::new(vec![0x01, 0x00, 0x00, 0x01, 0x00]);
StreamInfo::process_stream_info_block(&mut data);
}
#[test]
fn test_process_stream_info_block_full_check() {
let mut data = Vec::new();
// STREAMINFO header (type 0, length 34)
data.extend_from_slice(&[0x00, 0x00, 0x00, 0x22]);
// min block size (2 байта)
data.extend_from_slice(&[0x10, 0x00]);
// max block size (2 байта)
data.extend_from_slice(&[0x10, 0x00]);
// min frame size (3 байта)
data.extend_from_slice(&[0x00, 0x00, 0x01]);
// max frame size (3 байта)
data.extend_from_slice(&[0x00, 0x00, 0x02]);
let sample_rate: u64 = 44100;
let channels: u64 = 2;
let bps: u64 = 15;
let total_samples: u64 = 1000;
let combined: u64 = (sample_rate << 44) | (channels << 41) | (bps << 36) | total_samples;
data.extend_from_slice(&combined.to_be_bytes());
// MD5 (16 байт)
let md5 = [0xAB; 16];
data.extend_from_slice(&md5);
// проверка
let mut reader = Cursor::new(data);
let info = StreamInfo::process_stream_info_block(&mut reader);
assert_eq!(info.min_block_size, 0x1000);
assert_eq!(info.max_block_size, 0x1000);
assert_eq!(info.min_frame_size, 1);
assert_eq!(info.max_frame_size, 2);
assert_eq!(info.sample_rate, 44100);
assert_eq!(info.channels, 3); // channels + 1 = 2 + 1 = 3
assert_eq!(info.bps, 16); // bps + 1 = 15 + 1 = 16
assert_eq!(info.total_samples, 1000);
assert_eq!(info.checksum_combined, [0xAB; 16]);
}
#[test]
fn test_check_flac_header_valid() {
let mut data = Cursor::new("fLaCotherdataidkrandom");
let result = check_flac_header(&mut data);
assert!(result.is_ok());
}
#[test]
fn test_check_flac_header_invalid() {
let mut data = Cursor::new("NotFLACdatahere");
let result = check_flac_header(&mut data);
assert!(result.is_err());
assert_eq!(result.unwrap_err().kind(), io::ErrorKind::InvalidData);
}
#[test]
fn test_check_flac_header_too_short() {
let mut data = Cursor::new("fLa");
let result = check_flac_header(&mut data);
assert!(result.is_err());
assert_eq!(result.unwrap_err().kind(), io::ErrorKind::UnexpectedEof);
}
}