Skip to content

FilmCraft: An open-source, nonlinear video editor written by scratch in pure Rust

security(text): bound text and phonemizer work (#2870)

Earl Cof6e053b352a8
diff --git a/crates/text/src/layout.rs b/crates/text/src/layout.rs
index 50fbed58e..68d485e7e 100644
--- a/crates/text/src/layout.rs
+++ b/crates/text/src/layout.rs
@@ -544,10 +544,18 @@ fn paragraph(text: &str, base: usize, sty: &Styles, para: &ParagraphStyle) -> Ve
let mut cluster_starts: Vec<usize> = extents.keys().copied().collect();
cluster_starts.sort_unstable();
let char_bytes: Vec<usize> = text[r.clone()].char_indices().map(|(b, _)| r.start + b).collect();
+ let mut first_member = 0usize;
for (ci, &cs) in cluster_starts.iter().enumerate() {
let (x0, x1, rtl) = extents[&cs];
let next = cluster_starts.get(ci + 1).copied().unwrap_or(r.end);
- let members: Vec<usize> = char_bytes.iter().copied().filter(|b| *b >= cs && *b < next).collect();
+ while first_member < char_bytes.len() && char_bytes[first_member] < cs {
+ first_member += 1;
+ }
+ let member_start = first_member;
+ while first_member < char_bytes.len() && char_bytes[first_member] < next {
+ first_member += 1;
+ }
+ let members = &char_bytes[member_start..first_member];
let n = members.len().max(1) as f32;
for (mi, b) in members.iter().enumerate() {
let f = mi as f32 / n;
diff --git a/crates/text/src/sfnt.rs b/crates/text/src/sfnt.rs
index c000f4423..fec6ed38d 100644
--- a/crates/text/src/sfnt.rs
+++ b/crates/text/src/sfnt.rs
@@ -108,22 +108,43 @@ fn name_string(b: &[u8], id: u16) -> Option<String> {
if nid != id {
continue;
}
- let raw = b.get(storage + off..storage + off + len)?;
- let (rank, s) = match plat {
+ let rank = match plat {
3 if enc == 1 || enc == 10 => {
+ if best.as_ref().is_some_and(|(current, _)| *current <= if lang == 0x409 { 0 } else { 1 }) {
+ continue;
+ }
+ if lang == 0x409 { 0 } else { 1 }
+ }
+ 0 => {
+ if best.as_ref().is_some_and(|(current, _)| *current <= 2) {
+ continue;
+ }
+ 2
+ }
+ 1 if enc == 0 => {
+ if best.as_ref().is_some_and(|(current, _)| *current <= 3) {
+ continue;
+ }
+ 3
+ }
+ _ => continue,
+ };
+ // Only decode a record that can improve the selected name. A hostile name table may
+ // point thousands of records at the same huge string.
+ let raw = b.get(storage + off..storage + off + len)?;
+ let s = match plat {
+ 3 => {
let u: Vec<u16> = raw.as_chunks::<2>().0.iter().map(|c| u16::from_be_bytes([c[0], c[1]])).collect();
- (if lang == 0x409 { 0 } else { 1 }, String::from_utf16_lossy(&u))
+ String::from_utf16_lossy(&u)
}
0 => {
let u: Vec<u16> = raw.as_chunks::<2>().0.iter().map(|c| u16::from_be_bytes([c[0], c[1]])).collect();
- (2, String::from_utf16_lossy(&u))
+ String::from_utf16_lossy(&u)
}
- 1 if enc == 0 => (3, raw.iter().map(|&c| if c < 128 { c as char } else { '?' }).collect()),
- _ => continue,
+ 1 => raw.iter().map(|&c| if c < 128 { c as char } else { '?' }).collect(),
+ _ => return None,
};
- if best.as_ref().is_none_or(|(r0, _)| rank < *r0) {
- best = Some((rank, s));
- }
+ best = Some((rank, s));
}
best.map(|(_, s)| s).filter(|s| !s.trim().is_empty())
}
@@ -185,4 +206,27 @@ mod tests {
assert_eq!(faces.len(), 1);
assert_eq!((faces[0].index, faces[0].family.as_str(), faces[0].style.as_str()), (1, "Inter", "Regular"));
}
+
+ #[test]
+ fn later_non_improving_name_records_are_not_decoded() {
+ // The first record is the preferred Windows-English value. The second names an invalid
+ // range: it must be ignored instead of making the whole name lookup fail.
+ let mut table = vec![0; 30];
+ table[2..4].copy_from_slice(&2u16.to_be_bytes());
+ table[4..6].copy_from_slice(&30u16.to_be_bytes());
+ let first = 6usize;
+ table[first..first + 2].copy_from_slice(&3u16.to_be_bytes());
+ table[first + 2..first + 4].copy_from_slice(&1u16.to_be_bytes());
+ table[first + 4..first + 6].copy_from_slice(&0x409u16.to_be_bytes());
+ table[first + 6..first + 8].copy_from_slice(&1u16.to_be_bytes());
+ table[first + 8..first + 10].copy_from_slice(&4u16.to_be_bytes());
+ let second = first + 12;
+ table[second..second + 2].copy_from_slice(&3u16.to_be_bytes());
+ table[second + 2..second + 4].copy_from_slice(&1u16.to_be_bytes());
+ table[second + 4..second + 6].copy_from_slice(&0x409u16.to_be_bytes());
+ table[second + 6..second + 8].copy_from_slice(&1u16.to_be_bytes());
+ table[second + 8..second + 10].copy_from_slice(&u16::MAX.to_be_bytes());
+ table.extend_from_slice(&[0, b'A', 0, b'B']);
+ assert_eq!(name_string(&table, 1).as_deref(), Some("AB"));
+ }
}
diff --git a/crates/tts-text/src/phonemize.rs b/crates/tts-text/src/phonemize.rs
index e380cc5d9..d3e0882df 100644
--- a/crates/tts-text/src/phonemize.rs
+++ b/crates/tts-text/src/phonemize.rs
@@ -27,6 +27,10 @@ pub const MAX_CHUNK_CHARS: usize = 400;
const MAX_DICT_BYTES: usize = 16 * 1024 * 1024;
/// Maximum number of dictionary entries.
const MAX_DICT_ENTRIES: usize = 500_000;
+/// Most ARPAbet symbols retained for one dictionary pronunciation.
+const MAX_PRONUNCIATION_PHONES: usize = 256;
+/// Long unknown words are not useful narration and can make suffix fallback recurse repeatedly.
+const MAX_LETTER_TO_SOUND_CHARS: usize = 512;
/// Maximum number of overrides honoured (excess ignored, not an error).
const MAX_OVERRIDES: usize = 1_000;
/// Maximum length of one override value (longer ones ignored).
@@ -98,7 +102,7 @@ impl Lexicon {
skipped += 1;
continue;
};
- let phones: Vec<&str> = parts.collect();
+ let phones: Vec<&str> = parts.by_ref().take(MAX_PRONUNCIATION_PHONES + 1).collect();
if phones.is_empty() {
if had_comment {
continue;
@@ -106,6 +110,10 @@ impl Lexicon {
skipped += 1;
continue;
}
+ if phones.len() > MAX_PRONUNCIATION_PHONES {
+ skipped += 1;
+ continue;
+ }
// `WORD(2)` alternates fold into the same key.
let key = match (head.find('('), head.rfind(')')) {
(Some(open), Some(close)) if close > open + 1 && head.get(open + 1..close).is_some_and(|d| d.chars().all(|c| c.is_ascii_digit())) => {
@@ -298,19 +306,34 @@ fn flush_sentence(sentence: &mut Vec<Token>, chunks: &mut Vec<Chunk>, lex: &Lexi
/// Split a phoneme string longer than [`MAX_CHUNK_CHARS`] at the last `,` `;` `:`
/// before the limit, else at the last space, else hard-split at the limit.
fn split_long_chunk(s: String) -> Vec<String> {
- if s.chars().count() <= MAX_CHUNK_CHARS {
- return vec![s];
+ let mut out = Vec::new();
+ let mut start = 0usize;
+ while start < s.len() {
+ let rest = &s[start..];
+ let Some((limit, _)) = rest.char_indices().nth(MAX_CHUNK_CHARS) else {
+ let piece = rest.trim().to_string();
+ if !piece.is_empty() {
+ out.push(piece);
+ }
+ break;
+ };
+ let head = &rest[..limit];
+ let cut = head
+ .char_indices()
+ .rev()
+ .find(|&(_, c)| matches!(c, ',' | ';' | ':'))
+ .map(|(i, _)| i + 1)
+ .or_else(|| head.rfind(' ').map(|i| i + 1))
+ .unwrap_or(limit);
+ let piece = head[..cut].trim_end();
+ if !piece.is_empty() {
+ out.push(piece.to_string());
+ }
+ start += cut;
+ while s.get(start..).and_then(|rest| rest.chars().next()).is_some_and(char::is_whitespace) {
+ start += s[start..].chars().next().map(char::len_utf8).unwrap_or(0);
+ }
}
- let limit = s.char_indices().map(|(i, _)| i).nth(MAX_CHUNK_CHARS).unwrap_or(s.len());
- let head_boundary = s.get(..limit).and_then(|head| {
- head.char_indices().rev().find(|&(_, c)| matches!(c, ',' | ';' | ':')).map(|(i, _)| i + 1).or_else(|| head.rfind(' ').map(|i| i + 1)).or(Some(limit))
- });
- let Some(cut) = head_boundary else { return vec![s] };
- let head = s.get(..cut).unwrap_or("").trim_end().to_string();
- let tail = s.get(cut..).unwrap_or("").trim_start().to_string();
- let mut out = vec![head];
- out.extend(split_long_chunk(tail));
- out.retain(|p| !p.is_empty());
out
}
@@ -698,7 +721,7 @@ fn past_ed(last: &Phone) -> &'static str {
/// syllable (on the vowel before -tion/-sion). Always pronounceable.
fn letter_to_sound(word: &str) -> Option<String> {
let letters: Vec<char> = word.chars().filter(|c| c.is_ascii_alphabetic()).collect();
- if letters.is_empty() {
+ if letters.is_empty() || letters.len() > MAX_LETTER_TO_SOUND_CHARS {
return None;
}
// -ture / -sure endings (nature, measure): the e belongs to the suffix, so it
@@ -741,10 +764,9 @@ fn letter_to_sound(word: &str) -> Option<String> {
let mut i = 0usize;
while i < n {
let Some(rest) = chars.get(i..) else { break };
- let rest_str: String = rest.iter().collect();
let at_start = i == 0;
// Multi-letter rules first (longest match wins).
- if rest_str.ends_with("tion") && rest_str.len() == 4 {
+ if rest.len() == 4 && rest.iter().copied().eq("tion".chars()) {
// The vowel before the suffix takes the primary stress.
if let Some(&last) = vowel_positions.last()
&& let Some(v) = out.get_mut(last)
@@ -756,7 +778,7 @@ fn letter_to_sound(word: &str) -> Option<String> {
out.push("n".into());
break;
}
- if rest_str.ends_with("sion") && rest_str.len() == 4 {
+ if rest.len() == 4 && rest.iter().copied().eq("sion".chars()) {
if let Some(&last) = vowel_positions.last()
&& let Some(v) = out.get_mut(last)
{
@@ -767,35 +789,35 @@ fn letter_to_sound(word: &str) -> Option<String> {
out.push("n".into());
break;
}
- if rest_str.starts_with("sch") {
+ if rest.starts_with(&['s', 'c', 'h']) {
out.push("s".into());
out.push("k".into());
i += 3;
continue;
}
- if rest_str == "sten" {
+ if rest == ['s', 't', 'e', 'n'] {
// listen
out.push("s".into());
out.push("ə".into());
out.push("n".into());
break;
}
- if rest_str == "gue" {
+ if rest == ['g', 'u', 'e'] {
out.push("ɡ".into());
break;
}
- if rest_str == "que" {
+ if rest == ['q', 'u', 'e'] {
out.push("k".into());
break;
}
- if rest_str.starts_with("ough") {
+ if rest.starts_with(&['o', 'u', 'g', 'h']) {
// A famously irregular group; pick the "thought" vowel, f when final.
out.push("ɔ".into());
- if rest_str == "ough" {
+ if rest == ['o', 'u', 'g', 'h'] {
out.push("f".into());
break;
}
- if rest_str.starts_with("ought") {
+ if rest.starts_with(&['o', 'u', 'g', 'h', 't']) {
out.push("t".into());
i += 5;
continue;
@@ -803,13 +825,13 @@ fn letter_to_sound(word: &str) -> Option<String> {
i += 3;
continue;
}
- if rest_str.starts_with("gu") && rest_str.len() > 2 {
+ if rest.starts_with(&['g', 'u']) && rest.len() > 2 {
// The u is silent before a vowel (guard, guess).
out.push("ɡ".into());
i += 2;
continue;
}
- if rest_str.starts_with("ps") && at_start {
+ if rest.starts_with(&['p', 's']) && at_start {
out.push("s".into());
i += 2;
continue;
@@ -1170,6 +1192,18 @@ PERCENT P ER0 S EH1 N T
assert_eq!(lex.pronunciations("TRAIL").map(|v| v.first().map(String::as_str)), Some(Some("AE1 T")));
}
+ #[test]
+ fn skips_an_unreasonably_long_dictionary_pronunciation() {
+ let mut input = String::from("GOOD AE1\nTOO_LONG");
+ for _ in 0..=MAX_PRONUNCIATION_PHONES {
+ input.push_str(" AE1");
+ }
+ input.push('\n');
+ let lex = Lexicon::parse_cmudict(input.as_bytes()).unwrap();
+ assert_eq!(lex.len(), 1);
+ assert_eq!(lex.skipped(), 1);
+ }
+
#[test]
fn refuses_oversized_dictionaries() {
let oversized = vec![b'a'; MAX_DICT_BYTES + 1];
@@ -1335,6 +1369,19 @@ PERCENT P ER0 S EH1 N T
}
}
+ #[test]
+ fn chunk_splitting_is_iterative_for_many_chunks() {
+ let input = "a".repeat(MAX_CHUNK_CHARS * 2_000);
+ let chunks = split_long_chunk(input);
+ assert_eq!(chunks.len(), 2_000);
+ assert!(chunks.iter().all(|chunk| chunk.len() == MAX_CHUNK_CHARS));
+ }
+
+ #[test]
+ fn letter_to_sound_refuses_an_absurdly_long_unknown_word() {
+ assert!(letter_to_sound(&"ture".repeat(MAX_LETTER_TO_SOUND_CHARS)).is_none());
+ }
+
#[test]
fn am_reads_the_letter_name_not_the_article() {
for text in ["At 9:00 a.m.", "At 9:00am"] {