php-io-extensions / harfbuzz
1:1 PHP bindings of HarfBuzz: text shaping into positioned glyphs, with HarfBuzz's own font loading, and hb-ft over ext-freetype faces when it is loaded
Package info
github.com/php-io-extensions/harfbuzz
Type:php-ext
Ext name:ext-harfbuzz
pkg:composer/php-io-extensions/harfbuzz
Requires
- php: >=8.4
Requires (Dev)
- pestphp/pest: ^4.0
Suggests
None
Provides
None
Conflicts
None
Replaces
None
This package is auto-updated.
Last update: 2026-11-17 14:56:44 UTC
README
ext-harfbuzz
HarfBuzz bound 1:1 into PHP 8.4+, at the 8.3.0 API
Drawing text is more than drawing one glyph per character. "fi" can be one ligature glyph, "e" followed by a combining accent can be one glyph or a glyph and a mark placed over it, "AV" sits closer than "AH", Arabic letters change shape with their neighbours, and Hebrew runs right to left. Before a renderer draws anything, something has to turn a string into the right glyphs, in the right order, at the right positions, and remember which characters each glyph came from so a cursor can land between them.
HarfBuzz is that something. It is the shaping engine behind Chrome, Firefox, Android, GNOME and LibreOffice: give it a font and a buffer of text, call hb_shape(), and read back glyph ids, clusters, advances and offsets, with the font's OpenType features applied. It is written in C, and its documentation covers every call.
The only problem? PHP can't reach it. This extension binds HarfBuzz one to one under the C names, at the HarfBuzz 8.3.0 API: fonts opened from a file by HarfBuzz itself, or over ext-freetype faces (hb-ft) when that extension is loaded, buffers and their segment properties, shaping with features, and the shaped glyph infos and positions. Structs are typed classes, lists are PHP arrays with their counts kept as separate arguments, and the lengths HarfBuzz would read past are refused before it reads them. No defaults, no composites, no opinions: what HarfBuzz documents is what you call.
Basic usage
Most ways you will interface with ext-harfbuzz are in two parts -
Make a font and fill a buffer. HarfBuzz opens the file into a blob, makes face 0 of it, and makes a font that reads the face with its own OpenType functions, in font units until you set a scale; the buffer holds UTF-8 text, and hb_buffer_guess_segment_properties() picks its direction, script and language:
$blob = hb_blob_create_from_file('/System/Library/Fonts/Menlo.ttc'); // DejaVuSansMono.ttf on Linux $face = hb_face_create($blob, 0); $font = hb_font_create($face); hb_font_set_scale($font, 32 * 64, 32 * 64); // 32 pixels, in 26.6 fixed point $buffer = hb_buffer_create(); hb_buffer_add_utf8($buffer, "Café e\u{0301}", -1, 0, -1); hb_buffer_guess_segment_properties($buffer);
Shape it and walk the glyphs. Each glyph has its glyph id in the font (codepoint after shaping), its cluster (the byte offset of the text it came from) and its advance and offset in 26.6 fixed point. Destroy what you made when you're done:
hb_shape($font, $buffer, null, 0); $infos = hb_buffer_get_glyph_infos($buffer, $count); $positions = hb_buffer_get_glyph_positions($buffer, $count); $x = 0; for ($i = 0; $i < $count; $i++) { printf("glyph %4d cluster %d x %6.2f offset %5.2f\n", $infos[$i]->codepoint, $infos[$i]->cluster, ($x + $positions[$i]->x_offset) / 64, $positions[$i]->x_offset / 64); $x += $positions[$i]->x_advance; } printf("width %.2f px\n", $x / 64); hb_buffer_destroy($buffer); hb_font_destroy($font); hb_face_destroy($face); hb_blob_destroy($blob);
$ php shape.php glyph 38 cluster 0 x 0.00 offset 0.00 glyph 68 cluster 1 x 19.27 offset 0.00 glyph 73 cluster 2 x 38.53 offset 0.00 glyph 171 cluster 3 x 57.80 offset 0.00 glyph 3 cluster 5 x 77.06 offset 0.00 glyph 171 cluster 6 x 96.33 offset 0.00 width 115.59 px
é is two bytes, so the space is cluster 5. The decomposed e and U+0301 at bytes 6 to 8 became the same precomposed glyph 171 as the é before it: one glyph, one cluster. Load each glyph id with FT_Load_Glyph() and draw it at its x.
With ext-freetype loaded, the font can also be an hb-ft font over an FT_Face, at the size you set in FreeType. It shapes the text above the same way:
FT_Init_FreeType($library); FT_New_Face($library, '/System/Library/Fonts/Menlo.ttc', 0, $ftFace); FT_Set_Pixel_Sizes($ftFace, 0, 32); $font = hb_ft_font_create_referenced($ftFace);
Requirements
| OS | Linux or macOS. composer.json lists those two families. |
| PHP | 8.4 or newer, NTS or ZTS. |
| Extensions | None. ext-freetype is optional: when it is loaded, it starts first and hb-ft (hb_ft_font_create_referenced(), hb_ft_font_changed()) is registered; without it those two functions do not exist. The installers write 40-harfbuzz.ini, after ext-freetype's 30-freetype.ini. |
| Libraries | HarfBuzz 8.3.0 or newer, built with FreeType (hb-ft), with its headers, found through pkg-config (harfbuzz, freetype2). 8.3.0 is the floor: nothing newer is bound. |
To build it you need a C compiler, pkg-config, HarfBuzz's and FreeType's development files, and the development files of the PHP you intend to load it into:
# Debian, Ubuntu, Raspberry Pi OS sudo apt install build-essential pkg-config libharfbuzz-dev libfreetype-dev php8.4-dev # macOS: Xcode Command Line Tools, and Homebrew's PHP ships phpize and php-config xcode-select --install brew install pkgconf harfbuzz freetype php@8.4
Installation
With PHP PIE (recommended)
PIE is the PHP Foundation's installer for extensions. It downloads the tagged source from Packagist, builds it against the PHP on your PATH, installs the module and enables it. sudo where your PHP's extension directory is root-owned, as on Debian; not on a Homebrew Mac. Install the libraries first, and ext-freetype too if you want hb-ft:
pie install php-io-extensions/freetype # optional: hb-ft
pie install php-io-extensions/harfbuzz
Manually (install script)
The repository ships two installers, one per platform. Each one builds for each PHP it targets, installs harfbuzz.so into that PHP's extension_dir, writes 40-harfbuzz.ini into its conf.d scan directory, and checks the module loads. The macOS one builds in a temporary copy of the checkout and ad-hoc signs the module so the system loads it on first use; the Debian one builds in the checkout, writes the ini into the CLI, FPM and Apache conf.d of that PHP, and cleans the build products out afterwards.
git clone https://github.com/php-io-extensions/harfbuzz.git cd harfbuzz ./install-debian-trixie.sh # Debian Trixie, Ubuntu 24.04+, Raspberry Pi OS: the php on PATH ./install-macos.sh # Homebrew php@8.4 and php@8.4-zts ./install-macos.sh /path/to/bin/php # the macOS script takes specific PHP binaries
Manually (phpize)
git clone https://github.com/php-io-extensions/harfbuzz.git cd harfbuzz phpize ./configure --enable-harfbuzz make -j"$(nproc 2>/dev/null || sysctl -n hw.ncpu)" sudo make install
Then enable it: add extension=harfbuzz.so to your php.ini, or drop that line into a file in the scan directory that php --ini reports. With ext-freetype, put it after extension=freetype.so, or name the file to sort after freetype's.
Verify
php --ri harfbuzz also names the HarfBuzz headers it was built against and the library it runs with:
$ php --ri harfbuzz harfbuzz harfbuzz support => enabled Version => 0.11.0 HarfBuzz headers => 14.6.0 HarfBuzz library => 14.6.0
API
Function, handle, struct, field and constant names are the C names, so HarfBuzz's API reference is the reference: 26 functions, one stub per group in stubs/, each declared with its PHP types. SUPPORT.md lists every function HarfBuzz 8.3.0 declares in its public headers, bound or not; the API badge is computed from it.
| Stub | Functions | What it covers |
|---|---|---|
hb_face |
5 | hb_blob_create_from_file(), hb_blob_destroy(), hb_face_count(), hb_face_create(), hb_face_destroy(); the hb_blob_t and hb_face_t handles. |
hb_font |
4 | hb_font_create(), hb_font_destroy(), hb_font_set_scale(), hb_font_set_variations() (the instance of a variable font); the hb_font_t handle and hb_variation_t. |
hb_ft |
2 | hb_ft_font_create_referenced() and hb_ft_font_changed(). Registered only when ext-freetype is loaded. |
hb_buffer |
13 | Create, destroy, reset, hb_buffer_add_utf8(), the segment properties (direction, script, language, cluster level, guessed), hb_language_from_string(), the length, glyph infos and positions; hb_buffer_t, hb_language_t, hb_glyph_info_t, hb_glyph_position_t. |
hb_shape |
2 | hb_shape() and hb_feature_from_string(); hb_feature_t. |
harfbuzz |
— | The HB_DIRECTION_*, HB_SCRIPT_*, HB_BUFFER_CLUSTER_LEVEL_* constants, HB_FEATURE_GLOBAL_START and HB_FEATURE_GLOBAL_END. |
Translations
Every C parameter is its own PHP parameter, in C order. The only differences from C:
const char *is astring; its length stays its own parameter:hb_buffer_add_utf8($buffer, $text, -1, 0, -1).- An out-parameter is a by-reference parameter:
hb_feature_from_string('-kern', -1, $feature)writes anhb_feature_tto$feature, andhb_buffer_get_glyph_infos($buffer, $length)writes the count to$length. const hb_feature_t *featuresis a list ofhb_feature_t, ornull;$num_featuresstays its own parameter.const hb_variation_t *variationsis a list ofhb_variation_t, ornull, with$variations_lengthits own parameter. An array HarfBuzz returns with an out count is a list of fresh copies.- HarfBuzz's integer types and enums (
hb_codepoint_t,hb_position_t,hb_direction_t,hb_script_t, …) areint.hb_bool_tisbool. - A struct is a
finalclass with one typed public property per field:hb_glyph_info_t(codepoint,mask,cluster),hb_glyph_position_t(x_advance,y_advance,x_offset,y_offset),hb_feature_t(tag,value,start,end),hb_variation_t(tag,value). HarfBuzz's privatevarfields are not read. Anhb_feature_tproperty that wasunset()is not read as 0:hb_shape()throws PHP'sErrorfor an uninitialized typed property. hb_blob_t,hb_face_t,hb_font_t,hb_buffer_tandhb_language_tarefinalhandles with a private constructor, not cloneable or serializable, withpointer(): intandstatic fromPointer(int $pointer): static.fromPointer()trusts any address. The same native pointer and class in one thread is the same PHP object.
Lifetime
Dropping the last PHP reference does not destroy the native object. hb_blob_destroy(), hb_face_destroy(), hb_font_destroy() and hb_buffer_destroy() release their handle; a second destroy passes NULL, which HarfBuzz takes. A face references its blob and a font its face, so the blob and face can be destroyed once the font is made. A blob or face handle that holds NULL is passed to HarfBuzz, which reads it as the empty blob or face, and hb_blob_create_from_file() answers the empty blob for a file that does not open: a font over either has no glyphs. HarfBuzz interns languages, so an hb_language_t is never released; hb_language_from_string() answers a handle holding NULL (HB_LANGUAGE_INVALID) for an empty tag. An hb-ft font holds its own reference to the FreeType face, so FT_Done_Face() alone leaves the font working.
HarfBuzz 8.3's hb-ft takes advances from the FreeType size and ignores hb_font_set_scale(); 9 and newer scale them. After FT_Set_Pixel_Sizes(), call hb_ft_font_changed(): both give the same advances then.
Refusals
HarfBuzz reads the objects and lengths it is given without checking them. The extension refuses these calls, each of which crashes the process otherwise (tests/Probes shows each crash on a probe build):
- An
hb_font_torhb_buffer_tthat holds NULL (destroyed, or made from address 0):ValueError. - An hb-ft font whose face's
FT_Librarywas done:ValueError.FT_Done_FreeType()destroys every face of the library whatever its reference count. - An
FT_Facethat holds NULL inhb_ft_font_create_referenced():ValueError. - A
$text_lengthother than -1 larger than the string, or an item ($item_offset,$item_length) outside the text, inhb_buffer_add_utf8():ValueError. - A
$lenlarger than the string inhb_language_from_string():ValueError. - A
$num_featuresbelow 0 or larger than the list (0 fornull) inhb_shape():ValueError. A list element that is not anhb_feature_tis aTypeError. - A
$variations_lengthbelow 0 or larger than the list (0 fornull) inhb_font_set_variations():ValueError. A list element that is not anhb_variation_tis aTypeError.
Extensions you might use with this one
- ext-freetype: optional. It renders the glyph ids HarfBuzz returns, and with it loaded, hb-ft shapes with a face FreeType opened and sized.
- ext-fontconfig: finds the font for a family, or a fallback font for the characters the first one lacks, so each run of text shapes with a font that has its glyphs.
AI-assisted development
This codebase was built with LLM assistance under human direction. Prompts, reviews, and architectural decisions were owned by a professional software engineer — the model accelerates drafting and exploration; it does not replace judgment on APIs, dependency direction, or what ships.
Agentic Documentation
This repository carries an Open Knowledge Format bundle at .okf/: Markdown with YAML frontmatter, readable by you and loadable by a coding agent. It records what the README doesn't: every function, class and constant by stub, how handles keep one PHP object per native pointer, how a font reaches its ext-freetype face and library, how glyph infos, positions and feature lists are copied, each refusal and the length it guards, how to build release and probe builds, how to add a binding, and a log of every change that altered behaviour.
Start at .okf/index.md. AGENTS.md is the short rule sheet an agent reads before touching the C, the stubs, or packaging; each rule points into the bundle for the reason behind it.
Point your agent at the repo and it has the same context the maintainer has. Point yourself at it when the README's answer is "it does X" and you want "because".
Resources
- HarfBuzz API reference: the manual for every call this extension binds; this README only adds what PHP changes.
- HarfBuzz 8.3.0: the upstream tag the stubs and SUPPORT.md are checked against.
- PIE: the PHP Foundation's extension installer.
gen_stub.php: the php-src stub format.stubs/holds the API declarations; each*_arginfo.his generated from its stub.- Open Knowledge Format: the spec the
.okf/bundle follows.
Running the test suite
The suite is Pest v4: shaping Latin text, a combining mark, invalid UTF-8, right-to-left text and a kerning pair with -kern, features, scale changes, fonts opened by HarfBuzz itself, loading without ext-freetype, memory faces, handle identity, and the coverage script. It runs on Linux and macOS, with Menlo on macOS and DejaVu Sans Mono on Linux (fonts-dejavu-core), and needs ext-freetype for its hb-ft tests. Build both modules, then enable them through an ini scan directory rather than -d, so the child processes the tests start load them too:
git clone https://github.com/php-io-extensions/freetype.git (cd freetype && phpize && ./configure --enable-freetype && make -j"$(nproc 2>/dev/null || sysctl -n hw.ncpu)") git clone https://github.com/php-io-extensions/harfbuzz.git cd harfbuzz phpize && ./configure --enable-harfbuzz && make -j"$(nproc 2>/dev/null || sysctl -n hw.ncpu)" composer install mkdir -p /tmp/harfbuzz-ini echo "extension=$PWD/../freetype/modules/freetype.so" > /tmp/harfbuzz-ini/30-freetype.ini echo "extension=$PWD/modules/harfbuzz.so" > /tmp/harfbuzz-ini/40-harfbuzz.ini PHP_INI_SCAN_DIR=":/tmp/harfbuzz-ini" php -d memory_limit=128M vendor/bin/pest
Tests: 12 skipped, 31 passed (79 assertions) Duration: 13.32s
The twelve skipped tests are in tests/Probes: they run only against a probe build (./configure --enable-harfbuzz --enable-harfbuzz-probes, or HARFBUZZ_CONFIGURE=--enable-harfbuzz-probes ./install-macos.sh), which can turn each refusal off to show the crash it prevents. On macOS the probes run their child processes under libgmalloc, so a short read faults every time; two of them need its guard pages and skip on Linux. Never install a probe build for use.
The leading : keeps your PHP's own scan directory and adds the second one. If that PHP already loads an installed freetype.so or harfbuzz.so, the suite warns Module "harfbuzz" is already loaded and tests the installed one instead; copy the scan directory somewhere, replace its freetype and harfbuzz inis with the lines above, and point PHP_INI_SCAN_DIR at the copy without the colon. A module only loads in the PHP whose phpize built it: for Homebrew's ZTS build, run phpize and pass --with-php-config from /opt/homebrew/opt/php@8.4-zts/bin. Set XDEBUG_MODE=off for any timing you intend to read.
Contributing
Open an issue first for anything beyond a typo. Pull requests change a stub in stubs/ and the C under src/ together, regenerate the *_arginfo.h files with gen_stub, regenerate SUPPORT.md and the API badge with php scripts/support.php, and add a Pest test for the behaviour. A new refusal needs a probe test that shows the crash it prevents. CI must be green on every cell of the matrix, NTS and ZTS alike. Read AGENTS.md for the rules the code follows.
Security
ext-harfbuzz hands fonts and text, either of which can come from the network, to HarfBuzz. See SECURITY.md for what it guards against and how to report a vulnerability.
License
MIT. See LICENSE. HarfBuzz is under the "Old MIT" license; it is linked, not shipped.