qualia_audio/
media_store.rs1use std::fs;
4use std::io::Write;
5use std::path::PathBuf;
6
7use crate::hash::media_digest;
8use crate::types::AudioError;
9
10#[derive(Debug, Clone, Copy, PartialEq, Eq)]
11#[repr(u8)]
12pub enum RetentionClass {
13 Public = 0,
14 Restricted = 1,
15 Classified = 2,
16}
17
18#[derive(Debug, Clone, PartialEq, Eq)]
19pub struct AudioMediaRecord {
20 pub digest_hex: String,
21 pub byte_len: u64,
22 pub sample_rate: u32,
23 pub channels: u16,
24 pub frames: u32,
25 pub retention: RetentionClass,
26 pub digest_u64: u64,
27}
28
29pub struct AudioMediaStore {
30 root: PathBuf,
31}
32
33impl AudioMediaStore {
34 pub fn open(root: impl Into<PathBuf>) -> Result<Self, String> {
36 let root = root.into();
37 fs::create_dir_all(root.join("audio/by-hash")).map_err(|e| e.to_string())?;
38 fs::create_dir_all(root.join("audio/index")).map_err(|e| e.to_string())?;
39 Ok(Self { root })
40 }
41
42 pub fn import_bytes(
44 &self,
45 bytes: &[u8],
46 sample_rate: u32,
47 channels: u16,
48 frames: u32,
49 retention: RetentionClass,
50 ) -> Result<AudioMediaRecord, String> {
51 if bytes.is_empty() {
52 return Err("empty audio".into());
53 }
54 let d = media_digest(bytes);
55 let digest_hex = format!("{:016x}", d.hash);
56 let a = digest_hex.get(0..2).unwrap_or("00");
57 let b = digest_hex.get(2..4).unwrap_or("00");
58 let blob = self
59 .root
60 .join("audio/by-hash")
61 .join(a)
62 .join(b)
63 .join(format!("{digest_hex}.bin"));
64 if let Some(p) = blob.parent() {
65 fs::create_dir_all(p).map_err(|e| e.to_string())?;
66 }
67 if !blob.exists() {
68 let mut f = fs::File::create(&blob).map_err(|e| e.to_string())?;
69 f.write_all(bytes).map_err(|e| e.to_string())?;
70 }
71 let rec = AudioMediaRecord {
72 digest_hex: digest_hex.clone(),
73 byte_len: bytes.len() as u64,
74 sample_rate,
75 channels,
76 frames,
77 retention,
78 digest_u64: d.hash,
79 };
80 let idx = self
81 .root
82 .join("audio/index")
83 .join(format!("{digest_hex}.txt"));
84 let line = format!(
85 "digest={} rate={} ch={} frames={} len={}\n",
86 rec.digest_hex, sample_rate, channels, frames, rec.byte_len
87 );
88 fs::write(idx, line).map_err(|e| e.to_string())?;
89 Ok(rec)
90 }
91}
92
93pub fn synth_tone_f32(freq_hz: f32, sample_rate: u32, frames: usize, amp: f32) -> Vec<f32> {
95 let mut v = vec![0.0f32; frames];
96 for i in 0..frames {
97 let t = i as f32 / sample_rate as f32;
98 v[i] = amp * (core::f32::consts::TAU * freq_hz * t).sin();
99 }
100 v
101}
102
103pub fn synth_silence(frames: usize) -> Vec<f32> {
105 vec![0.0f32; frames]
106}
107
108pub fn guard_duration_bytes(
110 frames: u64,
111 channels: u16,
112 bytes_per_sample: u32,
113 max_bytes: u64,
114) -> Result<(), AudioError> {
115 let need = frames
116 .saturating_mul(channels as u64)
117 .saturating_mul(bytes_per_sample as u64);
118 if need > max_bytes {
119 Err(AudioError::MalformedAudio)
120 } else {
121 Ok(())
122 }
123}