1use crate::audiovae::{Conv1d, ConvT1d, Snake};
23use crate::pipeline::masked::SetMask;
24use crate::pipeline::Pipeline;
25use crate::pool::Pool;
26use crate::sampler::SplitMix64;
27use cortiq_core::CmfModel;
28use serde_json::Value;
29use std::sync::Arc;
30
31pub const SAMPLE_RATE: u32 = 24_000;
33
34pub fn is_omnivoice(model: &CmfModel) -> bool {
36 model.header.provenance.as_ref().is_some_and(|p| p.get("omnivoice").is_some())
37}
38
39#[derive(Clone, Debug)]
41pub struct OmniVoiceConfig {
42 pub books: usize,
44 pub vocab: usize,
46 pub mask_id: u32,
47 pub sample_rate: usize,
48 pub hop: usize,
50 pub upsampling: Vec<usize>,
52}
53
54impl OmniVoiceConfig {
55 pub fn from_model(model: &CmfModel) -> Result<Self, String> {
56 let p = model
57 .header
58 .provenance
59 .as_ref()
60 .and_then(|p| p.get("omnivoice"))
61 .ok_or("omnivoice: the file has no provenance.omnivoice")?;
62 let c = p.get("config").ok_or("omnivoice: provenance has no config")?;
63 let k = p.get("codec").ok_or("omnivoice: provenance has no codec config")?;
64 let u = |v: &Value, key: &str, d: usize| v.get(key).and_then(|x| x.as_u64()).map_or(d, |x| x as usize);
65 let ac = k.get("acoustic_model_config").cloned().unwrap_or(Value::Null);
66 let upsampling: Vec<usize> = ac
67 .get("upsampling_ratios")
68 .and_then(|v| v.as_array())
69 .map(|a| a.iter().filter_map(|x| x.as_u64().map(|x| x as usize)).collect())
70 .unwrap_or_else(|| vec![8, 5, 4, 2, 3]);
71 let cfg = Self {
72 books: u(c, "num_audio_codebook", 8),
73 vocab: u(c, "audio_vocab_size", 1025),
74 mask_id: u(c, "audio_mask_id", 1024) as u32,
75 sample_rate: u(k, "sample_rate", 24_000),
76 hop: upsampling.iter().product(),
77 upsampling,
78 };
79 if cfg.books == 0 || cfg.mask_id as usize >= cfg.vocab || cfg.hop == 0 {
80 return Err(format!("omnivoice: implausible config {cfg:?}"));
81 }
82 Ok(cfg)
83 }
84
85 pub fn frame_rate(&self) -> f64 {
87 self.sample_rate as f64 / self.hop as f64
88 }
89}
90
91#[derive(Clone, Debug)]
93pub struct GenConfig {
94 pub steps: usize,
95 pub guidance: f32,
96 pub t_shift: f32,
97 pub layer_penalty: f32,
98 pub position_temperature: f32,
100 pub class_temperature: f32,
102 pub denoise: bool,
103 pub postprocess: bool,
104 pub seed: u64,
105}
106
107impl Default for GenConfig {
108 fn default() -> Self {
109 Self {
110 steps: 32,
111 guidance: 2.0,
112 t_shift: 0.1,
113 layer_penalty: 5.0,
114 position_temperature: 5.0,
115 class_temperature: 0.0,
116 denoise: true,
117 postprocess: true,
118 seed: 0,
119 }
120 }
121}
122
123#[derive(Clone, Debug)]
125pub struct VoicePrompt {
126 pub codes: Vec<Vec<u32>>,
127 pub text: String,
128 pub rms: f32,
129}
130
131pub struct Request<'a> {
132 pub text: &'a str,
133 pub language: Option<&'a str>,
135 pub instruct: Option<&'a str>,
137 pub voice: Option<&'a VoicePrompt>,
138 pub duration: Option<f32>,
140 pub speed: Option<f32>,
141 pub generation: GenConfig,
142}
143
144pub fn resolve_language(lang: Option<&str>) -> Option<String> {
148 let l = lang?.trim();
149 if l.is_empty() || l.eq_ignore_ascii_case("none") {
150 return None;
151 }
152 let langs = crate::omnivoice_langs::LANGS;
153 if langs.iter().any(|(_, id)| *id == l) {
154 return Some(l.to_string());
155 }
156 let key = l.to_lowercase();
157 if let Some((_, id)) = langs.iter().find(|(n, _)| *n == key) {
158 return Some(id.to_string());
159 }
160 tracing::warn!("omnivoice: language {l:?} is not recognized; speaking without a language id");
161 None
162}
163
164const CATEGORIES_EN_ZH: [&[(&str, &str)]; 4] = [
165 &[("male", "男"), ("female", "女")],
166 &[("child", "儿童"), ("teenager", "少年"), ("young adult", "青年"), ("middle-aged", "中年"), ("elderly", "老年")],
167 &[
168 ("very low pitch", "极低音调"),
169 ("low pitch", "低音调"),
170 ("moderate pitch", "中音调"),
171 ("high pitch", "高音调"),
172 ("very high pitch", "极高音调"),
173 ],
174 &[("whisper", "耳语")],
175];
176const ACCENTS: [&str; 10] = [
177 "american accent",
178 "british accent",
179 "australian accent",
180 "chinese accent",
181 "canadian accent",
182 "indian accent",
183 "korean accent",
184 "portuguese accent",
185 "russian accent",
186 "japanese accent",
187];
188const DIALECTS: [&str; 12] =
189 ["河南话", "陕西话", "四川话", "贵州话", "云南话", "桂林话", "济南话", "石家庄话", "甘肃话", "宁夏话", "青岛话", "东北话"];
190
191fn is_cjk(c: char) -> bool {
192 ('\u{4e00}'..='\u{9fff}').contains(&c)
193}
194
195pub fn resolve_instruct(instruct: Option<&str>, use_zh: bool) -> Result<Option<String>, String> {
199 let Some(s) = instruct.map(str::trim).filter(|s| !s.is_empty()) else {
200 return Ok(None);
201 };
202 let valid = |n: &str| {
203 CATEGORIES_EN_ZH.iter().any(|c| c.iter().any(|(e, z)| *e == n || *z == n)) || ACCENTS.contains(&n) || DIALECTS.contains(&n)
204 };
205 let mut items = Vec::new();
206 let mut bad = Vec::new();
207 for raw in s.split([',', ',']).map(str::trim).filter(|x| !x.is_empty()) {
208 let n = raw.to_lowercase();
209 if valid(&n) {
210 items.push(n);
211 } else {
212 bad.push(raw.to_string());
213 }
214 }
215 if !bad.is_empty() {
216 let mut en: Vec<&str> = CATEGORIES_EN_ZH.iter().flat_map(|c| c.iter().map(|(e, _)| *e)).chain(ACCENTS).collect();
217 en.sort_unstable();
218 return Err(format!(
219 "omnivoice: unsupported instruct items {bad:?}; English items: {}; Chinese items use a full-width comma (男,河南话)",
220 en.join(", ")
221 ));
222 }
223 let dialect = items.iter().any(|n| n.ends_with('话'));
224 let accent = items.iter().any(|n| n.contains(" accent"));
225 if dialect && accent {
226 return Err("omnivoice: a Chinese dialect and an English accent cannot be mixed in one instruct".into());
227 }
228 let zh = if dialect { true } else if accent { false } else { use_zh };
229 let items: Vec<String> = items
230 .into_iter()
231 .map(|n| {
232 for c in CATEGORIES_EN_ZH {
233 for (e, z) in c {
234 if zh && n == *e {
235 return z.to_string();
236 }
237 if !zh && n == *z {
238 return e.to_string();
239 }
240 }
241 }
242 n
243 })
244 .collect();
245 let mut groups: Vec<Vec<&str>> = CATEGORIES_EN_ZH.iter().map(|c| c.iter().flat_map(|(e, z)| [*e, *z]).collect()).collect();
246 groups.push(ACCENTS.to_vec());
247 groups.push(DIALECTS.to_vec());
248 for g in &groups {
249 let hits: Vec<&String> = items.iter().filter(|n| g.contains(&n.as_str())).collect();
250 if hits.len() > 1 {
251 return Err(format!("omnivoice: conflicting instruct items {hits:?}: one per category (gender, age, pitch, style, accent, dialect)"));
252 }
253 }
254 let has_zh = items.iter().any(|n| n.chars().any(is_cjk));
255 Ok(Some(items.join(if has_zh { "," } else { ", " })))
256}
257
258pub fn combine_text(text: &str, ref_text: Option<&str>) -> String {
262 let full = match ref_text.filter(|r| !r.is_empty()) {
263 Some(r) => format!("{} {}", r.trim(), text.trim()),
264 None => text.trim().to_string(),
265 };
266 let full: String = full.chars().filter(|&c| c != '\r' && c != '\n').map(|c| match c {
267 '\u{ff08}' => '(',
268 '\u{ff09}' => ')',
269 c => c,
270 }).collect();
271 let mut collapsed = String::with_capacity(full.len());
273 let mut blank = false;
274 for c in full.chars() {
275 if c == ' ' || c == '\t' {
276 if !blank {
277 collapsed.push(' ');
278 }
279 blank = true;
280 } else {
281 collapsed.push(c);
282 blank = false;
283 }
284 }
285 let chars: Vec<char> = collapsed.chars().collect();
287 let mut out = String::with_capacity(collapsed.len());
288 let mut i = 0;
289 while i < chars.len() {
290 if chars[i].is_whitespace() {
291 let mut j = i;
292 while j < chars.len() && chars[j].is_whitespace() {
293 j += 1;
294 }
295 let before = i > 0 && is_cjk(chars[i - 1]);
296 let after = j < chars.len() && is_cjk(chars[j]);
297 if !before && !after {
298 out.extend(&chars[i..j]);
299 }
300 i = j;
301 } else {
302 out.push(chars[i]);
303 i += 1;
304 }
305 }
306 out
307}
308
309const NONVERBAL: [&str; 13] = [
310 "laughter",
311 "sigh",
312 "confirmation-en",
313 "question-en",
314 "question-ah",
315 "question-oh",
316 "question-ei",
317 "question-yi",
318 "surprise-ah",
319 "surprise-oh",
320 "surprise-wa",
321 "surprise-yo",
322 "dissatisfaction-hnn",
323];
324
325fn tokenize_with_tags(pipeline: &Pipeline, text: &str) -> Vec<u32> {
328 let mut ids = Vec::new();
329 let mut last = 0;
330 let mut i = 0;
331 let b = text.as_bytes();
332 while i < b.len() {
333 if b[i] == b'[' {
334 if let Some(tag) = NONVERBAL.iter().find(|t| text[i + 1..].starts_with(*t) && text[i + 1 + t.len()..].starts_with(']')) {
335 let end = i + tag.len() + 2;
336 if i > last {
337 ids.extend(pipeline.tokenizer.encode(&text[last..i]));
338 }
339 ids.extend(pipeline.tokenizer.encode(&text[i..end]));
340 last = end;
341 i = end;
342 continue;
343 }
344 }
345 i += 1;
346 }
347 if last < text.len() {
348 ids.extend(pipeline.tokenizer.encode(&text[last..]));
349 }
350 ids
351}
352
353pub fn add_punctuation(text: &str) -> String {
355 let t = text.trim();
356 let Some(last) = t.chars().last() else {
357 return String::new();
358 };
359 const END: &str = ";:,.!?…)]}\"'“”‘’;:,。!?、)】";
360 if END.contains(last) {
361 t.to_string()
362 } else if t.chars().any(is_cjk) {
363 format!("{t}。")
364 } else {
365 format!("{t}.")
366 }
367}
368
369fn char_weight(c: char) -> f64 {
373 use unicode_categories::UnicodeCategories;
374 let code = c as u32;
375 if c.is_ascii_alphabetic() {
376 return 1.0;
377 }
378 if code == 32 {
379 return 0.2;
380 }
381 if code == 0x0640 || c.is_mark() {
382 return 0.0;
383 }
384 if c.is_punctuation() || c.is_symbol() {
385 return 0.5;
386 }
387 if c.is_separator() {
388 return 0.2;
389 }
390 if c.is_number() {
391 return 3.5;
392 }
393 const RANGES: &[(u32, f64)] = &[
395 (0x02AF, 1.0),
396 (0x03FF, 1.0),
397 (0x052F, 1.0),
398 (0x058F, 1.0),
399 (0x05FF, 1.5),
400 (0x077F, 1.5),
401 (0x089F, 1.5),
402 (0x08FF, 1.5),
403 (0x097F, 1.8),
404 (0x09FF, 1.8),
405 (0x0A7F, 1.8),
406 (0x0AFF, 1.8),
407 (0x0B7F, 1.8),
408 (0x0BFF, 1.8),
409 (0x0C7F, 1.8),
410 (0x0CFF, 1.8),
411 (0x0D7F, 1.8),
412 (0x0DFF, 1.8),
413 (0x0EFF, 1.5),
414 (0x0FFF, 1.8),
415 (0x109F, 1.8),
416 (0x10FF, 1.0),
417 (0x11FF, 2.5),
418 (0x137F, 3.0),
419 (0x139F, 3.0),
420 (0x13FF, 1.0),
421 (0x167F, 1.0),
422 (0x169F, 1.0),
423 (0x16FF, 1.0),
424 (0x171F, 1.0),
425 (0x173F, 1.0),
426 (0x175F, 1.0),
427 (0x177F, 1.0),
428 (0x17FF, 1.8),
429 (0x18AF, 1.0),
430 (0x18FF, 1.0),
431 (0x194F, 1.8),
432 (0x19DF, 1.8),
433 (0x19FF, 1.8),
434 (0x1A1F, 1.8),
435 (0x1AAF, 1.8),
436 (0x1B7F, 1.8),
437 (0x1BBF, 1.8),
438 (0x1BFF, 1.8),
439 (0x1C4F, 1.8),
440 (0x1C7F, 1.8),
441 (0x1C8F, 1.0),
442 (0x1CBF, 1.0),
443 (0x1CCF, 1.8),
444 (0x1CFF, 1.8),
445 (0x1D7F, 1.0),
446 (0x1DBF, 1.0),
447 (0x1DFF, 1.0),
448 (0x1EFF, 1.0),
449 (0x309F, 2.2),
450 (0x30FF, 2.2),
451 (0x312F, 3.0),
452 (0x318F, 2.5),
453 (0x9FFF, 3.0),
454 (0xA4CF, 3.0),
455 (0xA4FF, 1.0),
456 (0xA63F, 1.0),
457 (0xA69F, 1.0),
458 (0xA6FF, 1.0),
459 (0xA7FF, 1.0),
460 (0xA82F, 1.8),
461 (0xA87F, 1.0),
462 (0xA8DF, 1.8),
463 (0xA8FF, 1.8),
464 (0xA92F, 1.8),
465 (0xA95F, 1.8),
466 (0xA97F, 2.5),
467 (0xA9DF, 1.8),
468 (0xA9FF, 1.8),
469 (0xAA5F, 1.8),
470 (0xAA7F, 1.8),
471 (0xAADF, 1.8),
472 (0xAAFF, 1.8),
473 (0xAB2F, 3.0),
474 (0xAB6F, 1.0),
475 (0xABBF, 1.0),
476 (0xABFF, 1.8),
477 (0xD7AF, 2.5),
478 (0xFAFF, 3.0),
479 (0xFDFF, 1.5),
480 (0xFE6F, 1.0),
481 (0xFEFF, 1.5),
482 (0xFFEF, 1.0),
483 ];
484 let idx = RANGES.partition_point(|&(b, _)| b < code);
485 if let Some(&(_, w)) = RANGES.get(idx) {
486 return w;
487 }
488 if code > 0x20000 {
489 return 3.0;
490 }
491 1.0
492}
493
494fn text_weight(t: &str) -> f64 {
495 t.chars().map(char_weight).sum()
496}
497
498fn estimate_duration(target: &str, ref_text: &str, ref_frames: f64) -> f64 {
502 if ref_frames <= 0.0 || ref_text.is_empty() {
503 return 0.0;
504 }
505 let rw = text_weight(ref_text);
506 if rw == 0.0 {
507 return 0.0;
508 }
509 let est = text_weight(target) / (rw / ref_frames);
510 const LOW: f64 = 50.0;
511 if est < LOW {
512 LOW * (est / LOW).powf(1.0 / 3.0)
513 } else {
514 est
515 }
516}
517
518pub fn estimate_frames(text: &str, ref_text: Option<&str>, ref_frames: Option<usize>, speed: f32) -> usize {
521 let (rt, rf) = match (ref_text.filter(|r| !r.is_empty()), ref_frames) {
522 (Some(t), Some(f)) => (t, f as f64),
523 _ => ("Nice to meet you.", 25.0),
524 };
525 let mut est = estimate_duration(text, rt, rf);
526 if speed > 0.0 && speed != 1.0 {
527 est /= speed as f64;
528 }
529 (est as i64).max(1) as usize
530}
531
532const ABBREVIATIONS: [&str; 52] = [
535 "Mr.", "Mrs.", "Ms.", "Dr.", "Prof.", "Sr.", "Jr.", "Rev.", "Fr.", "Hon.", "Pres.", "Gov.", "Capt.", "Gen.", "Sen.",
536 "Rep.", "Col.", "Maj.", "Lt.", "Cmdr.", "Sgt.", "Cpl.", "Co.", "Corp.", "Inc.", "Ltd.", "Est.", "Dept.", "St.",
537 "Ave.", "Blvd.", "Rd.", "Mt.", "Ft.", "No.", "Jan.", "Feb.", "Mar.", "Apr.", "Aug.", "Sep.", "Sept.", "Oct.",
538 "Nov.", "Dec.", "i.e.", "e.g.", "vs.", "Vs.", "Etc.", "approx.", "fig.",
539];
540
541pub fn chunk_text_punctuation(text: &str, chunk_len: usize, min_len: usize) -> Vec<String> {
545 const SPLIT: &str = ".,;:!?。,;:!?";
546 const CLOSING: &str = "\"'“”‘’)]》>」】";
547 let mut sentences: Vec<Vec<char>> = Vec::new();
548 let mut cur: Vec<char> = Vec::new();
549 for ch in text.chars() {
550 if cur.is_empty() && !sentences.is_empty() && (SPLIT.contains(ch) || CLOSING.contains(ch)) {
551 sentences.last_mut().unwrap().push(ch);
552 continue;
553 }
554 cur.push(ch);
555 if SPLIT.contains(ch) {
556 let mut abbr = false;
557 if ch == '.' {
558 let t: String = cur.iter().collect();
559 if let Some(w) = t.split_whitespace().last() {
560 abbr = ABBREVIATIONS.contains(&w) || w == "def.";
561 }
562 }
563 if !abbr {
564 sentences.push(std::mem::take(&mut cur));
565 }
566 }
567 }
568 if !cur.is_empty() {
569 sentences.push(cur);
570 }
571 let mut merged: Vec<Vec<char>> = Vec::new();
572 let mut chunk: Vec<char> = Vec::new();
573 for sen in sentences {
574 if chunk.len() + sen.len() <= chunk_len {
575 chunk.extend(sen);
576 } else {
577 if !chunk.is_empty() {
578 merged.push(chunk);
579 }
580 chunk = sen;
581 }
582 }
583 if !chunk.is_empty() {
584 merged.push(chunk);
585 }
586 let first_short = merged.first().is_some_and(|c| c.len() < min_len);
587 let mut fin: Vec<Vec<char>> = Vec::new();
588 for (i, c) in merged.into_iter().enumerate() {
589 if i == 1 && first_short {
590 fin.last_mut().unwrap().extend(c);
591 } else if c.len() >= min_len || fin.is_empty() {
592 fin.push(c);
593 } else {
594 fin.last_mut().unwrap().extend(c);
595 }
596 }
597 fin.into_iter().map(|c| c.into_iter().collect::<String>().trim().to_string()).filter(|s| !s.is_empty()).collect()
598}
599
600pub fn cross_fade(chunks: &[Vec<f32>], rate: usize) -> Vec<f32> {
603 let Some(first) = chunks.first() else { return Vec::new() };
604 let fade_n = (0.3 * rate as f64) as usize / 3;
605 let mut out = first.clone();
606 for c in &chunks[1..] {
607 let k = fade_n.min(out.len());
608 let n = out.len();
609 for i in 0..k {
610 let w = if k == 1 { 1.0 } else { 1.0 - i as f32 / (k - 1) as f32 };
611 out[n - k + i] *= w;
612 }
613 out.extend(std::iter::repeat_n(0f32, fade_n));
614 let mut nx = c.clone();
615 let k = fade_n.min(nx.len());
616 for (i, v) in nx.iter_mut().take(k).enumerate() {
617 *v *= if k == 1 { 0.0 } else { i as f32 / (k - 1) as f32 };
618 }
619 out.extend(nx);
620 }
621 out
622}
623
624pub const CHUNK_THRESHOLD_S: f64 = 30.0;
627pub const CHUNK_S: f64 = 15.0;
628
629pub fn generate_chunks(
634 pipeline: &Pipeline,
635 model: &Arc<CmfModel>,
636 cfg: &OmniVoiceConfig,
637 req: &Request,
638 pool: Option<&Pool>,
639) -> Result<Vec<Vec<Vec<u32>>>, String> {
640 let speed = req.speed.unwrap_or(1.0);
641 let est = estimate_frames(req.text, req.voice.map(|v| v.text.as_str()), req.voice.map(|v| v.codes[0].len()), speed);
642 if req.duration.is_some() || (est as f64) <= CHUNK_THRESHOLD_S * cfg.frame_rate() {
643 return Ok(vec![generate(pipeline, model, cfg, req, pool)?]);
644 }
645 let per_char = est as f64 / req.text.chars().count().max(1) as f64;
646 let chunk_len = (CHUNK_S * cfg.frame_rate() / per_char) as usize;
647 let chunks = chunk_text_punctuation(req.text, chunk_len.max(1), 3);
648 let mut out = Vec::with_capacity(chunks.len());
649 let mut first: Option<VoicePrompt> = None;
650 for (i, t) in chunks.iter().enumerate() {
651 let voice = match (req.voice, &first) {
652 (Some(v), _) => Some(v),
653 (None, Some(f)) => Some(f),
654 (None, None) => None,
655 };
656 let r = Request { text: t, language: req.language, instruct: req.instruct, voice, duration: None, speed: req.speed, generation: req.generation.clone() };
657 let codes = generate(pipeline, model, cfg, &r, pool)?;
658 if i == 0 && req.voice.is_none() {
659 first = Some(VoicePrompt { codes: codes.clone(), text: t.clone(), rms: f32::NAN });
662 }
663 out.push(codes);
664 }
665 Ok(out)
666}
667
668fn time_steps(steps: usize, shift: f32) -> Vec<f32> {
672 (0..=steps)
673 .map(|i| {
674 let t = i as f32 / steps as f32;
675 shift * t / (1.0 + (shift - 1.0) * t)
676 })
677 .collect()
678}
679
680fn schedule(total: usize, steps: usize, shift: f32) -> Vec<usize> {
682 let ts = time_steps(steps, shift);
683 let mut rem = total;
684 (0..steps)
685 .map(|s| {
686 let n = if s + 1 == steps {
687 rem
688 } else {
689 ((total as f64 * (ts[s + 1] as f64 - ts[s] as f64)).ceil() as usize).min(rem)
690 };
691 rem -= n;
692 n
693 })
694 .collect()
695}
696
697fn log_softmax(x: &[f32], out: &mut [f32]) {
698 let m = x.iter().copied().fold(f32::NEG_INFINITY, f32::max);
699 let s: f64 = x.iter().map(|&v| ((v - m) as f64).exp()).sum();
700 let l = m + s.ln() as f32;
701 for (o, &v) in out.iter_mut().zip(x) {
702 *o = v - l;
703 }
704}
705
706fn gumbel(rng: &mut SplitMix64) -> f32 {
707 let u = rng.next_f32();
708 -(-(u + 1e-10).ln() + 1e-10).ln()
709}
710
711struct TextEmbedding {
713 model: Arc<CmfModel>,
714 idx: usize,
715 width: usize,
716}
717
718impl TextEmbedding {
719 fn load(model: &Arc<CmfModel>, width: usize) -> Result<Self, String> {
720 let name = "ov.text_embedding.weight";
721 let idx = model.tensor_index(name).ok_or("omnivoice: no ov.text_embedding.weight")?;
722 let e = &model.tensors[idx];
723 if e.shape.len() != 2 || e.shape[1] != width {
724 return Err(format!("{name}: shape {:?}, expected [_, {width}]", e.shape));
725 }
726 Ok(Self { model: model.clone(), idx, width })
727 }
728
729 fn row(&self, id: u32) -> Result<Vec<f32>, String> {
730 let e = &self.model.tensors[self.idx];
731 if id as usize >= e.shape[0] {
732 return Err(format!("omnivoice: text token {id} past the embedding's {} rows", e.shape[0]));
733 }
734 let bytes = self.model.entry_bytes(e);
735 let w = self.width;
736 match e.dtype {
737 cortiq_core::TensorDtype::F16 => {
738 let r = &bytes[id as usize * w * 2..(id as usize + 1) * w * 2];
739 Ok(r.chunks_exact(2).map(|b| cortiq_core::quant::f16_to_f32(u16::from_le_bytes([b[0], b[1]]))).collect())
740 }
741 cortiq_core::TensorDtype::F32 => {
742 let r = &bytes[id as usize * w * 4..(id as usize + 1) * w * 4];
743 Ok(r.chunks_exact(4).map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]])).collect())
744 }
745 d => Err(format!("omnivoice: text embedding stored as {d:?}, expected F16 or F32")),
746 }
747 }
748}
749
750fn prof_on() -> bool {
752 static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
753 *ON.get_or_init(|| std::env::var_os("CMF_OV_PROF").is_some())
754}
755
756pub struct Prompt {
758 pub ids: Vec<Vec<u32>>,
760 pub audio_start: usize,
762 pub frames: usize,
764}
765
766pub fn build_prompt(pipeline: &Pipeline, cfg: &OmniVoiceConfig, req: &Request) -> Result<Prompt, String> {
769 if req.text.trim().is_empty() {
770 return Err("omnivoice: empty text".into());
771 }
772 let lang = resolve_language(req.language);
773 let instruct = resolve_instruct(req.instruct, req.text.chars().any(is_cjk))?;
774 let voice = req.voice;
775 if let Some(v) = voice {
776 if v.codes.len() != cfg.books || v.codes.iter().any(|c| c.len() != v.codes[0].len()) {
777 return Err(format!("omnivoice: a reference needs {} codebooks of one length", cfg.books));
778 }
779 }
780 let ref_frames = voice.map(|v| v.codes[0].len());
781 let est = estimate_frames(req.text, voice.map(|v| v.text.as_str()), ref_frames, if req.duration.is_some() { 1.0 } else { req.speed.unwrap_or(1.0) });
782 let frames = match req.duration {
783 Some(d) => ((d as f64 * cfg.frame_rate()) as i64).max(1) as usize,
784 None => est,
785 };
786 let mut style = String::new();
787 if req.generation.denoise && voice.is_some() {
788 style.push_str("<|denoise|>");
789 }
790 style.push_str(&format!(
791 "<|lang_start|>{}<|lang_end|><|instruct_start|>{}<|instruct_end|>",
792 lang.as_deref().unwrap_or("None"),
793 instruct.as_deref().unwrap_or("None")
794 ));
795 let mut text_ids = pipeline.tokenizer.encode(&style);
796 let full = combine_text(req.text, voice.map(|v| v.text.as_str()));
797 text_ids.extend(tokenize_with_tags(pipeline, &format!("<|text_start|>{full}<|text_end|>")));
798 let audio_start = text_ids.len();
799 let mut ids: Vec<Vec<u32>> = (0..cfg.books).map(|_| text_ids.clone()).collect();
800 for (c, row) in ids.iter_mut().enumerate() {
801 if let Some(v) = voice {
802 row.extend(&v.codes[c]);
803 }
804 row.extend(std::iter::repeat_n(cfg.mask_id, frames));
805 }
806 Ok(Prompt { ids, audio_start, frames })
807}
808
809pub fn generate(
811 pipeline: &Pipeline,
812 model: &Arc<CmfModel>,
813 cfg: &OmniVoiceConfig,
814 req: &Request,
815 pool: Option<&Pool>,
816) -> Result<Vec<Vec<u32>>, String> {
817 let prompt = build_prompt(pipeline, cfg, req)?;
818 if let Ok(f) = std::env::var("CMF_OV_PROMPT_DUMP") {
819 let _ = std::fs::write(&f, serde_json::to_vec(&serde_json::json!({"ids": prompt.ids, "audio_start": prompt.audio_start, "frames": prompt.frames})).unwrap_or_default());
820 }
821 generate_prompt(pipeline, model, cfg, &prompt, &req.generation, pool)
822}
823
824pub fn generate_prompt(
825 pipeline: &Pipeline,
826 model: &Arc<CmfModel>,
827 cfg: &OmniVoiceConfig,
828 prompt: &Prompt,
829 gc: &GenConfig,
830 pool: Option<&Pool>,
831) -> Result<Vec<Vec<u32>>, String> {
832 let h = pipeline.hidden_size;
833 let (books, v) = (cfg.books, cfg.vocab);
834 if pipeline.vocab_size != books * v {
835 return Err(format!("omnivoice: head width {} against {books} × {v}", pipeline.vocab_size));
836 }
837 let text = TextEmbedding::load(model, h)?;
838 let heads = crate::dit::cmf_f32(model, "lm_head.weight")?;
842 if heads.len() != books * v * h {
843 return Err(format!("omnivoice: lm_head holds {} values, expected {} × {h}", heads.len(), books * v));
844 }
845 let c_len = prompt.ids[0].len();
846 let t_len = prompt.frames;
847 let t0 = c_len - t_len;
848 let audio_row = |codes: &[u32]| -> Vec<f32> {
849 let mut r = vec![0f32; h];
850 for (c, &id) in codes.iter().enumerate() {
851 for (a, b) in r.iter_mut().zip(pipeline.embed_id((c * v) as u32 + id)) {
852 *a += b;
853 }
854 }
855 r
856 };
857 let col = |p: usize| -> Vec<u32> { prompt.ids.iter().map(|r| r[p]).collect() };
858 let n = c_len + t_len;
859 let mut rows = vec![0f32; n * h];
860 for p in 0..c_len {
861 let r = if p < prompt.audio_start { text.row(prompt.ids[0][p])? } else { audio_row(&col(p)) };
862 rows[p * h..(p + 1) * h].copy_from_slice(&r);
863 }
864 for t in 0..t_len {
866 let (a, b) = rows.split_at_mut(c_len * h);
867 b[t * h..(t + 1) * h].copy_from_slice(&a[(t0 + t) * h..(t0 + t + 1) * h]);
868 }
869 let group: Vec<i32> = (0..n).map(|p| i32::from(p >= c_len)).collect();
870 let head_rows: Vec<usize> = (t0..c_len).chain(c_len..n).collect();
871 let mut tokens = vec![vec![cfg.mask_id; t_len]; books];
872 let sched = schedule(t_len * books, gc.steps, gc.t_shift);
873 let mut rng = SplitMix64::new(gc.seed);
874 let vv = books * v;
875 let mut c_lp = vec![0f32; v];
876 let mut u_lp = vec![0f32; v];
877 let mut comb = vec![0f32; v];
878 let mut lp = vec![0f32; v];
879 for (step, &k) in sched.iter().enumerate() {
880 if k == 0 {
881 continue;
882 }
883 let t_fwd = std::time::Instant::now();
884 let (hidden, _) = pipeline.forward_masked_head(&rows, &SetMask { state: 0, group: &group }, &[])?;
885 let ms_fwd = t_fwd.elapsed().as_secs_f64() * 1e3;
886 let t_head = std::time::Instant::now();
887 let x: Vec<f32> = head_rows.iter().flat_map(|&r| hidden[r * h..(r + 1) * h].iter().copied()).collect();
888 let nr = head_rows.len();
889 let mut logits = vec![0f32; nr * books * v];
890 if !crate::gpu::gemm_nt_f32(&x, &heads, &mut logits, nr, h, books * v) {
891 crate::fcd_ops::gemm_nt(&x, &heads, &mut logits, nr, h, books * v, pool);
892 }
893 let ms_head = t_head.elapsed().as_secs_f64() * 1e3;
894 if logits.len() < 2 * t_len * vv {
895 return Err("omnivoice: the head returned too few rows".into());
896 }
897 if step == 0 {
898 if let Ok(f) = std::env::var("CMF_OV_STEP0_DUMP") {
899 let bytes: Vec<u8> = logits[..2 * t_len * vv].iter().flat_map(|v| v.to_le_bytes()).collect();
900 let _ = std::fs::write(&f, bytes);
901 }
902 }
903 let mut pred = vec![0u32; books * t_len];
904 let mut score = vec![f32::NEG_INFINITY; books * t_len];
905 for c in 0..books {
906 for t in 0..t_len {
907 if tokens[c][t] != cfg.mask_id {
908 continue;
909 }
910 let cl = &logits[t * vv + c * v..t * vv + (c + 1) * v];
911 let ul = &logits[(t_len + t) * vv + c * v..(t_len + t) * vv + (c + 1) * v];
912 if gc.guidance != 0.0 {
913 log_softmax(cl, &mut c_lp);
914 log_softmax(ul, &mut u_lp);
915 for i in 0..v {
916 comb[i] = c_lp[i] + gc.guidance * (c_lp[i] - u_lp[i]);
917 }
918 log_softmax(&comb, &mut lp);
919 } else {
920 log_softmax(cl, &mut lp);
921 }
922 lp[cfg.mask_id as usize] = f32::NEG_INFINITY;
923 let (mut best, mut bi) = (f32::NEG_INFINITY, 0usize);
924 for (i, &x) in lp.iter().enumerate() {
925 if x > best {
926 best = x;
927 bi = i;
928 }
929 }
930 let id = if gc.class_temperature > 0.0 {
931 let keep = (0.1 * v as f64).ceil() as usize;
933 let mut order: Vec<usize> = (0..v).collect();
934 order.sort_by(|&a, &b| lp[b].total_cmp(&lp[a]));
935 let mut top = (f32::NEG_INFINITY, bi);
936 for &i in &order[..keep] {
937 let s = lp[i] / gc.class_temperature + gumbel(&mut rng);
938 if s > top.0 {
939 top = (s, i);
940 }
941 }
942 top.1
943 } else {
944 bi
945 };
946 pred[c * t_len + t] = id as u32;
947 let mut s = best - c as f32 * gc.layer_penalty;
948 if gc.position_temperature > 0.0 {
949 s = s / gc.position_temperature + gumbel(&mut rng);
950 }
951 score[c * t_len + t] = s;
952 }
953 }
954 let mut order: Vec<usize> = (0..books * t_len).filter(|&i| score[i] > f32::NEG_INFINITY).collect();
955 order.sort_by(|&a, &b| score[b].total_cmp(&score[a]).then(a.cmp(&b)));
956 let mut touched = vec![false; t_len];
957 for &i in order.iter().take(k) {
958 let (c, t) = (i / t_len, i % t_len);
959 tokens[c][t] = pred[i];
960 touched[t] = true;
961 }
962 for t in (0..t_len).filter(|&t| touched[t]) {
963 let codes: Vec<u32> = (0..books).map(|c| tokens[c][t]).collect();
964 let r = audio_row(&codes);
965 rows[(t0 + t) * h..(t0 + t + 1) * h].copy_from_slice(&r);
966 rows[(c_len + t) * h..(c_len + t + 1) * h].copy_from_slice(&r);
967 }
968 if prof_on() {
969 eprintln!("omnivoice: step {step}: {n} rows forward {ms_fwd:.1} ms, head {ms_head:.1} ms, {k} codes fixed");
970 }
971 }
972 Ok(tokens)
973}
974
975struct Unit {
978 s1: Snake,
979 c1: Conv1d,
980 s2: Snake,
981 c2: Conv1d,
982}
983
984impl Unit {
985 fn load(model: &Arc<CmfModel>, p: &str, dilation: usize) -> Result<Self, String> {
986 Ok(Self {
987 s1: Snake::load(model, &format!("{p}.snake1"))?,
988 c1: Conv1d::load(model, &format!("{p}.conv1"), 3 * dilation, dilation)?,
989 s2: Snake::load(model, &format!("{p}.snake2"))?,
990 c2: Conv1d::load(model, &format!("{p}.conv2"), 0, 1)?,
991 })
992 }
993
994 fn apply(&self, x: &[f32], n: usize, pool: Option<&Pool>) -> Vec<f32> {
995 let mut h = x.to_vec();
996 self.s1.apply_pool(&mut h, n, pool);
997 let mut h = self.c1.apply(&h, n, pool);
998 self.s2.apply_pool(&mut h, n, pool);
999 let mut r = self.c2.apply(&h, n, pool);
1000 for (a, &b) in r.iter_mut().zip(x) {
1001 *a += b;
1002 }
1003 r
1004 }
1005}
1006
1007struct Block {
1008 snake: Snake,
1009 up: ConvT1d,
1010 units: Vec<Unit>,
1011}
1012
1013pub struct Codec {
1017 embed: Vec<Vec<f32>>,
1019 dim: usize,
1020 proj: Vec<(Vec<f32>, Vec<f32>)>,
1022 hidden: usize,
1023 fc2: (Vec<f32>, Vec<f32>),
1024 acoustic: usize,
1025 conv1: Conv1d,
1026 blocks: Vec<Block>,
1027 snake: Snake,
1028 conv2: Conv1d,
1029 pool: Option<Arc<Pool>>,
1030}
1031
1032impl Codec {
1033 pub fn from_model(model: &Arc<CmfModel>, cfg: &OmniVoiceConfig, pool: Option<Arc<Pool>>) -> Result<Self, String> {
1034 let f = |n: &str| crate::dit::cmf_f32(model, n);
1035 let shape = |n: &str| model.tensor(n).map(|e| e.shape.clone()).ok_or_else(|| format!("omnivoice: missing {n}"));
1036 let q = "ov.codec.quantizer.quantizers";
1037 let es = shape(&format!("{q}.0.codebook.embed"))?;
1038 let dim = es[1];
1039 let ps = shape(&format!("{q}.0.project_out.weight"))?;
1040 let hidden = ps[0];
1041 let mut embed = Vec::with_capacity(cfg.books);
1042 let mut proj = Vec::with_capacity(cfg.books);
1043 for c in 0..cfg.books {
1044 embed.push(f(&format!("{q}.{c}.codebook.embed"))?);
1045 proj.push((f(&format!("{q}.{c}.project_out.weight"))?, f(&format!("{q}.{c}.project_out.bias"))?));
1046 }
1047 let fs = shape("ov.codec.fc2.weight")?;
1048 let acoustic = fs[0];
1049 let d = "ov.codec.acoustic_decoder";
1050 let blocks = cfg
1051 .upsampling
1052 .iter()
1053 .enumerate()
1054 .map(|(i, &s)| {
1055 Ok(Block {
1056 snake: Snake::load(model, &format!("{d}.block.{i}.snake1"))?,
1057 up: ConvT1d::load_padded(model, &format!("{d}.block.{i}.conv_t1"), s, s.div_ceil(2), s % 2)?,
1058 units: [1usize, 3, 9]
1059 .iter()
1060 .enumerate()
1061 .map(|(j, &dl)| Unit::load(model, &format!("{d}.block.{i}.res_unit{}", j + 1), dl))
1062 .collect::<Result<_, String>>()?,
1063 })
1064 })
1065 .collect::<Result<_, String>>()?;
1066 Ok(Self {
1067 embed,
1068 dim,
1069 proj,
1070 hidden,
1071 fc2: (f("ov.codec.fc2.weight")?, f("ov.codec.fc2.bias")?),
1072 acoustic,
1073 conv1: Conv1d::load(model, &format!("{d}.conv1"), 3, 1)?,
1074 blocks,
1075 snake: Snake::load(model, &format!("{d}.snake1"))?,
1076 conv2: Conv1d::load(model, &format!("{d}.conv2"), 3, 1)?,
1077 pool,
1078 })
1079 }
1080
1081 pub fn decode(&self, codes: &[Vec<u32>]) -> Vec<f32> {
1083 let pool = self.pool.as_deref();
1084 let frames = codes.first().map_or(0, |c| c.len());
1085 if frames == 0 {
1086 return Vec::new();
1087 }
1088 let (hd, dim) = (self.hidden, self.dim);
1089 let mut q = vec![0f32; frames * hd];
1091 for (c, cb) in codes.iter().enumerate() {
1092 let mut e = vec![0f32; frames * dim];
1093 for (t, &id) in cb.iter().enumerate() {
1094 let id = (id as usize).min(self.embed[c].len() / dim - 1);
1095 e[t * dim..(t + 1) * dim].copy_from_slice(&self.embed[c][id * dim..(id + 1) * dim]);
1096 }
1097 let mut y = vec![0f32; frames * hd];
1098 crate::fcd_ops::gemm_nt(&e, &self.proj[c].0, &mut y, frames, dim, hd, pool);
1099 for (row, qr) in y.chunks_exact(hd).zip(q.chunks_exact_mut(hd)) {
1100 for ((a, &b), &bias) in qr.iter_mut().zip(row).zip(&self.proj[c].1) {
1101 *a += b + bias;
1102 }
1103 }
1104 }
1105 let ac = self.acoustic;
1106 let mut z = vec![0f32; frames * ac];
1107 crate::fcd_ops::gemm_nt(&q, &self.fc2.0, &mut z, frames, hd, ac, pool);
1108 let mut x = vec![0f32; ac * frames];
1110 for t in 0..frames {
1111 for ch in 0..ac {
1112 x[ch * frames + t] = z[t * ac + ch] + self.fc2.1[ch];
1113 }
1114 }
1115 let prof = prof_on();
1116 let t = std::time::Instant::now();
1117 let mut h = self.conv1.apply(&x, frames, pool);
1118 let mut n = frames;
1119 let mut last = t.elapsed().as_secs_f64();
1120 if prof {
1121 eprintln!("[ov codec] codebooks + conv1: {:.3} s", last);
1122 }
1123 for (bi, b) in self.blocks.iter().enumerate() {
1124 b.snake.apply_pool(&mut h, n, pool);
1125 h = if std::env::var("CMF_OV_CONVT_REF").is_ok() { b.up.apply(&h, n, pool) } else { b.up.apply_gemm(&h, n, pool) };
1126 n *= b.up.stride;
1127 let up = t.elapsed().as_secs_f64();
1128 for u in &b.units {
1129 h = u.apply(&h, n, pool);
1130 }
1131 let now = t.elapsed().as_secs_f64();
1132 if prof {
1133 eprintln!("[ov codec] block {bi}: {} ch × {n}: up {:.3} s, units {:.3} s", h.len() / n, up - last, now - up);
1134 }
1135 last = now;
1136 }
1137 self.snake.apply_pool(&mut h, n, pool);
1138 let y = self.conv2.apply(&h, n, pool);
1139 if prof {
1140 eprintln!("[ov codec] conv2: {:.3} s, total {:.3} s", t.elapsed().as_secs_f64() - last, t.elapsed().as_secs_f64());
1141 }
1142 y
1143 }
1144}
1145
1146struct SConv {
1151 w: Vec<f32>,
1152 b: Option<Vec<f32>>,
1153 out: usize,
1154 inp: usize,
1155 k: usize,
1156 stride: usize,
1157 pad: usize,
1158 dil: usize,
1159 groups: usize,
1160}
1161
1162impl SConv {
1163 fn new(w: Vec<f32>, b: Option<Vec<f32>>, shape: &[usize], stride: usize, pad: usize, dil: usize, groups: usize) -> Result<Self, String> {
1164 if shape.len() != 3 || w.len() != shape.iter().product::<usize>() {
1165 return Err(format!("omnivoice: conv weight of shape {shape:?}"));
1166 }
1167 Ok(Self { w, b, out: shape[0], inp: shape[1] * groups, k: shape[2], stride, pad, dil, groups })
1168 }
1169
1170 fn load(model: &CmfModel, name: &str, stride: usize, pad: usize, dil: usize, groups: usize) -> Result<Self, String> {
1171 let shape = model.tensor(&format!("{name}.weight")).map(|e| e.shape.clone()).ok_or_else(|| format!("omnivoice: missing {name}.weight"))?;
1172 let w = crate::dit::cmf_f32(model, &format!("{name}.weight"))?;
1173 let b = crate::dit::cmf_f32(model, &format!("{name}.bias")).ok();
1174 Self::new(w, b, &shape, stride, pad, dil, groups)
1175 }
1176
1177 fn out_len(&self, n: usize) -> usize {
1178 (n + 2 * self.pad).saturating_sub(self.dil * (self.k - 1) + 1) / self.stride + 1
1179 }
1180
1181 fn apply(&self, x: &[f32], n: usize, pool: Option<&Pool>) -> (Vec<f32>, usize) {
1182 let n_out = self.out_len(n);
1183 let (gi, go) = (self.inp / self.groups, self.out / self.groups);
1184 let kk = gi * self.k;
1185 let mut y = vec![0f32; self.out * n_out];
1186 const TILE: usize = 1 << 24; let span = (TILE / kk.max(1)).clamp(1, n_out.max(1));
1188 for g in 0..self.groups {
1189 let wg = &self.w[g * go * kk..(g + 1) * go * kk];
1190 let mut t0 = 0;
1191 while t0 < n_out {
1192 let m = span.min(n_out - t0);
1193 let mut col = vec![0f32; m * kk];
1194 for (r, row) in col.chunks_exact_mut(kk).enumerate() {
1195 let t = t0 + r;
1196 for c in 0..gi {
1197 let src = &x[(g * gi + c) * n..(g * gi + c + 1) * n];
1198 for j in 0..self.k {
1199 let p = (t * self.stride + j * self.dil) as isize - self.pad as isize;
1200 if p >= 0 && (p as usize) < n {
1201 row[c * self.k + j] = src[p as usize];
1202 }
1203 }
1204 }
1205 }
1206 let mut yt = vec![0f32; m * go];
1207 crate::fcd_ops::gemm_nt(&col, wg, &mut yt, m, kk, go, pool);
1208 for o in 0..go {
1209 let bias = self.b.as_ref().map_or(0.0, |b| b[g * go + o]);
1210 let dst = &mut y[(g * go + o) * n_out + t0..(g * go + o) * n_out + t0 + m];
1211 for (r, d) in dst.iter_mut().enumerate() {
1212 *d = yt[r * go + o] + bias;
1213 }
1214 }
1215 t0 += m;
1216 }
1217 }
1218 (y, n_out)
1219 }
1220}
1221
1222fn elu(x: &mut [f32]) {
1223 for v in x {
1224 if *v < 0.0 {
1225 *v = v.exp_m1();
1226 }
1227 }
1228}
1229
1230fn layer_norm_rows(x: &mut [f32], w: &[f32], b: &[f32], eps: f32) {
1231 let d = w.len();
1232 for row in x.chunks_exact_mut(d) {
1233 let mean = row.iter().map(|&v| v as f64).sum::<f64>() / d as f64;
1234 let var = row.iter().map(|&v| (v as f64 - mean).powi(2)).sum::<f64>() / d as f64;
1235 let r = 1.0 / (var + eps as f64).sqrt();
1236 for ((v, &g), &bb) in row.iter_mut().zip(w).zip(b) {
1237 *v = ((*v as f64 - mean) * r) as f32 * g + bb;
1238 }
1239 }
1240}
1241
1242fn transpose(x: &[f32], rows: usize, cols: usize) -> Vec<f32> {
1243 let mut y = vec![0f32; x.len()];
1244 for r in 0..rows {
1245 for c in 0..cols {
1246 y[c * rows + r] = x[r * cols + c];
1247 }
1248 }
1249 y
1250}
1251
1252struct HubertLayer {
1253 q: crate::qwen3_tts::Lin,
1254 k: crate::qwen3_tts::Lin,
1255 v: crate::qwen3_tts::Lin,
1256 o: crate::qwen3_tts::Lin,
1257 ln: (Vec<f32>, Vec<f32>),
1258 ff1: crate::qwen3_tts::Lin,
1259 ff2: crate::qwen3_tts::Lin,
1260 ln2: (Vec<f32>, Vec<f32>),
1261}
1262
1263struct Hubert {
1267 convs: Vec<SConv>,
1268 gn: (Vec<f32>, Vec<f32>),
1269 proj_ln: (Vec<f32>, Vec<f32>),
1270 proj: crate::qwen3_tts::Lin,
1271 pos: SConv,
1272 enc_ln: (Vec<f32>, Vec<f32>),
1273 layers: Vec<HubertLayer>,
1274 heads: usize,
1275}
1276
1277impl Hubert {
1278 fn load(model: &CmfModel, sm: &Value) -> Result<Self, String> {
1279 let p = "ov.codec.semantic_model";
1280 let f = |n: &str| crate::dit::cmf_f32(model, n);
1281 let ua = |k: &str| -> Vec<usize> {
1282 sm.get(k).and_then(|v| v.as_array()).map(|a| a.iter().filter_map(|x| x.as_u64().map(|x| x as usize)).collect()).unwrap_or_default()
1283 };
1284 let (kernels, strides) = (ua("conv_kernel"), ua("conv_stride"));
1285 let hs = sm.get("hidden_size").and_then(|v| v.as_u64()).unwrap_or(768) as usize;
1286 let heads = sm.get("num_attention_heads").and_then(|v| v.as_u64()).unwrap_or(12) as usize;
1287 let nl = sm.get("num_hidden_layers").and_then(|v| v.as_u64()).unwrap_or(12) as usize;
1288 let ffn = sm.get("intermediate_size").and_then(|v| v.as_u64()).unwrap_or(3072) as usize;
1289 let pk = sm.get("num_conv_pos_embeddings").and_then(|v| v.as_u64()).unwrap_or(128) as usize;
1290 let pg = sm.get("num_conv_pos_embedding_groups").and_then(|v| v.as_u64()).unwrap_or(16) as usize;
1291 if kernels.is_empty() || kernels.len() != strides.len() {
1292 return Err("omnivoice: the semantic model's config lacks conv_kernel / conv_stride".into());
1293 }
1294 let convs = kernels
1295 .iter()
1296 .zip(&strides)
1297 .enumerate()
1298 .map(|(i, (&k, &s))| {
1299 let c = SConv::load(model, &format!("{p}.feature_extractor.conv_layers.{i}.conv"), s, 0, 1, 1)?;
1300 if c.k != k {
1301 return Err(format!("omnivoice: HuBERT conv {i} has kernel {}, config {k}", c.k));
1302 }
1303 Ok(c)
1304 })
1305 .collect::<Result<Vec<_>, String>>()?;
1306 let g = f(&format!("{p}.encoder.pos_conv_embed.conv.parametrizations.weight.original0"))?;
1308 let vname = format!("{p}.encoder.pos_conv_embed.conv.parametrizations.weight.original1");
1309 let vshape = model.tensor(&vname).map(|e| e.shape.clone()).ok_or("omnivoice: missing the positional conv weight")?;
1310 let mut v = f(&vname)?;
1311 let (o_, i_, k_) = (vshape[0], vshape[1], vshape[2]);
1312 if g.len() != k_ || k_ != pk {
1313 return Err("omnivoice: positional conv weight norm of another shape".into());
1314 }
1315 for kk in 0..k_ {
1316 let mut ss = 0f64;
1317 for a in 0..o_ * i_ {
1318 ss += (v[a * k_ + kk] as f64).powi(2);
1319 }
1320 let s = g[kk] as f64 / ss.sqrt().max(1e-12);
1321 for a in 0..o_ * i_ {
1322 v[a * k_ + kk] = (v[a * k_ + kk] as f64 * s) as f32;
1323 }
1324 }
1325 let pos = SConv::new(v, f(&format!("{p}.encoder.pos_conv_embed.conv.bias")).ok(), &vshape, 1, pk / 2, 1, pg)?;
1326 let ln = |n: &str| -> Result<(Vec<f32>, Vec<f32>), String> { Ok((f(&format!("{n}.weight"))?, f(&format!("{n}.bias"))?)) };
1327 let lin = |n: &str, r: usize, c: usize| crate::qwen3_tts::Lin::load(model, n, r, c, true);
1328 let cd = convs.last().map_or(512, |c| c.out);
1329 let layers = (0..nl)
1330 .map(|l| {
1331 let q = format!("{p}.encoder.layers.{l}");
1332 Ok(HubertLayer {
1333 q: lin(&format!("{q}.attention.q_proj"), hs, hs)?,
1334 k: lin(&format!("{q}.attention.k_proj"), hs, hs)?,
1335 v: lin(&format!("{q}.attention.v_proj"), hs, hs)?,
1336 o: lin(&format!("{q}.attention.out_proj"), hs, hs)?,
1337 ln: ln(&format!("{q}.layer_norm"))?,
1338 ff1: lin(&format!("{q}.feed_forward.intermediate_dense"), ffn, hs)?,
1339 ff2: lin(&format!("{q}.feed_forward.output_dense"), hs, ffn)?,
1340 ln2: ln(&format!("{q}.final_layer_norm"))?,
1341 })
1342 })
1343 .collect::<Result<Vec<_>, String>>()?;
1344 Ok(Self {
1345 convs,
1346 gn: ln(&format!("{p}.feature_extractor.conv_layers.0.layer_norm"))?,
1347 proj_ln: ln(&format!("{p}.feature_projection.layer_norm"))?,
1348 proj: lin(&format!("{p}.feature_projection.projection"), hs, cd)?,
1349 pos,
1350 enc_ln: ln(&format!("{p}.encoder.layer_norm"))?,
1351 layers,
1352 heads,
1353 })
1354 }
1355
1356 fn features(&self, wav16: &[f32], pool: Option<&Pool>) -> Vec<f32> {
1358 let gelu = |x: &mut [f32]| x.iter_mut().for_each(|v| *v = crate::inference::gelu_erf(*v));
1359 let mut h = wav16.to_vec();
1360 let mut n = h.len();
1361 for (i, c) in self.convs.iter().enumerate() {
1362 let (y, m) = c.apply(&h, n, pool);
1363 h = y;
1364 n = m;
1365 if i == 0 {
1366 for (ch, row) in h.chunks_exact_mut(n).enumerate() {
1368 let mean = row.iter().map(|&v| v as f64).sum::<f64>() / n as f64;
1369 let var = row.iter().map(|&v| (v as f64 - mean).powi(2)).sum::<f64>() / n as f64;
1370 let r = 1.0 / (var + 1e-5).sqrt();
1371 for v in row.iter_mut() {
1372 *v = ((*v as f64 - mean) * r) as f32 * self.gn.0[ch] + self.gn.1[ch];
1373 }
1374 }
1375 }
1376 gelu(&mut h);
1377 }
1378 let cd = self.convs.last().map_or(0, |c| c.out);
1379 let mut x = transpose(&h, cd, n); layer_norm_rows(&mut x, &self.proj_ln.0, &self.proj_ln.1, 1e-5);
1381 let mut hid = self.proj.apply(&x, n, pool);
1382 let hs = hid.len() / n.max(1);
1383 let (mut pe, m) = self.pos.apply(&transpose(&hid, n, hs), n, pool);
1385 let pe = {
1386 gelu(&mut pe);
1387 let mut keep = vec![0f32; hs * n];
1388 for c in 0..hs {
1389 keep[c * n..(c + 1) * n].copy_from_slice(&pe[c * m..c * m + n]);
1390 }
1391 transpose(&keep, hs, n)
1392 };
1393 for (a, b) in hid.iter_mut().zip(&pe) {
1394 *a += b;
1395 }
1396 layer_norm_rows(&mut hid, &self.enc_ln.0, &self.enc_ln.1, 1e-5);
1397 let mut sum: Vec<f64> = hid.iter().map(|&v| v as f64).collect();
1398 let hd = hs / self.heads;
1399 let scale = 1.0 / (hd as f32).sqrt();
1400 for l in &self.layers {
1401 let q = l.q.apply(&hid, n, pool);
1402 let k = l.k.apply(&hid, n, pool);
1403 let v = l.v.apply(&hid, n, pool);
1404 let mut att = vec![0f32; n * hs];
1405 for hh in 0..self.heads {
1406 let pick = |x: &[f32]| -> Vec<f32> { (0..n).flat_map(|t| x[t * hs + hh * hd..t * hs + (hh + 1) * hd].to_vec()).collect() };
1407 let (qh, kh, vh) = (pick(&q), pick(&k), pick(&v));
1408 let mut sc = vec![0f32; n * n];
1409 crate::fcd_ops::gemm_nt(&qh, &kh, &mut sc, n, hd, n, pool);
1410 for row in sc.chunks_exact_mut(n) {
1411 let m = row.iter().fold(f32::NEG_INFINITY, |a, &b| a.max(b * scale));
1412 let mut s = 0f64;
1413 for x in row.iter_mut() {
1414 *x = (*x * scale - m).exp();
1415 s += *x as f64;
1416 }
1417 let inv = (1.0 / s) as f32;
1418 row.iter_mut().for_each(|x| *x *= inv);
1419 }
1420 let mut oh = vec![0f32; n * hd];
1421 crate::fcd_ops::gemm_nt(&sc, &transpose(&vh, n, hd), &mut oh, n, n, hd, pool);
1422 for t in 0..n {
1423 att[t * hs + hh * hd..t * hs + (hh + 1) * hd].copy_from_slice(&oh[t * hd..(t + 1) * hd]);
1424 }
1425 }
1426 let o = l.o.apply(&att, n, pool);
1427 for (a, b) in hid.iter_mut().zip(&o) {
1428 *a += b;
1429 }
1430 layer_norm_rows(&mut hid, &l.ln.0, &l.ln.1, 1e-5);
1431 let mut f1 = l.ff1.apply(&hid, n, pool);
1432 gelu(&mut f1);
1433 let f2 = l.ff2.apply(&f1, n, pool);
1434 for (a, b) in hid.iter_mut().zip(&f2) {
1435 *a += b;
1436 }
1437 layer_norm_rows(&mut hid, &l.ln2.0, &l.ln2.1, 1e-5);
1438 for (s, &v) in sum.iter_mut().zip(&hid) {
1439 *s += v as f64;
1440 }
1441 }
1442 let k = (self.layers.len() + 1) as f64;
1443 sum.iter().map(|&s| (s / k) as f32).collect()
1444 }
1445}
1446
1447struct EncBlock {
1448 units: Vec<Unit>,
1449 snake: Snake,
1450 down: SConv,
1451}
1452
1453pub struct Encoder {
1457 hubert: Hubert,
1458 sem_conv: SConv,
1459 sem_blocks: Vec<(Vec<(SConv, SConv)>, SConv)>,
1461 ac_conv1: SConv,
1462 ac_blocks: Vec<EncBlock>,
1463 ac_snake: Snake,
1464 ac_conv2: SConv,
1465 fc: crate::qwen3_tts::Lin,
1466 rvq: Vec<(crate::qwen3_tts::Lin, Vec<f32>, Vec<f32>, crate::qwen3_tts::Lin)>,
1468 dim: usize,
1469 hidden: usize,
1470 cfg: OmniVoiceConfig,
1471 sem_rate: u32,
1472 sem_down: usize,
1473 pool: Option<Arc<Pool>>,
1474}
1475
1476impl Encoder {
1477 pub fn from_model(model: &Arc<CmfModel>, cfg: &OmniVoiceConfig, pool: Option<Arc<Pool>>) -> Result<Self, String> {
1478 let k = model
1479 .header
1480 .provenance
1481 .as_ref()
1482 .and_then(|p| p.get("omnivoice"))
1483 .and_then(|p| p.get("codec"))
1484 .cloned()
1485 .ok_or("omnivoice: provenance has no codec config")?;
1486 let sm = k.get("semantic_model_config").cloned().unwrap_or(Value::Null);
1487 let hubert = Hubert::load(model, &sm)?;
1488 let u = |v: &Value, key: &str, d: usize| v.get(key).and_then(|x| x.as_u64()).map_or(d, |x| x as usize);
1489 let ks = u(&k, "kernel_size", 3);
1490 let uks = u(&k, "unit_kernel_size", 3);
1491 let ua = |key: &str, d: Vec<usize>| -> Vec<usize> {
1492 k.get(key).and_then(|v| v.as_array()).map(|a| a.iter().filter_map(|x| x.as_u64().map(|x| x as usize)).collect()).unwrap_or(d)
1493 };
1494 let (strides, dil) = (ua("strides", vec![1, 1]), ua("block_dilations", vec![1, 1]));
1495 let s = "ov.codec.encoder_semantic";
1496 let sem_conv = SConv::load(model, &format!("{s}.conv"), 1, ks / 2, 1, 1)?;
1497 let sem_blocks = strides
1498 .iter()
1499 .enumerate()
1500 .map(|(i, &st)| {
1501 let units = dil
1502 .iter()
1503 .enumerate()
1504 .map(|(j, &d)| {
1505 Ok((
1506 SConv::load(model, &format!("{s}.conv_blocks.{i}.res_units.{j}.conv1"), 1, ((uks - 1) / 2) * d, d, 1)?,
1507 SConv::load(model, &format!("{s}.conv_blocks.{i}.res_units.{j}.conv2"), 1, 0, 1, 1)?,
1508 ))
1509 })
1510 .collect::<Result<Vec<_>, String>>()?;
1511 let kern = if st == 1 { 3 } else { 2 * st };
1512 Ok((units, SConv::load(model, &format!("{s}.conv_blocks.{i}.conv"), st, (kern - 1) / 2, 1, 1)?))
1513 })
1514 .collect::<Result<Vec<_>, String>>()?;
1515 let ac = k.get("acoustic_model_config").cloned().unwrap_or(Value::Null);
1516 let down: Vec<usize> = ac
1517 .get("downsampling_ratios")
1518 .and_then(|v| v.as_array())
1519 .map(|a| a.iter().filter_map(|x| x.as_u64().map(|x| x as usize)).collect())
1520 .unwrap_or_else(|| vec![8, 5, 4, 2, 3]);
1521 let a = "ov.codec.acoustic_encoder";
1522 let ac_blocks = down
1523 .iter()
1524 .enumerate()
1525 .map(|(i, &st)| {
1526 Ok(EncBlock {
1527 units: [1usize, 3, 9]
1528 .iter()
1529 .enumerate()
1530 .map(|(j, &d)| Unit::load(model, &format!("{a}.block.{i}.res_unit{}", j + 1), d))
1531 .collect::<Result<_, String>>()?,
1532 snake: Snake::load(model, &format!("{a}.block.{i}.snake1"))?,
1533 down: SConv::load(model, &format!("{a}.block.{i}.conv1"), st, st.div_ceil(2), 1, 1)?,
1534 })
1535 })
1536 .collect::<Result<Vec<_>, String>>()?;
1537 let q = "ov.codec.quantizer.quantizers";
1538 let es = model.tensor(&format!("{q}.0.codebook.embed")).map(|e| e.shape.clone()).ok_or("omnivoice: no codebooks")?;
1539 let (rows, dim) = (es[0], es[1]);
1540 let hidden = model.tensor("ov.codec.fc.weight").map(|e| e.shape[0]).ok_or("omnivoice: no ov.codec.fc")?;
1541 let rvq = (0..cfg.books)
1542 .map(|c| {
1543 let e = crate::dit::cmf_f32(model, &format!("{q}.{c}.codebook.embed"))?;
1544 let norms: Vec<f32> = e.chunks_exact(dim).map(|r| r.iter().map(|v| v * v).sum()).collect();
1545 if norms.len() != rows {
1546 return Err("omnivoice: codebook of another size".to_string());
1547 }
1548 Ok((
1549 crate::qwen3_tts::Lin::load(model, &format!("{q}.{c}.project_in"), dim, hidden, true)?,
1550 e,
1551 norms,
1552 crate::qwen3_tts::Lin::load(model, &format!("{q}.{c}.project_out"), hidden, dim, true)?,
1553 ))
1554 })
1555 .collect::<Result<Vec<_>, String>>()?;
1556 let sem_rate = u(&k, "semantic_sample_rate", 16_000) as u32;
1557 let hop: usize = down.iter().product();
1558 let sem_down = ((hop as f64 / (cfg.sample_rate as f64 / sem_rate as f64)) / u(&k, "downsample_factor", 320) as f64) as usize;
1559 Ok(Self {
1560 hubert,
1561 sem_conv,
1562 sem_blocks,
1563 ac_conv1: SConv::load(model, &format!("{a}.conv1"), 1, 3, 1, 1)?,
1564 ac_blocks,
1565 ac_snake: Snake::load(model, &format!("{a}.snake1"))?,
1566 ac_conv2: SConv::load(model, &format!("{a}.conv2"), 1, 1, 1, 1)?,
1567 fc: crate::qwen3_tts::Lin::load(model, "ov.codec.fc", hidden, hidden, true)?,
1568 rvq,
1569 dim,
1570 hidden,
1571 cfg: cfg.clone(),
1572 sem_rate,
1573 sem_down: sem_down.max(1),
1574 pool,
1575 })
1576 }
1577
1578 fn acoustic_len(&self, n: usize) -> usize {
1580 let mut l = self.ac_conv1.out_len(n);
1581 for b in &self.ac_blocks {
1582 l = b.down.out_len(l);
1583 }
1584 self.ac_conv2.out_len(l)
1585 }
1586
1587 pub fn encode(&self, wav: &[f32]) -> Result<Vec<Vec<u32>>, String> {
1589 let pool = self.pool.as_deref();
1590 let wav16 = crate::mimo_audio::resample_sinc(wav, self.cfg.sample_rate as u32, self.sem_rate);
1591 let mut padded = vec![0f32; 160];
1592 padded.extend(&wav16);
1593 padded.extend([0f32; 160]);
1594 let feats = self.hubert.features(&padded, pool);
1595 let sh = self.sem_conv.inp;
1596 let frames_all = feats.len() / sh;
1597 let keep: Vec<usize> = (0..frames_all).step_by(self.sem_down).collect();
1598 let ns = keep.len();
1599 let mut x = vec![0f32; sh * ns];
1600 for (j, &t) in keep.iter().enumerate() {
1601 for c in 0..sh {
1602 x[c * ns + j] = feats[t * sh + c];
1603 }
1604 }
1605 let (mut e, _) = self.sem_conv.apply(&x, ns, pool);
1606 for (units, conv) in &self.sem_blocks {
1607 for (c1, c2) in units {
1608 let mut h = e.clone();
1609 elu(&mut h);
1610 let (mut h, _) = c1.apply(&h, ns, pool);
1611 elu(&mut h);
1612 let (h, _) = c2.apply(&h, ns, pool);
1613 for (a, b) in e.iter_mut().zip(&h) {
1614 *a += b;
1615 }
1616 }
1617 e = conv.apply(&e, ns, pool).0;
1618 }
1619 let input: Vec<f32> = if self.acoustic_len(wav.len()) != ns {
1621 let p = self.cfg.hop / 2;
1622 let mut v = vec![0f32; p];
1623 v.extend(wav);
1624 v.extend(std::iter::repeat_n(0f32, p));
1625 v
1626 } else {
1627 wav.to_vec()
1628 };
1629 let (mut h, mut n) = self.ac_conv1.apply(&input, input.len(), pool);
1630 for b in &self.ac_blocks {
1631 for u in &b.units {
1632 h = u.apply(&h, n, pool);
1633 }
1634 b.snake.apply(&mut h, n);
1635 let (y, m) = b.down.apply(&h, n, pool);
1636 h = y;
1637 n = m;
1638 }
1639 self.ac_snake.apply(&mut h, n);
1640 let (ea, na) = self.ac_conv2.apply(&h, n, pool);
1641 if na != ns {
1642 return Err(format!("omnivoice: acoustic frames {na} against semantic {ns}"));
1643 }
1644 let ach = ea.len() / na;
1645 let hid = self.hidden;
1647 if ach + sh != hid {
1648 return Err(format!("omnivoice: {ach} + {sh} channels against fc's {hid}"));
1649 }
1650 let mut cat = vec![0f32; ns * hid];
1651 for t in 0..ns {
1652 for c in 0..ach {
1653 cat[t * hid + c] = ea[c * ns + t];
1654 }
1655 for c in 0..sh {
1656 cat[t * hid + ach + c] = e[c * ns + t];
1657 }
1658 }
1659 let mut resid = self.fc.apply(&cat, ns, pool);
1660 let mut codes = Vec::with_capacity(self.rvq.len());
1661 for (pin, emb, norms, pout) in &self.rvq {
1662 let xi = pin.apply(&resid, ns, pool); let rows = norms.len();
1664 let mut dots = vec![0f32; ns * rows];
1665 crate::fcd_ops::gemm_nt(&xi, emb, &mut dots, ns, self.dim, rows, pool);
1666 let mut ids = Vec::with_capacity(ns);
1667 let mut q = vec![0f32; ns * self.dim];
1668 for t in 0..ns {
1669 let xx: f32 = xi[t * self.dim..(t + 1) * self.dim].iter().map(|v| v * v).sum();
1671 let (mut best, mut bi) = (f32::NEG_INFINITY, 0usize);
1672 for r in 0..rows {
1673 let d = -(xx - 2.0 * dots[t * rows + r] + norms[r]);
1674 if d > best {
1675 best = d;
1676 bi = r;
1677 }
1678 }
1679 ids.push(bi as u32);
1680 q[t * self.dim..(t + 1) * self.dim].copy_from_slice(&emb[bi * self.dim..(bi + 1) * self.dim]);
1681 }
1682 let qo = pout.apply(&q, ns, pool);
1683 for (a, b) in resid.iter_mut().zip(&qo) {
1684 *a -= b;
1685 }
1686 codes.push(ids);
1687 }
1688 Ok(codes)
1689 }
1690
1691 pub fn voice_prompt(&self, wav24: &[f32], ref_text: &str) -> Result<VoicePrompt, String> {
1694 if ref_text.trim().is_empty() {
1695 return Err("omnivoice: the reference transcript is empty".into());
1696 }
1697 let rms = (wav24.iter().map(|&v| (v as f64) * (v as f64)).sum::<f64>() / wav24.len().max(1) as f64).sqrt() as f32;
1698 let mut w = wav24.to_vec();
1699 if rms > 0.0 && rms < 0.1 {
1700 w.iter_mut().for_each(|v| *v *= 0.1 / rms);
1701 }
1702 let mut w = remove_silence(&w, self.cfg.sample_rate, 200, 100, 200);
1703 if w.is_empty() {
1704 return Err("omnivoice: the reference is empty after silence removal".into());
1705 }
1706 let secs = w.len() as f64 / self.cfg.sample_rate as f64;
1707 if secs > 20.0 {
1708 tracing::warn!("omnivoice: the reference is {secs:.1} s long; 3-10 s clones best");
1709 }
1710 w.truncate(w.len() - w.len() % self.cfg.hop);
1711 if w.is_empty() {
1712 return Err("omnivoice: the reference is shorter than one frame".into());
1713 }
1714 Ok(VoicePrompt { codes: self.encode(&w)?, text: add_punctuation(ref_text), rms })
1715 }
1716}
1717
1718struct Seg<'a> {
1722 s: &'a [i16],
1723 rate: usize,
1724}
1725
1726fn round_half_even(x: f64) -> i64 {
1728 let f = x.floor();
1729 let d = x - f;
1730 let fi = f as i64;
1731 if d > 0.5 || (d == 0.5 && fi % 2 != 0) { fi + 1 } else { fi }
1732}
1733
1734impl Seg<'_> {
1735 fn len_ms(&self) -> i64 {
1736 round_half_even(1000.0 * self.s.len() as f64 / self.rate as f64)
1737 }
1738
1739 fn frame(&self, ms: i64) -> usize {
1740 (ms as f64 * (self.rate as f64 / 1000.0)) as usize
1741 }
1742
1743 fn slice(&self, a: i64, b: i64) -> Vec<i16> {
1746 let len = self.len_ms();
1747 let (fa, fb) = (self.frame(a.min(len)), self.frame(b.min(len)));
1748 let n = self.s.len();
1749 let mut out: Vec<i16> = if fa < fb && fa < n { self.s[fa..fb.min(n)].to_vec() } else { Vec::new() };
1750 let want = fb.saturating_sub(fa);
1751 if !out.is_empty() && out.len() < want {
1752 out.resize(want, 0);
1753 }
1754 out
1755 }
1756
1757 fn rms(x: &[i16]) -> f64 {
1758 if x.is_empty() {
1759 return 0.0;
1760 }
1761 let ss: f64 = x.iter().map(|&v| (v as f64) * (v as f64)).sum();
1762 (ss / x.len() as f64).sqrt().floor()
1763 }
1764
1765 fn dbfs(x: &[i16]) -> f64 {
1766 let r = Self::rms(x);
1767 if r == 0.0 {
1768 f64::NEG_INFINITY
1769 } else {
1770 20.0 * (r / 32768.0).log10()
1771 }
1772 }
1773
1774 fn silence(&self, min_len: i64, thresh_db: f64, step: i64) -> Vec<(i64, i64)> {
1776 let len = self.len_ms();
1777 if len < min_len {
1778 return Vec::new();
1779 }
1780 let thresh = 10f64.powf(thresh_db / 20.0) * 32768.0;
1781 let last = len - min_len;
1782 let mut starts: Vec<i64> = (0..=last).step_by(step as usize).collect();
1783 if last % step != 0 {
1784 starts.push(last);
1785 }
1786 let silent: Vec<i64> = starts.into_iter().filter(|&i| Self::rms(&self.slice(i, i + min_len)) <= thresh).collect();
1787 let Some((&first, rest)) = silent.split_first() else {
1788 return Vec::new();
1789 };
1790 let mut ranges = Vec::new();
1791 let (mut prev, mut cur) = (first, first);
1792 for &i in rest {
1793 let continuous = i == prev + step;
1794 let gap = i > prev + min_len;
1795 if !continuous && gap {
1796 ranges.push((cur, prev + min_len));
1797 cur = i;
1798 }
1799 prev = i;
1800 }
1801 ranges.push((cur, prev + min_len));
1802 ranges
1803 }
1804
1805 fn nonsilent(&self, min_len: i64, thresh_db: f64, step: i64) -> Vec<(i64, i64)> {
1806 let sil = self.silence(min_len, thresh_db, step);
1807 let len = self.len_ms();
1808 if sil.is_empty() {
1809 return vec![(0, len)];
1810 }
1811 if sil[0] == (0, len) {
1812 return Vec::new();
1813 }
1814 let mut out = Vec::new();
1815 let mut prev = 0;
1816 for &(s, e) in &sil {
1817 out.push((prev, s));
1818 prev = e;
1819 }
1820 if sil.last().is_some_and(|l| l.1 != len) {
1821 out.push((prev, len));
1822 }
1823 if out.first() == Some(&(0, 0)) {
1824 out.remove(0);
1825 }
1826 out
1827 }
1828
1829 fn leading_silence(&self, thresh_db: f64) -> i64 {
1831 let len = self.len_ms();
1832 let mut ms = 0;
1833 while Self::dbfs(&self.slice(ms, ms + 10)) < thresh_db && ms < len {
1834 ms += 10;
1835 }
1836 ms.min(len)
1837 }
1838
1839 fn tail(&self, a: i64) -> Vec<i16> {
1841 self.slice(a, self.len_ms())
1842 }
1843}
1844
1845pub fn remove_silence(audio: &[f32], rate: usize, mid: i64, lead: i64, trail: i64) -> Vec<f32> {
1848 let pcm: Vec<i16> = audio.iter().map(|&x| (x * 32768.0).clamp(-32768.0, 32767.0) as i16).collect();
1849 let wave: Vec<i16> = if mid > 0 {
1850 let seg = Seg { s: &pcm, rate };
1851 let len = seg.len_ms();
1852 let mut ranges: Vec<(i64, i64)> = seg.nonsilent(mid, -50.0, 10).into_iter().map(|(s, e)| (s - mid, e + mid)).collect();
1853 for i in 0..ranges.len().saturating_sub(1) {
1854 let (last_end, next_start) = (ranges[i].1, ranges[i + 1].0);
1855 if next_start < last_end {
1856 let m = (last_end + next_start).div_euclid(2);
1857 ranges[i].1 = m;
1858 ranges[i + 1].0 = m;
1859 }
1860 }
1861 ranges.iter().flat_map(|&(s, e)| seg.slice(s.max(0), e.min(len))).collect()
1862 } else {
1863 pcm
1864 };
1865 let seg = Seg { s: &wave, rate };
1866 let start = (seg.leading_silence(-50.0) - lead).max(0);
1867 let mut w = seg.tail(start);
1868 w.reverse();
1869 let seg = Seg { s: &w, rate };
1870 let start = (seg.leading_silence(-50.0) - trail).max(0);
1871 let mut w = seg.tail(start);
1872 w.reverse();
1873 w.iter().map(|&v| v as f32 / 32768.0).collect()
1874}
1875
1876pub fn fade_and_pad(audio: &[f32], rate: usize, pad: f32, fade: f32) -> Vec<f32> {
1878 if audio.is_empty() {
1879 return Vec::new();
1880 }
1881 let mut x = audio.to_vec();
1882 let k = ((fade as f64 * rate as f64) as usize).min(x.len() / 2);
1883 if k > 0 {
1884 let n = x.len();
1885 for i in 0..k {
1886 let w = if k == 1 { 0.0 } else { i as f32 / (k - 1) as f32 };
1887 x[i] *= w;
1888 x[n - k + i] *= 1.0 - w;
1889 }
1890 }
1891 let p = (pad as f64 * rate as f64) as usize;
1892 let mut out = vec![0f32; p];
1893 out.extend(x);
1894 out.extend(std::iter::repeat_n(0f32, p));
1895 out
1896}
1897
1898pub fn post_process(audio: &[f32], rate: usize, ref_rms: Option<f32>, postprocess: bool) -> Vec<f32> {
1901 let mut x = if postprocess { remove_silence(audio, rate, 500, 100, 100) } else { audio.to_vec() };
1902 match ref_rms {
1903 Some(r) if r < 0.1 => x.iter_mut().for_each(|v| *v *= r / 0.1),
1904 Some(_) => {}
1905 None => {
1906 let peak = x.iter().fold(0f32, |m, v| m.max(v.abs()));
1907 if peak > 1e-6 {
1908 x.iter_mut().for_each(|v| *v = *v / peak * 0.5);
1909 }
1910 }
1911 }
1912 fade_and_pad(&x, rate, 0.1, 0.1)
1913}
1914
1915#[cfg(test)]
1916mod tests {
1917 use super::*;
1918
1919 #[test]
1920 fn schedule_covers_every_code() {
1921 let s = schedule(108 * 8, 32, 0.1);
1922 assert_eq!(s.len(), 32);
1923 assert_eq!(s.iter().sum::<usize>(), 108 * 8);
1924 assert!(s[0] < s[30]);
1926 assert_eq!(s[0], (864.0 * (0.1f64 * (1.0 / 32.0) / (1.0 - 0.9 * (1.0 / 32.0)))).ceil() as usize);
1927 }
1928
1929 #[test]
1930 fn duration_follows_the_reference_rate() {
1931 let f = estimate_frames("Hello, this is a test of the OmniVoice model running natively in cortiq.", None, None, 1.0);
1933 assert!(f > 50, "{f}");
1934 assert_eq!(estimate_frames("Hi.", None, None, 1.0), (50.0 * ((text_weight("Hi.") / (text_weight("Nice to meet you.") / 25.0)) / 50.0f64).powf(1.0 / 3.0)) as usize);
1935 }
1936
1937 #[test]
1938 fn instruct_is_normalized() {
1939 assert_eq!(resolve_instruct(Some("Female, Low Pitch"), false).unwrap().as_deref(), Some("female, low pitch"));
1940 assert_eq!(resolve_instruct(Some("female, low pitch"), true).unwrap().as_deref(), Some("女,低音调"));
1941 assert_eq!(resolve_instruct(Some("男, 四川话"), false).unwrap().as_deref(), Some("男,四川话"));
1942 assert!(resolve_instruct(Some("male, female"), false).is_err());
1943 assert!(resolve_instruct(Some("robot"), false).is_err());
1944 }
1945
1946 #[test]
1947 fn text_is_combined_like_the_reference() {
1948 assert_eq!(combine_text(" 你好 世界 ", Some("Hi there\n")), "Hi there你好世界");
1949 assert_eq!(combine_text("a\t\tb (c)", None), "a b (c)");
1950 }
1951
1952 #[test]
1953 fn languages_resolve() {
1954 assert_eq!(resolve_language(Some("English")).as_deref(), Some("en"));
1955 assert_eq!(resolve_language(Some("ru")).as_deref(), Some("ru"));
1956 assert_eq!(resolve_language(Some("none")), None);
1957 }
1958
1959 #[test]
1960 fn chunks_match_the_reference() {
1961 let c = |t: &str, l: usize| chunk_text_punctuation(t, l, 3);
1963 assert_eq!(
1964 c("Mr. Smith went to Washington. He met Dr. Brown, who said: hello! Then they left... The end.", 30),
1965 ["Mr. Smith went to Washington.", "He met Dr. Brown, who said:", "hello! Then they left...", "The end."]
1966 );
1967 assert_eq!(c("你好,世界。这是一个测试!还有更多的内容,对吧?", 8), ["你好,世界。", "这是一个测试!", "还有更多的内容,", "对吧?"]);
1968 assert_eq!(
1969 c("Short. A much longer sentence follows here, with commas, and more words. Final one.", 20),
1970 ["Short.", "A much longer sentence follows here,", "with commas,", "and more words.", "Final one."]
1971 );
1972 }
1973
1974 #[test]
1975 fn fade_and_pad_shape() {
1976 let x = vec![1f32; 4800];
1977 let y = fade_and_pad(&x, 24_000, 0.1, 0.1);
1978 assert_eq!(y.len(), 4800 + 2 * 2400);
1979 assert_eq!(y[2400], 0.0);
1980 assert_eq!(y[2400 + 2399], 1.0);
1981 }
1982}