Home/docs/guide/Web / WASM integration
Web / WASM integration
Browser Playback
Hand the original MKV to the browser and keep its ASS effects, font attachments, and danmaku. liberika 0.3.8 demuxes with FFmpeg WASM, decodes with WebCodecs, renders subtitles with libass, and composites everything onto a single canvas in the host page with WebGL2.
Download and try it out#
To try it without downloading anything, open the live demo: play the built-in sample, or choose a local video, subtitles and danmaku. Files are not uploaded.
npm
npm install @aimessoft/liberika-web
The runtime is published to npm as @aimessoft/liberika-web. The Worker and both WASM modules are referenced through new URL(..., import.meta.url), so Vite builds and serves it without configuration, as do other bundlers that follow that form.
You can also download liberika-web-0.3.8.zip, verify it against the SHA256SUMS file from the same release, extract it completely, and open index.html over HTTPS or a local HTTP server. The demo page lets you choose a local video, subtitles, and danmaku, so you do not need a media server.
Run in the extracted directory
python3 -m http.server 18765 --bind 127.0.0.1 # Open http://127.0.0.1:18765 in a browser
The archive contains the JavaScript, two WASM modules, the Worker, licenses, the build manifest, and the demo page; the npm package leaves out the demo page and the build manifest. When you deploy, keep the complete directory and its relative paths, and serve the JavaScript modules and application/wasm with the correct MIME types. SharedArrayBuffer and cross-origin isolation are not required. A page may also load the runtime from another origin that sends CORS headers, such as an npm CDN. The Worker then starts through a same-origin blob module, which a Content-Security-Policy must allow with worker-src blob:. To host only worker.js and the files beside it yourself, pass its address as Player.create({ canvas, workerURL }).
Minimal integration#
With a bundler, write import { Player } from '@aimessoft/liberika-web'. Without one, put the runtime files in your site's liberika/ directory. This example lets the user pick a local File, which the browser reads in chunks inside the Worker. You can also pass a Blob, or a media URL that allows cross-origin access, to open.
HTML + JavaScript module
<input id="media" type="file">
<button id="play" disabled>Play</button>
<canvas id="video" style="width:100%;height:60vh"></canvas>
<pre id="status"></pre>
<script type="module">
import { Player } from './liberika/index.js';
const media = document.querySelector('#media');
const play = document.querySelector('#play');
const status = document.querySelector('#status');
const showError = error => { status.textContent = error.message; };
const player = await Player.create({ canvas: document.querySelector('#video') });
player.addEventListener('error', event => showError(event.detail));
media.onchange = async () => {
const file = media.files[0];
if (!file) return;
media.disabled = true;
play.disabled = true;
try {
const info = await player.open(file);
status.textContent = `${file.name}: ${info.duration.toFixed(1)} s`;
play.disabled = false;
} catch (error) {
showError(error);
} finally {
media.disabled = false;
}
};
play.onclick = () => player.play().catch(showError);
// When the app unmounts: await player.destroy();
</script>Call play() from a user click to satisfy the browser's audio policy. When the app unmounts, run await player.destroy(). A canvas can be transferred only once, so rebuilding a player after destroying it requires a new canvas. Keep the original instance when you switch layouts.
If you create the canvas or the player later, create an AudioSession when the page initializes and pass it to Player.create({ canvas, audioSession }). This lets audio be prepared on the first real user input.
Subtitles, danmaku, and playback control#
ASS/SSA subtitles and font attachments embedded in MKV are passed to libass automatically. Danmaku reuses the native Rust DFM engine. Subtitles and danmaku share the Web Audio playback clock and are composited onto the same canvas.
Call after opening the media
await player.addSubtitle(await subtitleFile.text()); // ASS / SSA / SRT / WebVTT
await player.addDanmaku(await danmakuFile.text()); // Bilibili XML / Dandanplay JSON
await player.configureDanmaku({ opacity: 0.8, fontSize: 30, delay: 0 });
await player.configureSubtitles({ scale: 1 });Subtitle and danmaku supersampling (2×) is on by default and does not change the display size or video resolution. Pass { supersampling: false } to either call to disable it for that layer; omitted fields keep their current values.
| Operation | API and behavior |
|---|---|
| Play / seek | play(), pause(), seek(seconds). Seeking preserves the paused or playing state. |
| Volume / rate | setVolume(0…1), setRate(0.25…4). The current rate change also changes the pitch. |
| Tracks | info.tracks, selectAudio(id), selectSubtitle(id). Passing null turns off that track. |
| Chapters | info.chapters gives start and end in seconds; end can be null. Call seek(chapter.start) to jump to a chapter. |
| Screenshot | capture(width?) returns a PNG Blob that includes the video, subtitles, and danmaku. |
| Close / release | close() clears the current media, after which you can call open again. destroy() releases the Worker, decoder, frames, GPU resources, and audio resources. |
For the complete types, see index.d.ts. loaded, stats, timeupdate, error, and log are CustomEvents with their data in detail. play, pause, and ended are plain Events.
Browser and media source requirements#
- WebCodecs video and audio decoding, OffscreenCanvas, WebGL2, and Web Audio are all required. Open checks the codec configuration, profile, and dimensions, and codec support depends on the browser. The WASM build includes no software audio or video decoder and no server-side transcoding fallback.
- By default it requests prefer-hardware, then tries no-preference.
open(source, { hardwareDecode: false })requests prefer-software. These preference fields do not prove that hardware decoding was actually used. - Large remote files are read through a bounded HTTP Range cache. For files over 8 MiB, the server must return
206with a known total length. For cross-origin access, exposeContent-RangethroughAccess-Control-Expose-Headers. - Supported containers include MP4/MOV, MKV/WebM, MPEG-TS, AVI, FLV, and Ogg. Whether an audio or video codec plays depends on the current browser's WebCodecs query result.
- Output is currently SDR. Not yet supported: desktop HDR/EDR/Dolby Vision, ArtCNN, DRM, live streams of unknown length, bitmap subtitles, and conversion of embedded non-ASS subtitles. SRT and VTT are converted as plain text, and complex VTT layout is not preserved.
- When you seek, embedded ASS is read starting 5 seconds before the target, and events already seen are kept. On the first seek into a long event that started earlier than that, the event may be temporarily missing. Complete external ASS scripts do not have this limitation.
The verification record in the source repository covers specific versions of Chrome and Safari with specific test media; Firefox has not been verified yet. For detailed build and test steps, see the source repository's Web guide (in Chinese).
Build from source#
You need Emscripten 4.0.23, wasm-bindgen-cli 0.2.130, Rust, Python 3, Node, CMake, Meson, Ninja, make, and pkg-config. For the pinned tool versions and setup steps, see the source guide linked above.
shell
cargo run -p xtask -- web build python3 scripts/serve_web.py # Add --skip-native if the native C dependencies are already built
The complete deployable directory is target/web; intermediate files go in target/web-build. On the server, place the runtime in a versioned directory so old and new JS/WASM files are never mixed.
Full and nofont packages#
The full package includes about 6 MB of fallback font data. @aimessoft/liberika-web-nofont on npm and liberika-web-nofont-0.3.8.zip omit it. Browsers cannot pass system font bytes directly to the WASM subtitle path, so the host must supply Player.create({ canvas, fallbackFont: { data, index } }). A native host can share its font through erika_embedded_fallback_font instead of bundling a second copy.
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.