jassub 1.8.6 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/jassub.js DELETED
@@ -1,860 +0,0 @@
1
- import 'rvfc-polyfill'
2
-
3
- const webYCbCrMap = {
4
- bt709: 'BT709',
5
- // these might not be exactly correct? oops?
6
- bt470bg: 'BT601', // alias BT.601 PAL... whats the difference?
7
- smpte170m: 'BT601'// alias BT.601 NTSC... whats the difference?
8
- }
9
-
10
- const colorMatrixConversionMap = {
11
- BT601: {
12
- BT709: '1.0863 -0.0723 -0.014 0 0 0.0965 0.8451 0.0584 0 0 -0.0141 -0.0277 1.0418'
13
- },
14
- BT709: {
15
- BT601: '0.9137 0.0784 0.0079 0 0 -0.1049 1.1722 -0.0671 0 0 0.0096 0.0322 0.9582'
16
- },
17
- FCC: {
18
- BT709: '1.0873 -0.0736 -0.0137 0 0 0.0974 0.8494 0.0531 0 0 -0.0127 -0.0251 1.0378',
19
- BT601: '1.001 -0.0008 -0.0002 0 0 0.0009 1.005 -0.006 0 0 0.0013 0.0027 0.996'
20
- },
21
- SMPTE240M: {
22
- BT709: '0.9993 0.0006 0.0001 0 0 -0.0004 0.9812 0.0192 0 0 -0.0034 -0.0114 1.0148',
23
- BT601: '0.913 0.0774 0.0096 0 0 -0.1051 1.1508 -0.0456 0 0 0.0063 0.0207 0.973'
24
- }
25
- }
26
-
27
- /**
28
- * New JASSUB instance.
29
- * @class
30
- */
31
- export default class JASSUB extends EventTarget {
32
- /**
33
- * @param {Object} options Settings object.
34
- * @param {HTMLVideoElement} options.video Video to use as target for rendering and event listeners. Optional if canvas is specified instead.
35
- * @param {HTMLCanvasElement} [options.canvas=HTMLCanvasElement] Canvas to use for manual handling. Not required if video is specified.
36
- * @param {'js'|'wasm'} [options.blendMode='js'] Which image blending mode to use. WASM will perform better on lower end devices, JS will perform better if the device and browser supports hardware acceleration.
37
- * @param {Boolean} [options.asyncRender=true] Whether or not to use async rendering, which offloads the CPU by creating image bitmaps on the GPU.
38
- * @param {Boolean} [options.offscreenRender=true] Whether or not to render things fully on the worker, greatly reduces CPU usage.
39
- * @param {Boolean} [options.onDemandRender=true] Whether or not to render subtitles as the video player decodes renders, rather than predicting which frame the player is on using events.
40
- * @param {Number} [options.targetFps=24] Target FPS to render subtitles at. Ignored when onDemandRender is enabled.
41
- * @param {Number} [options.timeOffset=0] Subtitle time offset in seconds.
42
- * @param {Boolean} [options.debug=false] Whether or not to print debug information.
43
- * @param {Number} [options.prescaleFactor=1.0] Scale down (< 1.0) the subtitles canvas to improve performance at the expense of quality, or scale it up (> 1.0).
44
- * @param {Number} [options.prescaleHeightLimit=1080] The height in pixels beyond which the subtitles canvas won't be prescaled.
45
- * @param {Number} [options.maxRenderHeight=0] The maximum rendering height in pixels of the subtitles canvas. Beyond this subtitles will be upscaled by the browser.
46
- * @param {Boolean} [options.dropAllAnimations=false] Attempt to discard all animated tags. Enabling this may severly mangle complex subtitles and should only be considered as an last ditch effort of uncertain success for hardware otherwise incapable of displaing anything. Will not reliably work with manually edited or allocated events.
47
- * @param {Boolean} [options.dropAllBlur=false] The holy grail of performance gains. If heavy TS lags a lot, disabling this will make it ~x10 faster. This drops blur from all added subtitle tracks making most text and backgrounds look sharper, this is way less intrusive than dropping all animations, while still offering major performance gains.
48
- * @param {String} [options.workerUrl='jassub-worker.js'] The URL of the worker.
49
- * @param {String} [options.wasmUrl='jassub-worker.wasm'] The URL of the worker WASM.
50
- * @param {String} [options.legacyWasmUrl='jassub-worker.wasm.js'] The URL of the worker WASM. Only loaded if the browser doesn't support WASM.
51
- * @param {String} options.modernWasmUrl The URL of the modern worker WASM. This includes faster ASM instructions, but is only supported by newer browsers, disabled if the URL isn't defined.
52
- * @param {String} [options.subUrl=options.subContent] The URL of the subtitle file to play.
53
- * @param {String} [options.subContent=options.subUrl] The content of the subtitle file to play.
54
- * @param {String[]|Uint8Array[]} [options.fonts] An array of links or Uint8Arrays to the fonts used in the subtitle. If Uint8Array is used the array is copied, not referenced. This forces all the fonts in this array to be loaded by the renderer, regardless of if they are used.
55
- * @param {Object} [options.availableFonts={'liberation sans': './default.woff2'}] Object with all available fonts - Key is font family in lower case, value is link or Uint8Array: { arial: '/font1.ttf' }. These fonts are selectively loaded if detected as used in the current subtitle track.
56
- * @param {String} [options.fallbackFont='liberation sans'] The font family key of the fallback font in availableFonts to use if the other font for the style is missing special glyphs or unicode.
57
- * @param {Boolean} [options.useLocalFonts=false] If the Local Font Access API is enabled [chrome://flags/#font-access], the library will query for permissions to use local fonts and use them if any are missing. The permission can be queried beforehand using navigator.permissions.request({ name: 'local-fonts' }).
58
- * @param {Number} [options.libassMemoryLimit] libass bitmap cache memory limit in MiB (approximate).
59
- * @param {Number} [options.libassGlyphLimit] libass glyph cache memory limit in MiB (approximate).
60
- */
61
- constructor (options) {
62
- super()
63
- if (!globalThis.Worker) throw this.destroy('Worker not supported')
64
- if (!options) throw this.destroy('No options provided')
65
-
66
- this._loaded = /** @type {Promise<void>} */(new Promise(resolve => {
67
- this._init = resolve
68
- }))
69
-
70
- const test = JASSUB._test()
71
- this._onDemandRender = 'requestVideoFrameCallback' in HTMLVideoElement.prototype && (options.onDemandRender ?? true)
72
-
73
- // don't support offscreen rendering on custom canvases, as we can't replace it if colorSpace doesn't match
74
- this._offscreenRender = 'transferControlToOffscreen' in HTMLCanvasElement.prototype && !options.canvas && (options.offscreenRender ?? true)
75
-
76
- this.timeOffset = options.timeOffset || 0
77
- this._video = options.video
78
- this._videoHeight = 0
79
- this._videoWidth = 0
80
- this._videoColorSpace = null
81
- this._canvas = options.canvas
82
- if (this._video && !this._canvas) {
83
- this._canvasParent = document.createElement('div')
84
- this._canvasParent.className = 'JASSUB'
85
- this._canvasParent.style.position = 'relative'
86
-
87
- this._canvas = this._createCanvas()
88
-
89
- this._video.insertAdjacentElement('afterend', this._canvasParent)
90
- } else if (!this._canvas) {
91
- throw this.destroy('Don\'t know where to render: you should give video or canvas in options.')
92
- }
93
-
94
- this._bufferCanvas = document.createElement('canvas')
95
- this._bufferCtx = this._bufferCanvas.getContext('2d')
96
- if (!this._bufferCtx) throw this.destroy('Canvas rendering not supported')
97
-
98
- this._canvasctrl = this._offscreenRender ? this._canvas.transferControlToOffscreen() : this._canvas
99
- this._ctx = !this._offscreenRender && this._canvasctrl.getContext('2d')
100
-
101
- this._lastRenderTime = 0
102
- this.debug = !!options.debug
103
-
104
- this.prescaleFactor = options.prescaleFactor || 1.0
105
- this.prescaleHeightLimit = options.prescaleHeightLimit || 1080
106
- this.maxRenderHeight = options.maxRenderHeight || 0 // 0 - no limit.
107
-
108
- this._boundResize = this.resize.bind(this)
109
- this._boundTimeUpdate = this._timeupdate.bind(this)
110
- this._boundSetRate = this.setRate.bind(this)
111
- this._boundUpdateColorSpace = this._updateColorSpace.bind(this)
112
- if (this._video) this.setVideo(options.video)
113
-
114
- if (this._onDemandRender) {
115
- this.busy = false
116
- this._lastDemandTime = null
117
- }
118
-
119
- this._worker = new Worker(options.workerUrl || 'jassub-worker.js')
120
- this._worker.onmessage = e => this._onmessage(e)
121
- this._worker.onerror = e => this._error(e)
122
-
123
- test.then(() => {
124
- this._worker.postMessage({
125
- target: 'init',
126
- wasmUrl: JASSUB._supportsSIMD && options.modernWasmUrl ? options.modernWasmUrl : options.wasmUrl ?? 'jassub-worker.wasm',
127
- legacyWasmUrl: options.legacyWasmUrl ?? 'jassub-worker.wasm.js',
128
- asyncRender: typeof createImageBitmap !== 'undefined' && (options.asyncRender ?? true),
129
- onDemandRender: this._onDemandRender,
130
- width: this._canvasctrl.width || 0,
131
- height: this._canvasctrl.height || 0,
132
- blendMode: options.blendMode || 'js',
133
- subUrl: options.subUrl,
134
- subContent: options.subContent || null,
135
- fonts: options.fonts || [],
136
- availableFonts: options.availableFonts || { 'liberation sans': './default.woff2' },
137
- fallbackFont: options.fallbackFont || 'liberation sans',
138
- debug: this.debug,
139
- targetFps: options.targetFps || 24,
140
- dropAllAnimations: options.dropAllAnimations,
141
- dropAllBlur: options.dropAllBlur,
142
- libassMemoryLimit: options.libassMemoryLimit || 0,
143
- libassGlyphLimit: options.libassGlyphLimit || 0,
144
- // @ts-ignore
145
- useLocalFonts: typeof queryLocalFonts !== 'undefined' && (options.useLocalFonts ?? true),
146
- hasBitmapBug: JASSUB._hasBitmapBug
147
- })
148
- if (this._offscreenRender === true) this.sendMessage('offscreenCanvas', null, [this._canvasctrl])
149
- })
150
- }
151
-
152
- _createCanvas () {
153
- this._canvas = document.createElement('canvas')
154
- this._canvas.style.display = 'block'
155
- this._canvas.style.position = 'absolute'
156
- this._canvas.style.pointerEvents = 'none'
157
- this._canvasParent.appendChild(this._canvas)
158
- return this._canvas
159
- }
160
-
161
- // test support for WASM, ImageData, alphaBug, but only once, on init so it doesn't run when first running the page
162
-
163
- /** @type {boolean|null} */
164
- static _supportsSIMD = null
165
- /** @type {boolean|null} */
166
- static _hasAlphaBug = null
167
- /** @type {boolean|null} */
168
- static _hasBitmapBug = null
169
-
170
- static _testSIMD () {
171
- if (JASSUB._supportsSIMD !== null) return
172
-
173
- try {
174
- JASSUB._supportsSIMD = WebAssembly.validate(Uint8Array.of(0, 97, 115, 109, 1, 0, 0, 0, 1, 5, 1, 96, 0, 1, 123, 3, 2, 1, 0, 10, 10, 1, 8, 0, 65, 0, 253, 15, 253, 98, 11))
175
- } catch (e) {
176
- JASSUB._supportsSIMD = false
177
- }
178
- }
179
-
180
- static async _testImageBugs () {
181
- if (JASSUB._hasBitmapBug !== null) return
182
-
183
- const canvas1 = document.createElement('canvas')
184
- const ctx1 = canvas1.getContext('2d', { willReadFrequently: true })
185
- if (!ctx1) throw new Error('Canvas rendering not supported')
186
- // test ImageData constructor
187
- if (typeof ImageData.prototype.constructor === 'function') {
188
- try {
189
- // try actually calling ImageData, as on some browsers it's reported
190
- // as existing but calling it errors out as "TypeError: Illegal constructor"
191
- // eslint-disable-next-line no-new
192
- new ImageData(new Uint8ClampedArray([0, 0, 0, 0]), 1, 1)
193
- } catch (e) {
194
- console.log('Detected that ImageData is not constructable despite browser saying so')
195
-
196
- // @ts-ignore
197
- self.ImageData = function (data, width, height) {
198
- const imageData = ctx1.createImageData(width, height)
199
- if (data) imageData.data.set(data)
200
- return imageData
201
- }
202
- }
203
- }
204
-
205
- // Test for alpha bug, where e.g. WebKit can render a transparent pixel
206
- // (with alpha == 0) as non-black which then leads to visual artifacts.
207
- const canvas2 = document.createElement('canvas')
208
- const ctx2 = canvas2.getContext('2d', { willReadFrequently: true })
209
- if (!ctx2) throw new Error('Canvas rendering not supported')
210
-
211
- canvas1.width = canvas2.width = 1
212
- canvas1.height = canvas2.height = 1
213
- ctx1.clearRect(0, 0, 1, 1)
214
- ctx2.clearRect(0, 0, 1, 1)
215
- const prePut = ctx2.getImageData(0, 0, 1, 1).data
216
- ctx1.putImageData(new ImageData(new Uint8ClampedArray([0, 255, 0, 0]), 1, 1), 0, 0)
217
- ctx2.drawImage(canvas1, 0, 0)
218
- const postPut = ctx2.getImageData(0, 0, 1, 1).data
219
- JASSUB._hasAlphaBug = prePut[1] !== postPut[1]
220
- if (JASSUB._hasAlphaBug) console.log('Detected a browser having issue with transparent pixels, applying workaround')
221
-
222
- if (typeof createImageBitmap !== 'undefined') {
223
- const subarray = new Uint8ClampedArray([255, 0, 255, 0, 255]).subarray(1, 5)
224
- ctx2.drawImage(await createImageBitmap(new ImageData(subarray, 1)), 0, 0)
225
- const { data } = ctx2.getImageData(0, 0, 1, 1)
226
- JASSUB._hasBitmapBug = false
227
- for (const [i, number] of data.entries()) {
228
- // realistically at most this will be a diff of 4, but just to be safe
229
- if (Math.abs(subarray[i] - number) > 15) {
230
- JASSUB._hasBitmapBug = true
231
- console.log('Detected a browser having issue with partial bitmaps, applying workaround')
232
- break
233
- }
234
- }
235
- } else {
236
- JASSUB._hasBitmapBug = false
237
- }
238
-
239
- canvas1.remove()
240
- canvas2.remove()
241
- }
242
-
243
- static async _test () {
244
- JASSUB._testSIMD()
245
- await JASSUB._testImageBugs()
246
- }
247
-
248
- /**
249
- * Resize the canvas to given parameters. Auto-generated if values are ommited.
250
- * @param {Number} [width=0]
251
- * @param {Number} [height=0]
252
- * @param {Number} [top=0]
253
- * @param {Number} [left=0]
254
- * @param {Boolean} [force=false]
255
- */
256
- resize (width = 0, height = 0, top = 0, left = 0, force = this._video?.paused) {
257
- if ((!width || !height) && this._video) {
258
- const videoSize = this._getVideoPosition()
259
- let renderSize = null
260
- // support anamorphic video
261
- if (this._videoWidth) {
262
- const widthRatio = this._video.videoWidth / this._videoWidth
263
- const heightRatio = this._video.videoHeight / this._videoHeight
264
- renderSize = this._computeCanvasSize((videoSize.width || 0) / widthRatio, (videoSize.height || 0) / heightRatio)
265
- } else {
266
- renderSize = this._computeCanvasSize(videoSize.width || 0, videoSize.height || 0)
267
- }
268
- width = renderSize.width
269
- height = renderSize.height
270
- if (this._canvasParent) {
271
- top = videoSize.y - (this._canvasParent.getBoundingClientRect().top - this._video.getBoundingClientRect().top)
272
- left = videoSize.x
273
- }
274
- this._canvas.style.width = videoSize.width + 'px'
275
- this._canvas.style.height = videoSize.height + 'px'
276
- }
277
-
278
- this._canvas.style.top = top + 'px'
279
- this._canvas.style.left = left + 'px'
280
- if (force && this.busy === false) {
281
- this.busy = true
282
- } else {
283
- force = false
284
- }
285
- this.sendMessage('canvas', { width, height, videoWidth: this._videoWidth || this._video.videoWidth, videoHeight: this._videoHeight || this._video.videoHeight, force })
286
- }
287
-
288
- _getVideoPosition (width = this._video.videoWidth, height = this._video.videoHeight) {
289
- const videoRatio = width / height
290
- const { offsetWidth, offsetHeight } = this._video
291
- const elementRatio = offsetWidth / offsetHeight
292
- width = offsetWidth
293
- height = offsetHeight
294
- if (elementRatio > videoRatio) {
295
- width = Math.floor(offsetHeight * videoRatio)
296
- } else {
297
- height = Math.floor(offsetWidth / videoRatio)
298
- }
299
-
300
- const x = (offsetWidth - width) / 2
301
- const y = (offsetHeight - height) / 2
302
-
303
- return { width, height, x, y }
304
- }
305
-
306
- _computeCanvasSize (width = 0, height = 0) {
307
- const scalefactor = this.prescaleFactor <= 0 ? 1.0 : this.prescaleFactor
308
- const ratio = self.devicePixelRatio || 1
309
-
310
- if (height <= 0 || width <= 0) {
311
- width = 0
312
- height = 0
313
- } else {
314
- const sgn = scalefactor < 1 ? -1 : 1
315
- let newH = height * ratio
316
- if (sgn * newH * scalefactor <= sgn * this.prescaleHeightLimit) {
317
- newH *= scalefactor
318
- } else if (sgn * newH < sgn * this.prescaleHeightLimit) {
319
- newH = this.prescaleHeightLimit
320
- }
321
-
322
- if (this.maxRenderHeight > 0 && newH > this.maxRenderHeight) newH = this.maxRenderHeight
323
-
324
- width *= newH / height
325
- height = newH
326
- }
327
-
328
- return { width, height }
329
- }
330
-
331
- _timeupdate ({ type }) {
332
- const eventmap = {
333
- seeking: true,
334
- waiting: true,
335
- playing: false
336
- }
337
- const playing = eventmap[type]
338
- if (playing != null) this._playstate = playing
339
- this.setCurrentTime(this._video.paused || this._playstate, this._video.currentTime + this.timeOffset)
340
- }
341
-
342
- /**
343
- * Change the video to use as target for event listeners.
344
- * @param {HTMLVideoElement} video
345
- */
346
- setVideo (video) {
347
- if (video instanceof HTMLVideoElement) {
348
- this._removeListeners()
349
- this._video = video
350
- if (this._onDemandRender) {
351
- this._video.requestVideoFrameCallback(this._handleRVFC.bind(this))
352
- } else {
353
- this._playstate = video.paused
354
-
355
- video.addEventListener('timeupdate', this._boundTimeUpdate, false)
356
- video.addEventListener('progress', this._boundTimeUpdate, false)
357
- video.addEventListener('waiting', this._boundTimeUpdate, false)
358
- video.addEventListener('seeking', this._boundTimeUpdate, false)
359
- video.addEventListener('playing', this._boundTimeUpdate, false)
360
- video.addEventListener('ratechange', this._boundSetRate, false)
361
- video.addEventListener('resize', this._boundResize, false)
362
- }
363
- // everything else is unreliable for this, loadedmetadata and loadeddata included.
364
- if ('VideoFrame' in window) {
365
- video.addEventListener('loadedmetadata', this._boundUpdateColorSpace, false)
366
- if (video.readyState > 2) this._updateColorSpace()
367
- }
368
- if (video.videoWidth > 0) this.resize()
369
- // Support Element Resize Observer
370
- if (typeof ResizeObserver !== 'undefined') {
371
- if (!this._ro) this._ro = new ResizeObserver(() => this.resize())
372
- this._ro.observe(video)
373
- }
374
- } else {
375
- this._error('Video element invalid!')
376
- }
377
- }
378
-
379
- runBenchmark () {
380
- this.sendMessage('runBenchmark')
381
- }
382
-
383
- /**
384
- * Overwrites the current subtitle content.
385
- * @param {String} url URL to load subtitles from.
386
- */
387
- setTrackByUrl (url) {
388
- this.sendMessage('setTrackByUrl', { url })
389
- this._reAttachOffscreen()
390
- if (this._ctx) this._ctx.filter = 'none'
391
- }
392
-
393
- /**
394
- * Overwrites the current subtitle content.
395
- * @param {String} content Content of the ASS file.
396
- */
397
- setTrack (content) {
398
- this.sendMessage('setTrack', { content })
399
- this._reAttachOffscreen()
400
- if (this._ctx) this._ctx.filter = 'none'
401
- }
402
-
403
- /**
404
- * Free currently used subtitle track.
405
- */
406
- freeTrack () {
407
- this.sendMessage('freeTrack')
408
- }
409
-
410
- /**
411
- * Sets the playback state of the media.
412
- * @param {Boolean} isPaused Pause/Play subtitle playback.
413
- */
414
- setIsPaused (isPaused) {
415
- this.sendMessage('video', { isPaused })
416
- }
417
-
418
- /**
419
- * Sets the playback rate of the media [speed multiplier].
420
- * @param {Number} rate Playback rate.
421
- */
422
- setRate (rate) {
423
- this.sendMessage('video', { rate })
424
- }
425
-
426
- /**
427
- * Sets the current time, playback state and rate of the subtitles.
428
- * @param {Boolean} [isPaused] Pause/Play subtitle playback.
429
- * @param {Number} [currentTime] Time in seconds.
430
- * @param {Number} [rate] Playback rate.
431
- */
432
- setCurrentTime (isPaused, currentTime, rate) {
433
- this.sendMessage('video', { isPaused, currentTime, rate, colorSpace: this._videoColorSpace })
434
- }
435
-
436
- /**
437
- * @typedef {Object} ASS_Event
438
- * @property {Number} Start Start Time of the Event, in 0:00:00:00 format ie. Hrs:Mins:Secs:hundredths. This is the time elapsed during script playback at which the text will appear onscreen. Note that there is a single digit for the hours!
439
- * @property {Number} Duration End Time of the Event, in 0:00:00:00 format ie. Hrs:Mins:Secs:hundredths. This is the time elapsed during script playback at which the text will disappear offscreen. Note that there is a single digit for the hours!
440
- * @property {String} Style Style name. If it is "Default", then your own *Default style will be subtituted.
441
- * @property {String} Name Character name. This is the name of the character who speaks the dialogue. It is for information only, to make the script is easier to follow when editing/timing.
442
- * @property {Number} MarginL 4-figure Left Margin override. The values are in pixels. All zeroes means the default margins defined by the style are used.
443
- * @property {Number} MarginR 4-figure Right Margin override. The values are in pixels. All zeroes means the default margins defined by the style are used.
444
- * @property {Number} MarginV 4-figure Bottom Margin override. The values are in pixels. All zeroes means the default margins defined by the style are used.
445
- * @property {String} Effect Transition Effect. This is either empty, or contains information for one of the three transition effects implemented in SSA v4.x
446
- * @property {String} Text Subtitle Text. This is the actual text which will be displayed as a subtitle onscreen. Everything after the 9th comma is treated as the subtitle text, so it can include commas.
447
- * @property {Number} ReadOrder Number in order of which to read this event.
448
- * @property {Number} Layer Z-index overlap in which to render this event.
449
- * @property {Number} _index (Internal) index of the event.
450
- */
451
-
452
- /**
453
- * Create a new ASS event directly.
454
- * @param {ASS_Event} event
455
- */
456
- createEvent (event) {
457
- this.sendMessage('createEvent', { event })
458
- }
459
-
460
- /**
461
- * Overwrite the data of the event with the specified index.
462
- * @param {ASS_Event} event
463
- * @param {Number} index
464
- */
465
- setEvent (event, index) {
466
- this.sendMessage('setEvent', { event, index })
467
- }
468
-
469
- /**
470
- * Remove the event with the specified index.
471
- * @param {Number} index
472
- */
473
- removeEvent (index) {
474
- this.sendMessage('removeEvent', { index })
475
- }
476
-
477
- /**
478
- * Get all ASS events.
479
- * @param {function(Error|null, ASS_Event): void} callback Function to callback when worker returns the events.
480
- */
481
- getEvents (callback) {
482
- this._fetchFromWorker({
483
- target: 'getEvents'
484
- }, (err, { events }) => {
485
- callback(err, events)
486
- })
487
- }
488
-
489
- /**
490
- * Set a style override.
491
- * @param {ASS_Style} style
492
- */
493
- styleOverride(style) {
494
- this.sendMessage('styleOverride', { style })
495
- }
496
-
497
- /**
498
- * Disable style override.
499
- */
500
- disableStyleOverride() {
501
- this.sendMessage('disableStyleOverride')
502
- }
503
-
504
- /**
505
- * @typedef {Object} ASS_Style
506
- * @property {String} Name The name of the Style. Case sensitive. Cannot include commas.
507
- * @property {String} FontName The fontname as used by Windows. Case-sensitive.
508
- * @property {Number} FontSize Font size.
509
- * @property {Number} PrimaryColour A long integer BGR (blue-green-red) value. ie. the byte order in the hexadecimal equivelent of this number is BBGGRR
510
- * @property {Number} SecondaryColour A long integer BGR (blue-green-red) value. ie. the byte order in the hexadecimal equivelent of this number is BBGGRR
511
- * @property {Number} OutlineColour A long integer BGR (blue-green-red) value. ie. the byte order in the hexadecimal equivelent of this number is BBGGRR
512
- * @property {Number} BackColour This is the colour of the subtitle outline or shadow, if these are used. A long integer BGR (blue-green-red) value. ie. the byte order in the hexadecimal equivelent of this number is BBGGRR.
513
- * @property {Number} Bold This defines whether text is bold (true) or not (false). -1 is True, 0 is False. This is independant of the Italic attribute - you can have have text which is both bold and italic.
514
- * @property {Number} Italic Italic. This defines whether text is italic (true) or not (false). -1 is True, 0 is False. This is independant of the bold attribute - you can have have text which is both bold and italic.
515
- * @property {Number} Underline -1 or 0
516
- * @property {Number} StrikeOut -1 or 0
517
- * @property {Number} ScaleX Modifies the width of the font. [percent]
518
- * @property {Number} ScaleY Modifies the height of the font. [percent]
519
- * @property {Number} Spacing Extra space between characters. [pixels]
520
- * @property {Number} Angle The origin of the rotation is defined by the alignment. Can be a floating point number. [degrees]
521
- * @property {Number} BorderStyle 1=Outline + drop shadow, 3=Opaque box
522
- * @property {Number} Outline If BorderStyle is 1, then this specifies the width of the outline around the text, in pixels. Values may be 0, 1, 2, 3 or 4.
523
- * @property {Number} Shadow If BorderStyle is 1, then this specifies the depth of the drop shadow behind the text, in pixels. Values may be 0, 1, 2, 3 or 4. Drop shadow is always used in addition to an outline - SSA will force an outline of 1 pixel if no outline width is given.
524
- * @property {Number} Alignment This sets how text is "justified" within the Left/Right onscreen margins, and also the vertical placing. Values may be 1=Left, 2=Centered, 3=Right. Add 4 to the value for a "Toptitle". Add 8 to the value for a "Midtitle". eg. 5 = left-justified toptitle
525
- * @property {Number} MarginL This defines the Left Margin in pixels. It is the distance from the left-hand edge of the screen.The three onscreen margins (MarginL, MarginR, MarginV) define areas in which the subtitle text will be displayed.
526
- * @property {Number} MarginR This defines the Right Margin in pixels. It is the distance from the right-hand edge of the screen. The three onscreen margins (MarginL, MarginR, MarginV) define areas in which the subtitle text will be displayed.
527
- * @property {Number} MarginV This defines the vertical Left Margin in pixels. For a subtitle, it is the distance from the bottom of the screen. For a toptitle, it is the distance from the top of the screen. For a midtitle, the value is ignored - the text will be vertically centred.
528
- * @property {Number} Encoding This specifies the font character set or encoding and on multi-lingual Windows installations it provides access to characters used in multiple than one languages. It is usually 0 (zero) for English (Western, ANSI) Windows.
529
- * @property {Number} treat_fontname_as_pattern
530
- * @property {Number} Blur
531
- * @property {Number} Justify
532
- */
533
-
534
- /**
535
- * Create a new ASS style directly.
536
- * @param {ASS_Style} style
537
- */
538
- createStyle (style) {
539
- this.sendMessage('createStyle', { style })
540
- }
541
-
542
- /**
543
- * Overwrite the data of the style with the specified index.
544
- * @param {ASS_Style} style
545
- * @param {Number} index
546
- */
547
- setStyle (style, index) {
548
- this.sendMessage('setStyle', { style, index })
549
- }
550
-
551
- /**
552
- * Remove the style with the specified index.
553
- * @param {Number} index
554
- */
555
- removeStyle (index) {
556
- this.sendMessage('removeStyle', { index })
557
- }
558
-
559
- /**
560
- * Get all ASS styles.
561
- * @param {function(Error|null, ASS_Style): void} callback Function to callback when worker returns the styles.
562
- */
563
- getStyles (callback) {
564
- this._fetchFromWorker({
565
- target: 'getStyles'
566
- }, (err, { styles }) => {
567
- callback(err, styles)
568
- })
569
- }
570
-
571
- /**
572
- * Adds a font to the renderer.
573
- * @param {String|Uint8Array} font Font to add.
574
- */
575
- addFont (font) {
576
- this.sendMessage('addFont', { font })
577
- }
578
- /**
579
- * Changes the font family of the default font, this font needs to be previously added via addFont or fonts array on construction.
580
- * @param {String} font Font family to change to.
581
- */
582
- setDefaultFont(font) {
583
- this.sendMessage('defaultFont', { font })
584
- }
585
-
586
- _sendLocalFont (name) {
587
- try {
588
- // @ts-ignore
589
- queryLocalFonts().then(fontData => {
590
- const font = fontData?.find(obj => obj.fullName.toLowerCase() === name)
591
- if (font) {
592
- font.blob().then(blob => {
593
- blob.arrayBuffer().then(buffer => {
594
- this.addFont(new Uint8Array(buffer))
595
- })
596
- })
597
- }
598
- })
599
- } catch (e) {
600
- console.warn('Local fonts API:', e)
601
- }
602
- }
603
-
604
- _getLocalFont ({ font }) {
605
- try {
606
- // electron by default has all permissions enabled, and it doesn't have perm query
607
- // if this happens, just send it
608
- if (navigator?.permissions?.query) {
609
- // @ts-ignore
610
- navigator.permissions.query({ name: 'local-fonts' }).then(permission => {
611
- if (permission.state === 'granted') {
612
- this._sendLocalFont(font)
613
- }
614
- })
615
- } else {
616
- this._sendLocalFont(font)
617
- }
618
- } catch (e) {
619
- console.warn('Local fonts API:', e)
620
- }
621
- }
622
-
623
- _unbusy () {
624
- // play catchup, leads to more frames being painted, but also more jitter
625
- if (this._lastDemandTime) {
626
- this._demandRender(this._lastDemandTime)
627
- } else {
628
- this.busy = false
629
- }
630
- }
631
-
632
- _handleRVFC (now, { mediaTime, width, height }) {
633
- if (this._destroyed) return null
634
- if (this.busy) {
635
- this._lastDemandTime = { mediaTime, width, height }
636
- } else {
637
- this.busy = true
638
- this._demandRender({ mediaTime, width, height })
639
- }
640
- this._video.requestVideoFrameCallback(this._handleRVFC.bind(this))
641
- }
642
-
643
- _demandRender ({ mediaTime, width, height }) {
644
- this._lastDemandTime = null
645
- if (width !== this._videoWidth || height !== this._videoHeight) {
646
- this._videoWidth = width
647
- this._videoHeight = height
648
- this.resize()
649
- }
650
- this.sendMessage('demand', { time: mediaTime + this.timeOffset })
651
- }
652
-
653
- // if we're using offscreen render, we can't use ctx filters, so we can't use a transfered canvas
654
- _detachOffscreen () {
655
- if (!this._offscreenRender || this._ctx) return null
656
- this._canvas.remove()
657
- this._createCanvas()
658
- this._canvasctrl = this._canvas
659
- this._ctx = this._canvasctrl.getContext('2d')
660
- this.sendMessage('detachOffscreen')
661
- // force a render after resize
662
- this.busy = false
663
- this.resize(0, 0, 0, 0, true)
664
- }
665
-
666
- // if the video or track changed, we need to re-attach the offscreen canvas
667
- _reAttachOffscreen () {
668
- if (!this._offscreenRender || !this._ctx) return null
669
- this._canvas.remove()
670
- this._createCanvas()
671
- this._canvasctrl = this._canvas.transferControlToOffscreen()
672
- this._ctx = false
673
- this.sendMessage('offscreenCanvas', null, [this._canvasctrl])
674
- this.resize(0, 0, 0, 0, true)
675
- }
676
-
677
- _updateColorSpace () {
678
- this._video.requestVideoFrameCallback(() => {
679
- try {
680
- // eslint-disable-next-line no-undef
681
- const frame = new VideoFrame(this._video)
682
- this._videoColorSpace = webYCbCrMap[frame.colorSpace.matrix]
683
- frame.close()
684
- this.sendMessage('getColorSpace')
685
- } catch (e) {
686
- // sources can be tainted
687
- console.warn(e)
688
- }
689
- })
690
- }
691
-
692
- /**
693
- * Veryify the color spaces for subtitles and videos, then apply filters to correct the color of subtitles.
694
- * @param {Object} options
695
- * @param {String} options.subtitleColorSpace Subtitle color space. One of: BT601 BT709 SMPTE240M FCC
696
- * @param {String=} options.videoColorSpace Video color space. One of: BT601 BT709
697
- */
698
- _verifyColorSpace ({ subtitleColorSpace, videoColorSpace = this._videoColorSpace }) {
699
- if (!subtitleColorSpace || !videoColorSpace) return
700
- if (subtitleColorSpace === videoColorSpace) return
701
- this._detachOffscreen()
702
- this._ctx.filter = `url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg'><filter id='f'><feColorMatrix type='matrix' values='${colorMatrixConversionMap[subtitleColorSpace][videoColorSpace]} 0 0 0 0 0 1 0'/></filter></svg>#f")`
703
- }
704
-
705
- _render ({ images, asyncRender, times, width, height, colorSpace }) {
706
- this._unbusy()
707
- if (this.debug) times.IPCTime = Date.now() - times.JSRenderTime
708
- if (this._canvasctrl.width !== width || this._canvasctrl.height !== height) {
709
- this._canvasctrl.width = width
710
- this._canvasctrl.height = height
711
- this._verifyColorSpace({ subtitleColorSpace: colorSpace })
712
- }
713
- this._ctx.clearRect(0, 0, this._canvasctrl.width, this._canvasctrl.height)
714
- for (const image of images) {
715
- if (image.image) {
716
- if (asyncRender) {
717
- this._ctx.drawImage(image.image, image.x, image.y)
718
- image.image.close()
719
- } else {
720
- this._bufferCanvas.width = image.w
721
- this._bufferCanvas.height = image.h
722
- this._bufferCtx.putImageData(new ImageData(this._fixAlpha(new Uint8ClampedArray(image.image)), image.w, image.h), 0, 0)
723
- this._ctx.drawImage(this._bufferCanvas, image.x, image.y)
724
- }
725
- }
726
- }
727
- if (this.debug) {
728
- times.JSRenderTime = Date.now() - times.JSRenderTime - times.IPCTime
729
- let total = 0
730
- const count = times.bitmaps || images.length
731
- delete times.bitmaps
732
- for (const key in times) total += times[key]
733
- console.log('Bitmaps: ' + count + ' Total: ' + (total | 0) + 'ms', times)
734
- }
735
- }
736
-
737
- _fixAlpha (uint8) {
738
- if (JASSUB._hasAlphaBug) {
739
- for (let j = 3; j < uint8.length; j += 4) {
740
- uint8[j] = uint8[j] > 1 ? uint8[j] : 1
741
- }
742
- }
743
- return uint8
744
- }
745
-
746
- _ready () {
747
- this._init()
748
- this.dispatchEvent(new CustomEvent('ready'))
749
- }
750
-
751
- /**
752
- * Send data and execute function in the worker.
753
- * @param {String} target Target function.
754
- * @param {Object} [data] Data for function.
755
- * @param {Transferable[]} [transferable] Array of transferables.
756
- */
757
- async sendMessage (target, data = {}, transferable) {
758
- await this._loaded
759
- if (transferable) {
760
- this._worker.postMessage({
761
- target,
762
- transferable,
763
- ...data
764
- }, [...transferable])
765
- } else {
766
- this._worker.postMessage({
767
- target,
768
- ...data
769
- })
770
- }
771
- }
772
-
773
- _fetchFromWorker (workerOptions, callback) {
774
- try {
775
- const target = workerOptions.target
776
-
777
- const timeout = setTimeout(() => {
778
- reject(new Error('Error: Timeout while try to fetch ' + target))
779
- }, 5000)
780
-
781
- const resolve = ({ data }) => {
782
- if (data.target === target) {
783
- callback(null, data)
784
- this._worker.removeEventListener('message', resolve)
785
- this._worker.removeEventListener('error', reject)
786
- clearTimeout(timeout)
787
- }
788
- }
789
-
790
- const reject = event => {
791
- callback(event)
792
- this._worker.removeEventListener('message', resolve)
793
- this._worker.removeEventListener('error', reject)
794
- clearTimeout(timeout)
795
- }
796
-
797
- this._worker.addEventListener('message', resolve)
798
- this._worker.addEventListener('error', reject)
799
-
800
- this._worker.postMessage(workerOptions)
801
- } catch (error) {
802
- this._error(error)
803
- }
804
- }
805
-
806
- _console ({ content, command }) {
807
- console[command].apply(console, JSON.parse(content))
808
- }
809
-
810
- _onmessage ({ data }) {
811
- if (this['_' + data.target]) this['_' + data.target](data)
812
- }
813
-
814
- _error (err) {
815
- const error = err instanceof Error
816
- ? err // pass
817
- : err instanceof ErrorEvent
818
- ? err.error // ErrorEvent has error property which is an Error object
819
- : new Error(err) // construct Error
820
-
821
- const event = err instanceof Event
822
- ? new ErrorEvent(err.type, err) // clone event
823
- : new ErrorEvent('error', { error }) // construct Event
824
-
825
- this.dispatchEvent(event)
826
-
827
- console.error(error)
828
-
829
- return error
830
- }
831
-
832
- _removeListeners () {
833
- if (this._video) {
834
- if (this._ro) this._ro.unobserve(this._video)
835
- if (this._ctx) this._ctx.filter = 'none'
836
- this._video.removeEventListener('timeupdate', this._boundTimeUpdate)
837
- this._video.removeEventListener('progress', this._boundTimeUpdate)
838
- this._video.removeEventListener('waiting', this._boundTimeUpdate)
839
- this._video.removeEventListener('seeking', this._boundTimeUpdate)
840
- this._video.removeEventListener('playing', this._boundTimeUpdate)
841
- this._video.removeEventListener('ratechange', this._boundSetRate)
842
- this._video.removeEventListener('resize', this._boundResize)
843
- this._video.removeEventListener('loadedmetadata', this._boundUpdateColorSpace)
844
- }
845
- }
846
-
847
- /**
848
- * Destroy the object, worker, listeners and all data.
849
- * @param {String|Error} [err] Error to throw when destroying.
850
- */
851
- destroy (err) {
852
- if (err) err = this._error(err)
853
- if (this._video && this._canvasParent) this._video.parentNode?.removeChild(this._canvasParent)
854
- this._destroyed = true
855
- this._removeListeners()
856
- this.sendMessage('destroy')
857
- this._worker?.terminate()
858
- return err
859
- }
860
- }