Home/docs/kernel/Subtitles and danmaku
Subtitles and danmaku
Subtitle & Danmaku
Subtitle tracks support SRT / WebVTT / ASS and are rendered by libass. Danmaku accepts two inputs, Bilibili XML and JSON, is laid out with DFM+ collision avoidance, and is drawn on the GPU through a glyph atlas. Both are composited with the video in the render pipeline’s composite pass.
Subtitles字幕#
A subtitle track comes from one of two sources, embedded or external (ErikaTrackSource). Add an external subtitle with add_external_subtitle, which returns the track id. A subtitle track id of -1 disables subtitles. External text subtitles get built-in charset detection and transcoding that covers GBK, Big5, Shift_JIS, and UTF-16, passes UTF-8 through, and falls back conservatively for low-confidence or binary input.
libass renders subtitles. Native targets first try readable system fonts for missing glyphs. The embedded Droid Sans Fallback is registered as a later fallback only when the default embedded-fallback-font feature is enabled. Builds without it need system fonts or font data supplied by the host.
Style overrides
The host can override the subtitle style. The granularity is controlled bit by bit through the bit flags of ErikaSubtitleStyle.override_mask:
| Flag | Bit | Overrides |
|---|---|---|
| ERIKA_SUBTITLE_OVERRIDE_FONT_SIZE_FIELDS | 2 | Font size |
| ERIKA_SUBTITLE_OVERRIDE_FONT_NAME | 3 | Font family and font file |
| ERIKA_SUBTITLE_OVERRIDE_COLORS | 4 | Primary color and outline color |
| ERIKA_SUBTITLE_OVERRIDE_ATTRIBUTES | 5 | Bold, italic, underline, strikethrough |
| ERIKA_SUBTITLE_OVERRIDE_BORDER | 6 | Border style and width |
| ERIKA_SUBTITLE_OVERRIDE_ALIGNMENT | 7 | Alignment |
| ERIKA_SUBTITLE_OVERRIDE_MARGINS | 8 | Margins |
| ERIKA_SUBTITLE_OVERRIDE_BLUR | 11 | Blur |
ERIKA_SUBTITLE_OVERRIDE_ALL is the combination of all the bits above. Container ASS scripts keep their own fonts unless the host forces a replacement through the font-name override bit.
In-memory fonts
0.1.5 introduced the in-memory font registry. The host can register font data (never written to disk), query a font’s faces, select an ordered fallback set, replace font data, and clear the registry. The renderer rebuilds its cache according to the selected-font generation: a font in the selected set takes effect on the active subtitle track immediately after it is replaced, while a font that is registered but not selected does not trigger a renderer rebuild.
Danmaku弾幕#
Danmaku input is Bilibili XML (a file or URL) or JSON (an inline string). There are two loading paths:
load_danmaku_file/load_danmaku_json— Replace all danmaku with a single anonymous track.add_danmaku_track_file/add_danmaku_track_json— Build a list of named tracks; each track can be enabled, disabled, and offset independently.
The per-track offset_micros shifts the timeline of a single track; the global offset applies to all tracks. Layout is generated on the erika-danmaku thread, and each plan is gated by generation and media time to stay in sync with the video.
DFM+ layout
The DFM+ collision-avoidance engine lays out danmaku. Scrolling, top, and bottom modes each have their own track allocation, density limits, and overwrite policy. Drawing goes through a glyph atlas: glyphs are rasterized into the atlas once, then drawn every frame with instanced vertices.
ErikaDanmakuConfig controls the layout parameters:
| Field | Description |
|---|---|
| font_size | Logical danmaku font size, matching NipaPlay’s default danmaku font size; converted to glyph pixels using the surface scale. |
| opacity / outline_width / shadow_* | Opacity, outline width, shadow offset, and shadow style. |
| display_area | Fraction of the display area that danmaku can occupy. |
| scroll_duration_seconds / scroll_speed_factor | Scroll duration and speed factor. |
| merge_duplicates | Merges duplicate danmaku. |
| allow_stacking / allow_scroll_overwrite | Same-track stacking and scroll overwrite policies. |
| max_quantity / max_lines_per_mode | Total danmaku limit and the maximum number of lines per mode. |
| block_top / block_bottom / block_scroll | Blocks danmaku by mode. |
Block words are supplied through set_danmaku_block_words_json as a JSON array, and each entry is matched against the danmaku text.
Danmaku JSON contract
load_danmaku_json and add_danmaku_track_json accept inline JSON. The root of the input can take two forms:
- Item array:
[ { ... }, { ... } ] - Wrapper object: an object that contains a
comments,danmaku, oritemsarray, for example{ "comments": [ ... ] }. Line-delimited JSON Lines (JSONL) is also accepted.
Each danmaku item supports the following fields (compatible aliases are in parentheses):
| Field | Type | Default | Description |
|---|---|---|---|
| content (text, c) | String | — | Danmaku text. Entries where it is missing or contains only whitespace are skipped. |
| time (t) | Number / String | 0.0 | Time at which the danmaku is shown, in seconds. Fractional seconds are supported (for example 12.45). |
| type (mode, y) | String / Number | "scroll" | Danmaku type: scroll / 1 (scrolling), bottom / 4 (fixed at the bottom), top / 5 (fixed at the top), reverse / 6 (reverse scrolling), special / 7 (mode 7 advanced comments: positioning, linear motion, duration and opacity fades; rotation and multiline text are not supported). You can also use the numeric fields type_code / mode_code. |
| color (r) | Number / String | White | Danmaku color: a decimal RGB integer (for example 16777215), a full #RRGGBB hex string (for example "#FFFFFF"), or CSS rgb(r,g,b). Note: do not use 3-digit shorthand such as #FFF; it is parsed directly as hex 0x000FFF. |
| font_size (fontSize, size, s) | Number / String | 25.0 | Reference font size of the source (in points). The final rendered size is also scaled by the global configuration and the surface scale. |
| opacity (alpha, a) | Number / String | 1.0 | Custom opacity (0.0 to 1.0). |
| is_me (isMe, self, mine) | Boolean / Number | false | Whether the current user posted this danmaku. It gets layout priority and is not filtered out by the anti-stacking policy. |
| id | u64 / String | Assigned sequentially | Business ID. Accepts an unsigned integer in the u64 range or a decimal string; 0 is treated as not provided. |
Parsing and behavior:
idis optional: When it is omitted, 0, invalid, or out of range, liberika assigns sequence numbers by each item’s natural position in the whole input.- Exact
u64parsing: Unsigned integers or decimal strings from0to18446744073709551615(u64::MAX) are parsed without any floating-point conversion, which rules out the precision loss of JS/JSON double-precision floats. - Business IDs are decoupled from layout identity: Business IDs may repeat, or collide across sources when multiple tracks are merged. Callers should not concatenate track IDs and do not need to synthesize special IDs to make layout unique.
- Continuity across sliding windows: After multiple tracks are merged, the danmaku session assigns internal layout identities for the current content version independently. Within one continuous session, consecutive time windows strictly inherit earlier admission and track-assignment decisions, which supports the public guarantee that danmaku do not appear midway or change tracks when the window refreshes (except when the viewport size, timeline content, or layout configuration changes).
- Error tolerance: A malformed root fails immediately. An item with missing or blank text is skipped without aborting the rest of the batch. An invalid optional field falls back to its default, and unknown business fields (such as
cidanddanmakuId) are ignored.
Standard danmaku JSON example
[
{ "time": 1.5, "content": "Heads-up, intense scene ahead", "type": "scroll", "color": "#FF0000" },
{ "t": 2.0, "c": "Iconic scene check-in", "mode": 5, "color": 16777215, "id": "9007199254740993" },
{ "time": 4.8, "content": "Danmaku group photo", "is_me": true, "opacity": 0.9 }
]
Supersampling defaults · 0.3.0#
Subtitle and danmaku supersampling is on by default in both the native and Web backends. It sharpens glyphs while keeping the logical display size, and does not raise the video resolution. The two are configured independently; on Web, turn them off with configureSubtitles({ supersampling: false }) and configureDanmaku({ supersampling: false }), respectively.
Seeking while paused, a long subtitle that spans a seek, and switching tracks while paused all recompute the current subtitle. System font fallback bounds memory with a zero-copy coverage check and a bounded LRU cache, and keeps the valid glyphs.
System fonts, color emoji and advanced danmaku#
Since 0.3.6, native subtitles and danmaku try system fonts before the embedded fallback. Native danmaku supports color emoji; Web danmaku uses browser Canvas and system color fonts. Libass subtitles remain monochrome. Chinese on iOS 18+ / tvOS still requires an embedded fallback or readable font bytes supplied by the host.
Version 0.3.7 supports Bilibili mode 7 positioning, straight-line motion, duration and opacity fades. Rotation, multiline text, mode 8 code comments and mode 9 BAS are not supported. When constructing a normal Rust DanmakuItem directly, supply special: None; XML / JSON parsers handle this automatically.
Since 0.3.5, external subtitle loading failures return an error to the caller without emitting a fatal playback event. The host can show the error and offer a retry. Repeated UTF-8 BOMs are normalized.
Hosts that draw native danmaku themselves must handle DanmakuRenderPlan.color_atlas and color_glyphs as well as the monochrome glyph atlas, or color emoji will be invisible. With libass, HarfBuzz composes flags, skin tones and family sequences; when a composed glyph is unavailable, or libass is disabled, glyphs are drawn separately.