NL
apps/winzik / src / Cast / FontMetrics.php · commit 6576d6f
<?phpnamespace App\Cast;/** * The widths of a TrueType font's characters, read from the file itself (no FreeType nor GD here: the phone's PHP has * neither): its cmap (formats 4 and 12), hmtx, hhea, head and OS/2 tables. What libass will draw at a size, measured * beforehand: VlcTarget puts the karaoke's ball over the syllable sung, so it must know where each syllable is. * * libass sizes a font as VSFilter does: the ASS font size is the height usWinAscent + usWinDescent (OS/2) in pixels, * so one font unit = size / (usWinAscent + usWinDescent) pixels. Kerning is not counted (a pixel or two). */final class FontMetrics{    /** @var array<int, int> code point => advance (font units) */    private array $advance = [];    private int $defaultAdvance = 0;    private int $height = 1;    /** @var array<string, ?self> */    private static array $loaded = [];    public static function of(string $file): ?self    {        if (!array_key_exists($file, self::$loaded)) {            try {                self::$loaded[$file] = is_file($file) ? new self((string)file_get_contents($file)) : null;            } catch (\Throwable) {                self::$loaded[$file] = null;            }        }        return self::$loaded[$file];    }    private function __construct(string $ttf)    {        $tables = [];        $count = self::u16($ttf, 4);        for ($i = 0; $i < $count; $i++) {            $at = 12 + 16 * $i;            $tables[substr($ttf, $at, 4)] = self::u32($ttf, $at + 8);        }        foreach (['cmap', 'hmtx', 'hhea', 'OS/2'] as $need) {            if (!isset($tables[$need])) {                throw new \RuntimeException("no $need table");            }        }        $os2 = $tables['OS/2'];        $this->height = max(1, self::u16($ttf, $os2 + 74) + self::u16($ttf, $os2 + 76));      // usWinAscent + usWinDescent        $metrics = self::u16($ttf, $tables['hhea'] + 34);       // numberOfHMetrics        $widths = [];        for ($g = 0; $g < $metrics; $g++) {            $widths[$g] = self::u16($ttf, $tables['hmtx'] + 4 * $g);        }        $last = $widths[$metrics - 1] ?? 0;        $glyphs = $this->cmap($ttf, $tables['cmap']);        foreach ($glyphs as $code => $glyph) {            $this->advance[$code] = $widths[$glyph] ?? $last;        }        $this->defaultAdvance = $this->advance[ord('n')] ?? (int)($this->height / 2);    }    /** @return array<int, int> code point => glyph */    private function cmap(string $ttf, int $cmap): array    {        $best = null;        $n = self::u16($ttf, $cmap + 2);        for ($i = 0; $i < $n; $i++) {            $platform = self::u16($ttf, $cmap + 4 + 8 * $i);            $encoding = self::u16($ttf, $cmap + 6 + 8 * $i);            $at = $cmap + self::u32($ttf, $cmap + 8 + 8 * $i);            $format = self::u16($ttf, $at);            if (($platform === 3 && ($encoding === 1 || $encoding === 10) || $platform === 0) && ($format === 4 || $format === 12)) {                if ($best === null || $format === 12) {                    $best = [$format, $at];                }            }        }        if ($best === null) {            return [];        }        [$format, $at] = $best;        $map = [];        if ($format === 12) {            $groups = self::u32($ttf, $at + 12);            for ($i = 0; $i < $groups; $i++) {                $g = $at + 16 + 12 * $i;                [$start, $end, $glyph] = [self::u32($ttf, $g), self::u32($ttf, $g + 4), self::u32($ttf, $g + 8)];                for ($c = $start; $c <= min($end, $start + 0xFFFF); $c++) {                    $map[$c] = $glyph + $c - $start;                }            }            return $map;        }        $segs = intdiv(self::u16($ttf, $at + 6), 2);        $ends = $at + 14;        $starts = $ends + 2 * $segs + 2;        $deltas = $starts + 2 * $segs;        $offsets = $deltas + 2 * $segs;        for ($i = 0; $i < $segs; $i++) {            $end = self::u16($ttf, $ends + 2 * $i);            $start = self::u16($ttf, $starts + 2 * $i);            $delta = self::u16($ttf, $deltas + 2 * $i);            $offset = self::u16($ttf, $offsets + 2 * $i);            for ($c = $start; $c <= $end && $c !== 0xFFFF; $c++) {                if ($offset === 0) {                    $glyph = ($c + $delta) & 0xFFFF;                } else {                    $glyph = self::u16($ttf, $offsets + 2 * $i + $offset + 2 * ($c - $start));                    $glyph = $glyph === 0 ? 0 : ($glyph + $delta) & 0xFFFF;                }                $map[$c] = $glyph;            }        }        return $map;    }    /** The width of $text at the ASS font size $size, in pixels. */    public function width(string $text, float $size): float    {        $units = 0;        foreach (mb_str_split($text, 1, 'UTF-8') as $char) {            $units += $this->advance[mb_ord($char, 'UTF-8')] ?? $this->defaultAdvance;        }        return $units * $size / $this->height;    }    private static function u16(string $s, int $at): int    {        return $at + 2 <= strlen($s) ? (ord($s[$at]) << 8) | ord($s[$at + 1]) : 0;    }    private static function u32(string $s, int $at): int    {        return $at + 4 <= strlen($s) ? (int)unpack('N', $s, $at)[1] : 0;    }}