@scrpr/jassub
v2.5.14-zimuzoo.2
Published
The Fastest JavaScript SSA/ASS Subtitle Renderer For Browsers
Maintainers
Readme
Features
- Supports all SSA/ASS features (everything libass supports)
- Supports all OpenType, TrueType and WOFF fonts, as well as embedded fonts
- Supports anamorphic videos (on browsers which support it)
- Supports color space mangling (on browsers which support it)
- Capable of using local fonts (on browsers which support it)
- Capable of finding fonts online (opt-in, done via Google Fonts API)
- Works fast (all the heavy lifting is done by WebAssembly and WebGL, with absolutely minimal JS glue)
- Is fully multi-threaded
- Is asynchronous (renders when available, not in order of execution)
- Benefits from hardware acceleration (uses WebGL)
- Doesn't manipulate the DOM to render subtitles
- Easy to use - just connect it to video element
Requirements
The
{
"Cross-Origin-Embedder-Policy": "require-corp",
"Cross-Origin-Opener-Policy": "same-origin"
}headers are recommended to use this library, as it uses SharedArrayBuffer for multi-threading, but if you can't set them, it will fallback automatically to work in single-threaded mode. Firefox doesn't support threading so they are not required there.
At minimum WASM + TextDecoder + OffscreenCanvas + Web Workers + Proxy + Fetch + Promise + getVideoPlaybackQuality/requestVideoFrameCallback are required for JASSUB to work.
JASSUB supports Chrome/Safari/Firefox 80/17/105, you bring the support down to 67/16.2/68 if you enable some flags/settings in your browser for these features. For other engines polyfills might be needed. Babel is also recommended if you need to support older JS engines as JASSUB ships as ES modules with modern syntax.
Usage
Install the library via:
[p]npm i @scrpr/jassubDeploy the runtime assets
The npm package contains a browser-ready worker, the pthread helper, and both WASM builds. Package files are not public URLs, so the consuming application should copy them into a same-origin static directory before starting its development server or production build.
For example, save this as scripts/sync-jassub-assets.mjs in the consuming application:
import { copyFile, mkdir } from 'node:fs/promises'
const assets = [
'worker.js',
'jassub-worker.js',
'jassub-worker.wasm',
'jassub-worker-modern.wasm',
'LICENSE.txt'
]
const publicDirectory = new URL('../public/jassub/', import.meta.url)
await mkdir(publicDirectory, { recursive: true })
await Promise.all(assets.map((asset) => copyFile(
new URL(import.meta.resolve(`@scrpr/jassub/assets/${asset}`)),
new URL(asset, publicDirectory)
)))Run the script from both predev and prebuild (or the equivalent hooks in your build system):
{
"scripts": {
"predev": "node scripts/sync-jassub-assets.mjs",
"prebuild": "node scripts/sync-jassub-assets.mjs"
}
}Keep worker.js, jassub-worker.js, and the WASM files in the same deployed directory: the threaded runtime resolves its helper relative to the worker URL.
Then pass the deployed URLs explicitly:
import JASSUB from '@scrpr/jassub'
const runtimeDirectory = '/jassub/'
const instance = new JASSUB({
video: document.querySelector('video'),
subUrl: './tracks/sub.ass',
workerUrl: `${runtimeDirectory}worker.js`,
wasmUrl: `${runtimeDirectory}jassub-worker.wasm`,
modernWasmUrl: `${runtimeDirectory}jassub-worker-modern.wasm`,
defaultFont: 'Noto Sans',
fonts: ['/fonts/NotoSans-Regular.woff2']
})Using only with canvas
You're also able to use it without any video. However, that requires you to set the time the subtitles should render at yourself:
import JASSUB from '@scrpr/jassub'
const instance = new JASSUB({
canvas: document.querySelector('canvas'),
subUrl: './tracks/sub.ass',
workerUrl: '/jassub/worker.js',
wasmUrl: '/jassub/jassub-worker.wasm',
modernWasmUrl: '/jassub/jassub-worker-modern.wasm',
defaultFont: 'Noto Sans',
fonts: ['/fonts/NotoSans-Regular.woff2']
})
await instance.ready
instance.manualRender({ expectedDisplayTime: performance.now(), width: 1920, height: 1080, mediaTime: 10.20 })Docs
The library is fully typed, so you can simply browse the types of instance or instance.renderer. "Private" fields are prefixed with _ such as _fontId or _findAvailableFonts, and shouldn't be used by developers, but can if the need arises.
instance.renderer calls are ALWAYS async as it's a remote worker, which means you should always await/then them for the IPC call to be serialized!!! For example:
const x = instance.renderer.useLocalFonts // does nothing, returns IPC proxy object
const y = await instance.renderer.useLocalFonts // returns true/false
instance.renderer.useLocalFonts = false // this is fine
await (instance.renderer.useLocalFonts = false) // or u can await it for safety
instance.renderer.setDefaultFont('Gandhi Sans') // this is fine, sets default font
await instance.renderer.setDefaultFont('Gandhi Sans') // or you can await if if you wantMake sure to always await instance.ready before running any methods!!!
Example usage can be found in the demo source here.
Understanding font management
If you know for sure that your subtitles use specific fonts, you can pre-load them via the fonts option when creating the JASSUB instance:
const instance = new JASSUB({
video: document.querySelector('video'),
subUrl: './tracks/sub.ass',
fonts: [new URL('./fonts/GandhiSans-Regular.woff', import.meta.url).href, new Uint8Array(data)]
})This will load/fetch the fonts ASAP when the renderer and WASM is initiated, this process is non-blocking.
If you however have a very big database of fonts and/or you're unsure if your subtitles use, or you want to conserve memory, bandwidth etc you can define fonts via availableFonts, which is a case-insensitive, postscript-insensitive map of fonts and their sources. This means the keys can, but don't need to include the weight of the font, but it is preferred. For example:
const instance = new JASSUB({
video: document.querySelector('video'),
subUrl: './tracks/sub.ass',
availableFonts: {
'Gandhi Sans': new URL('./fonts/GandhiSans-Regular.ttf', import.meta.url).href,
'RoBoTO mEdiuM': new Uint8Array(data), // this is quite stupid if you want to conserve resources, since the data will be lingering in memory, but it is supported
'roboto': new URL('./fonts/Roboto-Medium.woff2', import.meta.url).href
}
})When JASSUB then needs one of these fonts for immediate rendering it will load the font from the given source, however this can cause a flash of unstyled text if the default font was previously loaded, as the font is being loaded asynchronously, which looks something like this:
With complex typesetting this might not just be text, but glyphs, icons etc. If the default font wasn't previously loaded and wasn't pre-loaded a FOUT won't happen!, and nothing will render for at most a few frames as the font is being downloaded from the given URL.
The above also applies to the default font, which must be named explicitly with defaultFont. You can pre-load it via fonts[], or define it in availableFonts. If you use await instance.renderer.setDefaultFont('Gandhi Sans') and wish to preload it, you should do so manually via await instance.renderer.addFonts(['Gandhi Sans']), however this is not recommended as it can cause FOUTs as explained above.
For the best user experience, which avoids FOUTs, while using as little memory/bandwidth as possible, you should use a config in the lines of:
const instance = new JASSUB({
fonts: fileAttachments // extracted file attachments for the given video, for example MKV's attachments
availableFonts: {
'My Fallback Font Family Name': './fonts/MyFallbackFont.woff2' // or new URL(...).href, only necessary if you want a custom default font, don't include this in fonts[]!
},
defaultFont: 'My Fallback Font Family Name',
queryFonts: 'localandremote' // optional, local or remote fonts will be queried if a font isn't found in fonts[] or availableFonts and is required for immediate rendering
})About finding fonts online
By default, JASSUB will only use embedded, constructor defined and local fonts. However, if you want to enable online font finding, you can do so by setting the queryFonts option to 'localandremote' when creating the JASSUB instance, note that this loads 50+ KB of code:
const instance = new JASSUB({
video: document.querySelector('video'),
subUrl: './tracks/sub.ass',
queryFonts: 'localandremote'
})This finds fonts from the free and public Google Fonts API if they aren't available locally or embedded, which has some privacy implications [in theory, not in practice]. Be mindful of the licensing. Note that Google Fonts doesn't include a lot of non-free fonts such as Arial, so this isn't a perfect solution.
Looking for backwards compatibility with much older browser engines?
If you want to support even older engines, then please check the v1.8.8 tag, or install it via:
[p]npm i [email protected]Support for older browsers (without OffscreenCanvas, WebAssembly threads, etc) has been dropped in v2.0.0 and later.
How to build?
Get the Source
Run git clone --recursive https://github.com/scrpr/jassub.git, then:
pnpm install
pnpm buildThe build compiles the library, bundles the browser worker, and copies the checked-in WASM builds into dist. Rebuilding libass and the WASM binaries themselves still uses the Docker workflow below.
Docker
- Install Docker
- ./run-docker-build.sh or ./run-docker-build.ps1
