Skip to main content

read_fonts/tables/
bitmap.rs

1//! Common bitmap (EBLC/EBDT/CBLC/CBDT) types.
2
3use crate::{array, offset::CheckedOffset};
4
5include!("../../generated/generated_bitmap.rs");
6
7impl BitmapSize {
8    /// Returns the bitmap location information for the given glyph.
9    ///
10    /// The `offset_data` parameter is provided by the `offset_data()` method
11    /// of the parent `Eblc` or `Cblc` table.
12    ///
13    /// The resulting [`BitmapLocation`] value is used by the `data()` method
14    /// in the associated `Ebdt` or `Cbdt` table to extract the bitmap data.
15    pub fn location(
16        &self,
17        offset_data: FontData,
18        glyph_id: GlyphId,
19    ) -> Result<BitmapLocation, ReadError> {
20        if !(self.start_glyph_index()..=self.end_glyph_index()).contains(&glyph_id) {
21            return Err(ReadError::OutOfBounds);
22        }
23        let subtable_list = self.index_subtable_list(offset_data)?;
24        let mut location = BitmapLocation {
25            bit_depth: self.bit_depth,
26            ..BitmapLocation::default()
27        };
28        for record in subtable_list.index_subtable_records() {
29            let subtable = record.index_subtable(subtable_list.offset_data())?;
30            if !(record.first_glyph_index()..=record.last_glyph_index()).contains(&glyph_id) {
31                continue;
32            }
33            // glyph index relative to the first glyph in the subtable
34            let glyph_ix =
35                glyph_id.to_u32() as usize - record.first_glyph_index().to_u32() as usize;
36            match &subtable {
37                IndexSubtable::Format1(st) => {
38                    location.format = st.image_format();
39                    let [first_offset, second_offset] =
40                        array::get_pair(st.sbit_offsets(), glyph_ix)?.map(|o| o.get() as usize);
41                    let base = CheckedOffset::new(st.image_data_offset() as usize);
42                    let start = base.add(first_offset).ok_or_oob()?;
43                    let end = base.add(second_offset).ok_or_oob()?;
44                    location.data_offset = start;
45                    if end < start {
46                        return Err(ReadError::OutOfBounds);
47                    }
48                    location.data_size = end - start;
49                }
50                IndexSubtable::Format2(st) => {
51                    location.format = st.image_format();
52                    let data_size = st.image_size() as usize;
53                    location.data_size = data_size;
54                    location.data_offset = CheckedOffset::new(glyph_ix)
55                        .mul(data_size)
56                        .add(st.image_data_offset() as usize)
57                        .ok_or_oob()?;
58                    location.metrics = Some(*st.big_metrics());
59                }
60                IndexSubtable::Format3(st) => {
61                    location.format = st.image_format();
62                    let [first_offset, second_offset] =
63                        array::get_pair(st.sbit_offsets(), glyph_ix)?.map(|o| o.get() as usize);
64                    let base = CheckedOffset::new(st.image_data_offset() as usize);
65                    let start = base.add(first_offset).ok_or_oob()?;
66                    let end = base.add(second_offset).ok_or_oob()?;
67                    location.data_offset = start;
68                    if end < start {
69                        return Err(ReadError::OutOfBounds);
70                    }
71                    location.data_size = end - start;
72                }
73                IndexSubtable::Format4(st) => {
74                    location.format = st.image_format();
75                    let array = st.glyph_array();
76                    let array_ix = match array
77                        .binary_search_by(|x| x.glyph_id().to_u32().cmp(&glyph_id.to_u32()))
78                    {
79                        Ok(ix) => ix,
80                        _ => return Err(ReadError::InvalidCollectionIndex(glyph_id.to_u32())),
81                    };
82                    let [first_offset, second_offset] =
83                        array::get_pair(array, array_ix)?.map(|p| p.sbit_offset() as usize);
84                    let base = CheckedOffset::new(st.image_data_offset() as usize);
85                    let start = base.add(first_offset).ok_or_oob()?;
86                    let end = base.add(second_offset).ok_or_oob()?;
87                    location.data_offset = start;
88                    if end < start {
89                        return Err(ReadError::OutOfBounds);
90                    }
91                    location.data_size = end - start;
92                }
93                IndexSubtable::Format5(st) => {
94                    location.format = st.image_format();
95                    let array = st.glyph_array();
96                    let array_ix = match array
97                        .binary_search_by(|gid| gid.get().to_u32().cmp(&glyph_id.to_u32()))
98                    {
99                        Ok(ix) => ix,
100                        _ => return Err(ReadError::InvalidCollectionIndex(glyph_id.to_u32())),
101                    };
102                    let data_size = st.image_size() as usize;
103                    location.data_size = data_size;
104                    location.data_offset = CheckedOffset::new(array_ix)
105                        .mul(data_size)
106                        .add(st.image_data_offset() as usize)
107                        .ok_or_oob()?;
108                    location.metrics = Some(*st.big_metrics());
109                }
110            }
111            return Ok(location);
112        }
113        Err(ReadError::OutOfBounds)
114    }
115
116    /// Returns the [IndexSubtableList] associated with this size.
117    ///
118    /// The `offset_data` parameter is provided by the `offset_data()` method
119    /// of the parent `Eblc` or `Cblc` table.
120    pub fn index_subtable_list<'a>(
121        &self,
122        offset_data: FontData<'a>,
123    ) -> Result<IndexSubtableList<'a>, ReadError> {
124        let start = self.index_subtable_list_offset() as usize;
125        // FreeType ignores the declared size and bounds reads by the end of the
126        // parent table. Some fonts, such as ProggyClean, rely on this behavior
127        // because they set indexTablesSize to the size of the index subtable
128        // record array alone, excluding the referenced subtables.
129        //
130        // See `tt_sbit_decoder_init` and `tt_sbit_decoder_load_image` in FreeType.
131        // <https://gitlab.freedesktop.org/freetype/freetype/-/blob/VER-2-13-3/src/sfnt/ttsbit.c#L1241>
132        let data = offset_data.split_off(start).ok_or(ReadError::OutOfBounds)?;
133        IndexSubtableList::read(data, self.number_of_index_subtables())
134    }
135}
136
137#[derive(Clone, Default)]
138pub struct BitmapLocation {
139    /// Format of EBDT/CBDT image data.
140    pub format: u16,
141    /// Offset in bytes from the start of the EBDT/CBDT table.
142    pub data_offset: usize,
143    /// Size of the image data in bytes.
144    pub data_size: usize,
145    /// Bit depth from the associated size. Required for computing image data
146    /// size when unspecified.
147    pub bit_depth: u8,
148    /// Full metrics, if present in the EBLC/CBLC table.
149    pub metrics: Option<BigGlyphMetrics>,
150}
151
152impl BitmapLocation {
153    /// Returns true if the location references an empty bitmap glyph such as
154    /// a space.
155    pub fn is_empty(&self) -> bool {
156        self.data_size == 0
157    }
158}
159
160#[derive(Copy, Clone, PartialEq, Eq, Debug)]
161pub enum BitmapDataFormat {
162    /// The full bitmap is tightly packed according to the bit depth.
163    BitAligned,
164    /// Each row of the data is aligned to a byte boundary.
165    ByteAligned,
166    Png,
167}
168
169#[derive(Clone)]
170pub enum BitmapMetrics {
171    Small(SmallGlyphMetrics),
172    Big(BigGlyphMetrics),
173}
174
175#[derive(Clone)]
176pub struct BitmapData<'a> {
177    pub metrics: BitmapMetrics,
178    pub content: BitmapContent<'a>,
179}
180
181#[derive(Clone)]
182pub enum BitmapContent<'a> {
183    Data(BitmapDataFormat, &'a [u8]),
184    Composite(&'a [BdtComponent]),
185}
186
187pub(crate) fn bitmap_data<'a>(
188    offset_data: FontData<'a>,
189    location: &BitmapLocation,
190    is_color: bool,
191) -> Result<BitmapData<'a>, ReadError> {
192    let start = location.data_offset;
193    let end = CheckedOffset::new(start)
194        .add(location.data_size)
195        .ok_or_oob()?;
196    let mut image_data = offset_data
197        .slice(start..end)
198        .ok_or(ReadError::OutOfBounds)?
199        .cursor();
200    match location.format {
201        // Small metrics, byte-aligned data
202        // <https://learn.microsoft.com/en-us/typography/opentype/spec/ebdt#format-1-small-metrics-byte-aligned-data>
203        1 => {
204            let metrics = read_small_metrics(&mut image_data)?;
205            // The data for each row is padded to a byte boundary
206            let pitch = (metrics.width as usize * location.bit_depth as usize).div_ceil(8);
207            let height = metrics.height as usize;
208            let data = image_data.read_array::<u8>(pitch * height)?;
209            Ok(BitmapData {
210                metrics: BitmapMetrics::Small(metrics),
211                content: BitmapContent::Data(BitmapDataFormat::ByteAligned, data),
212            })
213        }
214        // Small metrics, bit-aligned data
215        // <https://learn.microsoft.com/en-us/typography/opentype/spec/ebdt#format-2-small-metrics-bit-aligned-data>
216        2 => {
217            let metrics = read_small_metrics(&mut image_data)?;
218            let width = metrics.width as usize * location.bit_depth as usize;
219            let height = metrics.height as usize;
220            // The data is tightly packed
221            let data = image_data.read_array::<u8>((width * height).div_ceil(8))?;
222            Ok(BitmapData {
223                metrics: BitmapMetrics::Small(metrics),
224                content: BitmapContent::Data(BitmapDataFormat::BitAligned, data),
225            })
226        }
227        // Format 3 is obsolete
228        // <https://learn.microsoft.com/en-us/typography/opentype/spec/ebdt#format-3-obsolete>
229        // Format 4 is not supported
230        // <https://learn.microsoft.com/en-us/typography/opentype/spec/ebdt#format-4-not-supported-metrics-in-eblc-compressed-data>
231        // ---
232        // Metrics in EBLC/CBLC, bit-aligned image data only
233        // <https://learn.microsoft.com/en-us/typography/opentype/spec/ebdt#format-5-metrics-in-eblc-bit-aligned-image-data-only>
234        5 => {
235            let metrics = location.metrics.ok_or(ReadError::MalformedData(
236                "expected metrics from location table",
237            ))?;
238            let width = metrics.width as usize * location.bit_depth as usize;
239            let height = metrics.height as usize;
240            // The data is tightly packed
241            let data = image_data.read_array::<u8>((width * height).div_ceil(8))?;
242            Ok(BitmapData {
243                metrics: BitmapMetrics::Big(metrics),
244                content: BitmapContent::Data(BitmapDataFormat::BitAligned, data),
245            })
246        }
247        // Big metrics, byte-aligned data
248        // <https://learn.microsoft.com/en-us/typography/opentype/spec/ebdt#format-6-big-metrics-byte-aligned-data>
249        6 => {
250            let metrics = read_big_metrics(&mut image_data)?;
251            // The data for each row is padded to a byte boundary
252            let pitch = (metrics.width as usize * location.bit_depth as usize).div_ceil(8);
253            let height = metrics.height as usize;
254            let data = image_data.read_array::<u8>(pitch * height)?;
255            Ok(BitmapData {
256                metrics: BitmapMetrics::Big(metrics),
257                content: BitmapContent::Data(BitmapDataFormat::ByteAligned, data),
258            })
259        }
260        // Big metrics, bit-aligned data
261        // <https://learn.microsoft.com/en-us/typography/opentype/spec/ebdt#format7-big-metrics-bit-aligned-data>
262        7 => {
263            let metrics = read_big_metrics(&mut image_data)?;
264            let width = metrics.width as usize * location.bit_depth as usize;
265            let height = metrics.height as usize;
266            // The data is tightly packed
267            let data = image_data.read_array::<u8>((width * height).div_ceil(8))?;
268            Ok(BitmapData {
269                metrics: BitmapMetrics::Big(metrics),
270                content: BitmapContent::Data(BitmapDataFormat::BitAligned, data),
271            })
272        }
273        // Small metrics, component data
274        // <https://learn.microsoft.com/en-us/typography/opentype/spec/ebdt#format-8-small-metrics-component-data>
275        8 => {
276            let metrics = read_small_metrics(&mut image_data)?;
277            let _pad = image_data.read::<u8>()?;
278            let count = image_data.read::<u16>()? as usize;
279            let components = image_data.read_array::<BdtComponent>(count)?;
280            Ok(BitmapData {
281                metrics: BitmapMetrics::Small(metrics),
282                content: BitmapContent::Composite(components),
283            })
284        }
285        // Big metrics, component data
286        // <https://learn.microsoft.com/en-us/typography/opentype/spec/ebdt#format-9-big-metrics-component-data>
287        9 => {
288            let metrics = read_big_metrics(&mut image_data)?;
289            let count = image_data.read::<u16>()? as usize;
290            let components = image_data.read_array::<BdtComponent>(count)?;
291            Ok(BitmapData {
292                metrics: BitmapMetrics::Big(metrics),
293                content: BitmapContent::Composite(components),
294            })
295        }
296        // Small metrics, PNG image data
297        // <https://learn.microsoft.com/en-us/typography/opentype/spec/cbdt#format-17-small-metrics-png-image-data>
298        17 if is_color => {
299            let metrics = read_small_metrics(&mut image_data)?;
300            let data_len = image_data.read::<u32>()? as usize;
301            let data = image_data.read_array::<u8>(data_len)?;
302            Ok(BitmapData {
303                metrics: BitmapMetrics::Small(metrics),
304                content: BitmapContent::Data(BitmapDataFormat::Png, data),
305            })
306        }
307        // Big metrics, PNG image data
308        // <https://learn.microsoft.com/en-us/typography/opentype/spec/cbdt#format-18-big-metrics-png-image-data>
309        18 if is_color => {
310            let metrics = read_big_metrics(&mut image_data)?;
311            let data_len = image_data.read::<u32>()? as usize;
312            let data = image_data.read_array::<u8>(data_len)?;
313            Ok(BitmapData {
314                metrics: BitmapMetrics::Big(metrics),
315                content: BitmapContent::Data(BitmapDataFormat::Png, data),
316            })
317        }
318        // Metrics in CBLC table, PNG image data
319        // <https://learn.microsoft.com/en-us/typography/opentype/spec/cbdt#format-19-metrics-in-cblc-table-png-image-data>
320        19 if is_color => {
321            let metrics = location.metrics.ok_or(ReadError::MalformedData(
322                "expected metrics from location table",
323            ))?;
324            let data_len = image_data.read::<u32>()? as usize;
325            let data = image_data.read_array::<u8>(data_len)?;
326            Ok(BitmapData {
327                metrics: BitmapMetrics::Big(metrics),
328                content: BitmapContent::Data(BitmapDataFormat::Png, data),
329            })
330        }
331        _ => Err(ReadError::MalformedData("unexpected bitmap data format")),
332    }
333}
334
335fn read_small_metrics(cursor: &mut Cursor) -> Result<SmallGlyphMetrics, ReadError> {
336    Ok(cursor.read_array::<SmallGlyphMetrics>(1)?[0])
337}
338
339fn read_big_metrics(cursor: &mut Cursor) -> Result<BigGlyphMetrics, ReadError> {
340    Ok(cursor.read_array::<BigGlyphMetrics>(1)?[0])
341}
342
343/// [IndexSubtables](https://learn.microsoft.com/en-us/typography/opentype/spec/eblc#indexsubtables) format type.
344#[derive(Clone)]
345pub enum IndexSubtable<'a> {
346    Format1(IndexSubtable1<'a>),
347    Format2(IndexSubtable2<'a>),
348    Format3(IndexSubtable3<'a>),
349    Format4(IndexSubtable4<'a>),
350    Format5(IndexSubtable5<'a>),
351}
352
353impl<'a> IndexSubtable<'a> {
354    ///Return the `FontData` used to resolve offsets for this table.
355    pub fn offset_data(&self) -> FontData<'a> {
356        match self {
357            Self::Format1(item) => item.offset_data(),
358            Self::Format2(item) => item.offset_data(),
359            Self::Format3(item) => item.offset_data(),
360            Self::Format4(item) => item.offset_data(),
361            Self::Format5(item) => item.offset_data(),
362        }
363    }
364
365    /// Format of this IndexSubTable.
366    pub fn index_format(&self) -> u16 {
367        match self {
368            Self::Format1(item) => item.index_format(),
369            Self::Format2(item) => item.index_format(),
370            Self::Format3(item) => item.index_format(),
371            Self::Format4(item) => item.index_format(),
372            Self::Format5(item) => item.index_format(),
373        }
374    }
375
376    /// Format of EBDT image data.
377    pub fn image_format(&self) -> u16 {
378        match self {
379            Self::Format1(item) => item.image_format(),
380            Self::Format2(item) => item.image_format(),
381            Self::Format3(item) => item.image_format(),
382            Self::Format4(item) => item.image_format(),
383            Self::Format5(item) => item.image_format(),
384        }
385    }
386
387    /// Offset to image data in EBDT table.
388    pub fn image_data_offset(&self) -> u32 {
389        match self {
390            Self::Format1(item) => item.image_data_offset(),
391            Self::Format2(item) => item.image_data_offset(),
392            Self::Format3(item) => item.image_data_offset(),
393            Self::Format4(item) => item.image_data_offset(),
394            Self::Format5(item) => item.image_data_offset(),
395        }
396    }
397}
398
399impl ReadArgs for IndexSubtable<'_> {
400    type Args = (GlyphId16, GlyphId16);
401}
402impl<'a> FontRead<'a> for IndexSubtable<'a> {
403    fn read_with_args(data: FontData<'a>, args: Self::Args) -> Result<Self, ReadError> {
404        let format: u16 = data.read_at(0usize)?;
405        match format {
406            IndexSubtable1::FORMAT => FontRead::read_with_args(data, args).map(Self::Format1),
407            IndexSubtable2::FORMAT => FontRead::read(data).map(Self::Format2),
408            IndexSubtable3::FORMAT => FontRead::read_with_args(data, args).map(Self::Format3),
409            IndexSubtable4::FORMAT => FontRead::read(data).map(Self::Format4),
410            IndexSubtable5::FORMAT => FontRead::read(data).map(Self::Format5),
411            other => Err(ReadError::InvalidFormat(other.into())),
412        }
413    }
414}
415
416impl<'a> MinByteRange<'a> for IndexSubtable<'a> {
417    fn min_byte_range(&self) -> Range<usize> {
418        match self {
419            Self::Format1(item) => item.min_byte_range(),
420            Self::Format2(item) => item.min_byte_range(),
421            Self::Format3(item) => item.min_byte_range(),
422            Self::Format4(item) => item.min_byte_range(),
423            Self::Format5(item) => item.min_byte_range(),
424        }
425    }
426
427    fn min_table_bytes(&self) -> &'a [u8] {
428        match self {
429            Self::Format1(item) => item.min_table_bytes(),
430            Self::Format2(item) => item.min_table_bytes(),
431            Self::Format3(item) => item.min_table_bytes(),
432            Self::Format4(item) => item.min_table_bytes(),
433            Self::Format5(item) => item.min_table_bytes(),
434        }
435    }
436}
437
438#[cfg(test)]
439mod tests {
440    use super::*;
441    use crate::{types::GlyphId16, FontData};
442    use font_test_data::bebuffer::BeBuffer;
443
444    fn bitmap_size_location(data: &[u8], glyph_id: GlyphId) -> Result<BitmapLocation, ReadError> {
445        let data = FontData::new(data);
446        let size = data.read_ref_at::<BitmapSize>(0).unwrap();
447        size.location(data, glyph_id)
448    }
449
450    fn bitmap_size_with_subtable(subtable: &[u8]) -> BeBuffer {
451        BeBuffer::new()
452            .push(BitmapSize::RAW_BYTE_LEN as u32)
453            .push((IndexSubtableRecord::RAW_BYTE_LEN + subtable.len()) as u32)
454            .push(1u32)
455            .push(0u32)
456            .extend([0u8; SbitLineMetrics::RAW_BYTE_LEN])
457            .extend([0u8; SbitLineMetrics::RAW_BYTE_LEN])
458            .push(GlyphId16::new(0))
459            .push(GlyphId16::new(0))
460            .push(0u8)
461            .push(0u8)
462            .push(1u8)
463            .push(0u8)
464            .push(GlyphId16::new(0))
465            .push(GlyphId16::new(0))
466            .push(IndexSubtableRecord::RAW_BYTE_LEN as u32)
467            .extend(subtable.iter().copied())
468    }
469
470    #[test]
471    fn short_index_tables_size_is_ignored() {
472        // Some fonts (e.g. ProggyClean) set indexTablesSize to the size of
473        // the index subtable array alone, excluding the subtables it points
474        // to. Ensure we still resolve the subtables.
475        let subtable = BeBuffer::new()
476            .push(2u16) // index format
477            .push(5u16) // image format
478            .push(0u32) // image data offset
479            .push(4u32) // image size
480            .extend([0u8; 8]); // big metrics
481        let subtable = subtable.data();
482        let data = BeBuffer::new()
483            .push(BitmapSize::RAW_BYTE_LEN as u32)
484            // indexTablesSize covering only the record array
485            .push(IndexSubtableRecord::RAW_BYTE_LEN as u32)
486            .push(1u32)
487            .push(0u32)
488            .extend([0u8; SbitLineMetrics::RAW_BYTE_LEN])
489            .extend([0u8; SbitLineMetrics::RAW_BYTE_LEN])
490            .push(GlyphId16::new(0))
491            .push(GlyphId16::new(1))
492            .push(0u8)
493            .push(0u8)
494            .push(1u8)
495            .push(0u8)
496            .push(GlyphId16::new(0))
497            .push(GlyphId16::new(1))
498            .push(IndexSubtableRecord::RAW_BYTE_LEN as u32)
499            .extend(subtable.iter().copied());
500        let location = bitmap_size_location(data.data(), GlyphId::new(1)).unwrap();
501        assert_eq!(location.data_offset, 4);
502        assert_eq!(location.data_size, 4);
503    }
504
505    #[test]
506    fn format_2_truncated_metrics_returns_error_instead_of_panicking() {
507        let data =
508            bitmap_size_with_subtable(&BeBuffer::new().push(2u16).push(5u16).push(0u32).push(1u32));
509        // Just don't panic!
510        let result = bitmap_size_location(data.data(), GlyphId::new(0));
511        assert!(matches!(result, Err(ReadError::OutOfBounds)));
512    }
513
514    #[test]
515    fn format_4_sbit_offsets_are_relative_to_image_data_offset() {
516        let data = bitmap_size_with_subtable(
517            &BeBuffer::new()
518                .push(4u16) // index format
519                .push(17u16) // image format
520                .push(1000u32) // image data offset
521                .push(1u32) // num glyphs
522                .push(GlyphId16::new(0))
523                .push(20u16) // sbit offset
524                .push(GlyphId16::new(1))
525                .push(30u16), // sbit offset of the following glyph
526        );
527        let location = bitmap_size_location(data.data(), GlyphId::new(0)).unwrap();
528        assert_eq!(location.data_offset, 1020);
529        assert_eq!(location.data_size, 10);
530    }
531
532    #[test]
533    fn format_5_truncated_metrics_returns_error_instead_of_panicking() {
534        let data = bitmap_size_with_subtable(
535            &BeBuffer::new()
536                .push(5u16)
537                .push(5u16)
538                .push(0u32)
539                .push(1u32)
540                .push(0u32),
541        );
542        // Just don't panic!
543        let result = bitmap_size_location(data.data(), GlyphId::new(0));
544        assert!(result.is_err());
545    }
546}