Files
texrra-engine/crates/texrra-tex-core/src/subset.rs
T

288 lines
9.3 KiB
Rust

//! Minimal TrueType `glyf` subsetting for embedded PDF fonts.
//!
//! Glyph IDs deliberately stay unchanged: the PDF Type0 font uses Identity-H
//! with CID = glyph ID, and `CIDToGIDMap /Identity`, so a subset may only
//! replace unused glyph outlines with empty ones. Other tables are copied
//! verbatim and only the SFNT offsets/checksums are rebuilt.
use std::collections::BTreeSet;
use rusttype::Font;
fn be_u16(bytes: &[u8], offset: usize) -> u16 {
u16::from_be_bytes([bytes[offset], bytes[offset + 1]])
}
fn be_u32(bytes: &[u8], offset: usize) -> u32 {
u32::from_be_bytes([
bytes[offset],
bytes[offset + 1],
bytes[offset + 2],
bytes[offset + 3],
])
}
fn be_i16(bytes: &[u8], offset: usize) -> i16 {
i16::from_be_bytes([bytes[offset], bytes[offset + 1]])
}
fn table_checksum(data: &[u8]) -> u32 {
let mut sum = 0_u32;
for chunk in data.chunks(4) {
let mut word = [0_u8; 4];
word[..chunk.len()].copy_from_slice(chunk);
sum = sum.wrapping_add(u32::from_be_bytes(word));
}
sum
}
struct Table {
tag: [u8; 4],
data: Vec<u8>,
}
/// Component glyph IDs referenced by a composite glyph.
fn components(glyph: &[u8]) -> Vec<u16> {
if glyph.len() < 10 || be_i16(glyph, 0) >= 0 {
return Vec::new();
}
let mut result = Vec::new();
let mut offset = 10;
loop {
if offset + 4 > glyph.len() {
break;
}
let flags = be_u16(glyph, offset);
let index = be_u16(glyph, offset + 2);
result.push(index);
offset += 4;
offset += if flags & 0x0001 != 0 { 4 } else { 2 };
if flags & 0x0008 != 0 {
offset += 2;
} else if flags & 0x0040 != 0 {
offset += 4;
} else if flags & 0x0080 != 0 {
offset += 8;
}
if flags & 0x0020 == 0 {
break;
}
}
result
}
/// Subset a TrueType font to `characters`, preserving glyph IDs.
///
/// The returned font is still a valid SFNT file. Unused glyphs have empty
/// outlines, which is enough for PDF viewers because the page only references
/// used CIDs.
pub fn subset_font(bytes: &[u8], font: &Font, characters: &BTreeSet<char>) -> Vec<u8> {
if bytes.len() < 12 {
return bytes.to_vec();
}
let num_tables = usize::from(be_u16(bytes, 4));
let mut tables = Vec::with_capacity(num_tables);
for index in 0..num_tables {
let record = 12 + index * 16;
if record + 16 > bytes.len() {
return bytes.to_vec();
}
let mut tag = [0_u8; 4];
tag.copy_from_slice(&bytes[record..record + 4]);
let offset = be_u32(bytes, record + 8) as usize;
let length = be_u32(bytes, record + 12) as usize;
if offset + length > bytes.len() {
return bytes.to_vec();
}
tables.push(Table {
tag,
data: bytes[offset..offset + length].to_vec(),
});
}
let Some(head_index) = tables.iter().position(|table| &table.tag == b"head") else {
return bytes.to_vec();
};
let Some(loca_index) = tables.iter().position(|table| &table.tag == b"loca") else {
return bytes.to_vec();
};
let Some(glyf_index) = tables.iter().position(|table| &table.tag == b"glyf") else {
return bytes.to_vec();
};
let Some(maxp_index) = tables.iter().position(|table| &table.tag == b"maxp") else {
return bytes.to_vec();
};
if tables[head_index].data.len() < 54 || tables[maxp_index].data.len() < 6 {
return bytes.to_vec();
}
let num_glyphs = usize::from(be_u16(&tables[maxp_index].data, 4));
let long_loca = be_i16(&tables[head_index].data, 50) != 0;
let loca_len = if long_loca {
(num_glyphs + 1) * 4
} else {
(num_glyphs + 1) * 2
};
if tables[loca_index].data.len() < loca_len {
return bytes.to_vec();
}
let mut offsets = Vec::with_capacity(num_glyphs + 1);
for index in 0..=num_glyphs {
let value = if long_loca {
be_u32(&tables[loca_index].data, index * 4) as usize
} else {
usize::from(be_u16(&tables[loca_index].data, index * 2)) * 2
};
offsets.push(value);
}
let glyf = &tables[glyf_index].data;
let mut used = BTreeSet::new();
used.insert(0_u16);
for character in characters {
used.insert(font.glyph(*character).id().0 as u16);
}
// Composite glyphs reference component glyphs by ID. Keep those too, or
// the subsetted outline points at empty glyphs.
loop {
let mut added = false;
for glyph in used.clone() {
let index = usize::from(glyph);
if index >= num_glyphs {
continue;
}
let start = offsets[index];
let end = offsets[index + 1];
if end <= start || end > glyf.len() {
continue;
}
for component in components(&glyf[start..end]) {
if used.insert(component) {
added = true;
}
}
}
if !added {
break;
}
}
let mut new_glyf = Vec::new();
let mut new_loca = Vec::with_capacity(num_glyphs + 1);
for glyph in 0..num_glyphs {
let start = offsets[glyph];
let end = offsets[glyph + 1];
new_loca.push(new_glyf.len());
if used.contains(&(glyph as u16)) && end > start && end <= glyf.len() {
new_glyf.extend_from_slice(&glyf[start..end]);
}
while new_glyf.len() % 2 != 0 {
new_glyf.push(0);
}
}
new_loca.push(new_glyf.len());
if long_loca {
let mut bytes = Vec::with_capacity(new_loca.len() * 4);
for offset in &new_loca {
bytes.extend_from_slice(&(*offset as u32).to_be_bytes());
}
tables[loca_index].data = bytes;
} else {
if new_glyf.len() / 2 > usize::from(u16::MAX) {
return bytes.to_vec();
}
let mut bytes = Vec::with_capacity(new_loca.len() * 2);
for offset in &new_loca {
bytes.extend_from_slice(&((*offset / 2) as u16).to_be_bytes());
}
tables[loca_index].data = bytes;
}
tables[glyf_index].data = new_glyf;
// The head checksum adjustment must be zero while table checksums are
// computed.
tables[head_index].data[8..12].fill(0);
let mut output = Vec::new();
output.extend_from_slice(&bytes[..12]);
let directory_len = 12 + tables.len() * 16;
let mut data_offset = directory_len;
let mut records = Vec::with_capacity(tables.len());
for table in &tables {
let checksum = table_checksum(&table.data);
records.push((table.tag, checksum, data_offset, table.data.len()));
data_offset += table.data.len();
data_offset = data_offset.div_ceil(4) * 4;
}
for (tag, checksum, offset, length) in &records {
output.extend_from_slice(tag);
output.extend_from_slice(&checksum.to_be_bytes());
output.extend_from_slice(&(*offset as u32).to_be_bytes());
output.extend_from_slice(&(*length as u32).to_be_bytes());
}
for table in &tables {
output.extend_from_slice(&table.data);
while output.len() % 4 != 0 {
output.push(0);
}
}
let adjustment = 0xB1B0_AFBA_u32.wrapping_sub(table_checksum(&output));
if let Some((_, _, offset, _)) = records.iter().find(|(tag, _, _, _)| tag == b"head") {
output[offset + 8..offset + 12].copy_from_slice(&adjustment.to_be_bytes());
}
output
}
#[cfg(test)]
mod tests {
use super::*;
fn table<'a>(font: &'a [u8], tag: &[u8; 4]) -> &'a [u8] {
let count = usize::from(be_u16(font, 4));
for index in 0..count {
let record = 12 + index * 16;
if &font[record..record + 4] == tag {
let offset = be_u32(font, record + 8) as usize;
let length = be_u32(font, record + 12) as usize;
return &font[offset..offset + length];
}
}
panic!("missing table");
}
#[test]
fn composite_components_survive_subsetting() {
let bytes = include_bytes!("../../../assets/fonts-subset/LiberationSerif-Regular.ttf");
let font = Font::from_bytes(&bytes[..]).expect("font");
let mut characters = BTreeSet::new();
characters.insert('\u{e9}');
let subset = subset_font(bytes, &font, &characters);
let maxp = table(&subset, b"maxp");
let num_glyphs = usize::from(be_u16(maxp, 4));
let head = table(&subset, b"head");
let long_loca = be_i16(head, 50) != 0;
let loca = table(&subset, b"loca");
let glyf = table(&subset, b"glyf");
let offset = |glyph: usize| {
if long_loca {
be_u32(loca, glyph * 4) as usize
} else {
usize::from(be_u16(loca, glyph * 2)) * 2
}
};
let glyph_len = |glyph: usize| {
assert!(glyph < num_glyphs);
offset(glyph + 1) - offset(glyph)
};
let composite = font.glyph('\u{e9}').id().0 as usize;
let component = font.glyph('e').id().0 as usize;
assert!(glyph_len(composite) > 0, "accented glyph has no outline");
assert!(glyph_len(component) > 0, "component glyph was dropped");
assert!(glyf.len() < 4096, "subset kept too much glyph data");
}
}