jassub 1.2.4 → 1.4.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/dist/jassub.js DELETED
@@ -1,688 +0,0 @@
1
- // visit ./COPYRIGHT for copyright information
2
-
3
- import 'rvfc-polyfill'
4
-
5
- /**
6
- * New JASSUB instance.
7
- * @class
8
- */
9
- export default class JASSUB extends EventTarget {
10
- /**
11
- * @param {Object} options Settings object.
12
- * @param {HTMLVideoElement} options.video Video to use as target for rendering and event listeners. Optional if canvas is specified instead.
13
- * @param {HTMLCanvasElement} [options.canvas=HTMLCanvasElement] Canvas to use for manual handling. Not required if video is specified.
14
- * @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.
15
- * @param {Boolean} [options.asyncRender=true] Whether or not to use async rendering, which offloads the CPU by creating image bitmaps on the GPU.
16
- * @param {Boolean} [options.offscreenRender=true] Whether or not to render things fully on the worker, greatly reduces CPU usage.
17
- * @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.
18
- * @param {Number} [options.targetFps=24] Target FPS to render subtitles at. Ignored when onDemandRender is enabled.
19
- * @param {Number} [options.timeOffset=0] Subtitle time offset in seconds.
20
- * @param {Boolean} [options.debug=false] Whether or not to print debug information.
21
- * @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).
22
- * @param {Number} [options.prescaleHeightLimit=1080] The height in pixels beyond which the subtitles canvas won't be prescaled.
23
- * @param {Number} [options.maxRenderHeight=0] The maximum rendering height in pixels of the subtitles canvas. Beyond this subtitles will be upscaled by the browser.
24
- * @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.
25
- * @param {String} [options.workerUrl='jassub-worker.js'] The URL of the worker.
26
- * @param {String} [options.legacyWorkerUrl='jassub-worker-legacy.js'] The URL of the legacy worker. Only loaded if the browser doesn't support WASM.
27
- * @param {String} [options.subUrl=options.subContent] The URL of the subtitle file to play.
28
- * @param {String} [options.subContent=options.subUrl] The content of the subtitle file to play.
29
- * @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.
30
- * @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.
31
- * @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.
32
- * @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' }).
33
- * @param {Number} [options.libassMemoryLimit] libass bitmap cache memory limit in MiB (approximate).
34
- * @param {Number} [options.libassGlyphLimit] libass glyph cache memory limit in MiB (approximate).
35
- */
36
- constructor (options = {}) {
37
- super()
38
- if (!globalThis.Worker) {
39
- this.destroy('Worker not supported')
40
- }
41
- JASSUB._test()
42
- const blendMode = options.blendMode || 'js'
43
- const asyncRender = typeof createImageBitmap !== 'undefined' && (options.asyncRender ?? true)
44
- const offscreenRender = typeof OffscreenCanvas !== 'undefined' && (options.offscreenRender ?? true)
45
- this._onDemandRender = 'requestVideoFrameCallback' in HTMLVideoElement.prototype && (options.onDemandRender ?? true)
46
-
47
- this.timeOffset = options.timeOffset || 0
48
- this._video = options.video
49
- this._canvas = options.canvas
50
- if (this._video && !this._canvas) {
51
- this._canvasParent = document.createElement('div')
52
- this._canvasParent.className = 'JASSUB'
53
- this._canvasParent.style.position = 'relative'
54
-
55
- this._canvas = document.createElement('canvas')
56
- this._canvas.style.display = 'block'
57
- this._canvas.style.position = 'absolute'
58
- this._canvas.style.pointerEvents = 'none'
59
- this._canvasParent.appendChild(this._canvas)
60
-
61
- if (this._video.nextSibling) {
62
- this._video.parentNode.insertBefore(this._canvasParent, this._video.nextSibling)
63
- } else {
64
- this._video.parentNode.appendChild(this._canvasParent)
65
- }
66
- } else if (!this._canvas) {
67
- this.destroy('Don\'t know where to render: you should give video or canvas in options.')
68
- }
69
-
70
- this._bufferCanvas = document.createElement('canvas')
71
- this._bufferCtx = this._bufferCanvas.getContext('2d', { desynchronized: true, willReadFrequently: true })
72
-
73
- this._canvasctrl = offscreenRender ? this._canvas.transferControlToOffscreen() : this._canvas
74
- this._ctx = !offscreenRender && this._canvasctrl.getContext('2d', { desynchronized: true })
75
-
76
- this._lastRenderTime = 0
77
- this.debug = !!options.debug
78
-
79
- this.prescaleFactor = options.prescaleFactor || 1.0
80
- this.prescaleHeightLimit = options.prescaleHeightLimit || 1080
81
- this.maxRenderHeight = options.maxRenderHeight || 0 // 0 - no limit.
82
-
83
- this._worker = new Worker(JASSUB._supportsWebAssembly ? options.workerUrl || 'jassub-worker.js' : options.legacyWorkerUrl || 'jassub-worker-legacy.js')
84
- this._worker.onmessage = e => this._onmessage(e)
85
- this._worker.onerror = e => this._error(e)
86
-
87
- this._worker.postMessage({
88
- target: 'init',
89
- asyncRender,
90
- onDemandRender: this._onDemandRender,
91
- width: this._canvas.width,
92
- height: this._canvas.height,
93
- preMain: true,
94
- blendMode,
95
- subUrl: options.subUrl,
96
- subContent: options.subContent || null,
97
- fonts: options.fonts || [],
98
- availableFonts: options.availableFonts || { 'liberation sans': './default.woff2' },
99
- fallbackFont: options.fallbackFont || 'liberation sans',
100
- debug: this.debug,
101
- targetFps: options.targetFps || 24,
102
- dropAllAnimations: options.dropAllAnimations,
103
- libassMemoryLimit: options.libassMemoryLimit || 0,
104
- libassGlyphLimit: options.libassGlyphLimit || 0,
105
- hasAlphaBug: JASSUB._hasAlphaBug,
106
- useLocalFonts: ('queryLocalFonts' in self) && (options.useLocalFonts ?? true)
107
- })
108
- if (offscreenRender === true) this.sendMessage('offscreenCanvas', null, [this._canvasctrl])
109
-
110
- this._boundResize = this.resize.bind(this)
111
- this._boundTimeUpdate = this._timeupdate.bind(this)
112
- this._boundSetRate = this.setRate.bind(this)
113
- if (this._video) this.setVideo(options.video)
114
-
115
- if (this._onDemandRender) {
116
- this.busy = false
117
- this._lastDemandTime = null
118
- this._video?.requestVideoFrameCallback(this._handleRVFC.bind(this))
119
- }
120
- }
121
-
122
- // test support for WASM, ImageData, alphaBug, but only once, on init so it doesn't run when first running the page
123
- static _supportsWebAssembly = null
124
- static _hasAlphaBug = null
125
-
126
- static _test () {
127
- // check if ran previously
128
- if (JASSUB._supportsWebAssembly !== null) return null
129
-
130
- const canvas1 = document.createElement('canvas')
131
- const ctx1 = canvas1.getContext('2d', { willReadFrequently: true })
132
- // test ImageData constructor
133
- if (typeof ImageData.prototype.constructor === 'function') {
134
- try {
135
- // try actually calling ImageData, as on some browsers it's reported
136
- // as existing but calling it errors out as "TypeError: Illegal constructor"
137
- // eslint-disable-next-line no-new
138
- new ImageData(new Uint8ClampedArray([0, 0, 0, 0]), 1, 1)
139
- } catch (e) {
140
- console.log('detected that ImageData is not constructable despite browser saying so')
141
-
142
- self.ImageData = function (data, width, height) {
143
- const imageData = ctx1.createImageData(width, height)
144
- if (data) imageData.data.set(data)
145
- return imageData
146
- }
147
- }
148
- }
149
-
150
- try {
151
- if (typeof WebAssembly === 'object' && typeof WebAssembly.instantiate === 'function') {
152
- const module = new WebAssembly.Module(Uint8Array.of(0x0, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00))
153
- if (module instanceof WebAssembly.Module) JASSUB._supportsWebAssembly = (new WebAssembly.Instance(module) instanceof WebAssembly.Instance)
154
- }
155
- } catch (e) {
156
- JASSUB._supportsWebAssembly = false
157
- }
158
-
159
- // Test for alpha bug, where e.g. WebKit can render a transparent pixel
160
- // (with alpha == 0) as non-black which then leads to visual artifacts.
161
- const canvas2 = document.createElement('canvas')
162
- const ctx2 = canvas2.getContext('2d', { willReadFrequently: true })
163
-
164
- canvas1.width = canvas2.width = 1
165
- canvas1.height = canvas2.height = 1
166
- ctx1.clearRect(0, 0, 1, 1)
167
- ctx2.clearRect(0, 0, 1, 1)
168
- const prePut = ctx2.getImageData(0, 0, 1, 1).data
169
- ctx1.putImageData(new ImageData(new Uint8ClampedArray([0, 255, 0, 0]), 1, 1), 0, 0)
170
- ctx2.drawImage(canvas1, 0, 0)
171
- const postPut = ctx2.getImageData(0, 0, 1, 1).data
172
- JASSUB._hasAlphaBug = prePut[1] !== postPut[1]
173
- if (JASSUB._hasAlphaBug) console.log('Detected a browser having issue with transparent pixels, applying workaround')
174
- canvas1.remove()
175
- canvas2.remove()
176
- }
177
-
178
- /**
179
- * Resize the canvas to given parameters. Auto-generated if values are ommited.
180
- * @param {Number} [width=0]
181
- * @param {Number} [height=0]
182
- * @param {Number} [top=0]
183
- * @param {Number} [left=0]
184
- */
185
- resize (width = 0, height = 0, top = 0, left = 0) {
186
- let videoSize = null
187
- if ((!width || !height) && this._video) {
188
- videoSize = this._getVideoPosition()
189
- const newsize = this._computeCanvasSize((videoSize.width || 0) * (self.devicePixelRatio || 1), (videoSize.height || 0) * (self.devicePixelRatio || 1))
190
- width = newsize.width
191
- height = newsize.height
192
- if (this._canvasParent) {
193
- top = videoSize.y - (this._canvasParent.getBoundingClientRect().top - this._video.getBoundingClientRect().top)
194
- left = videoSize.x
195
- }
196
- }
197
-
198
- if (videoSize != null) {
199
- this._canvas.style.top = top + 'px'
200
- this._canvas.style.left = left + 'px'
201
- this._canvas.style.width = videoSize.width + 'px'
202
- this._canvas.style.height = videoSize.height + 'px'
203
- }
204
- if (!(this._canvasctrl.width === width && this._canvasctrl.height === height)) {
205
- // only re-paint if dimensions actually changed
206
- // dont spam re-paints like crazy when re-sizing with animations, but still update instantly without them
207
- if (this._resizeTimeoutBuffer) {
208
- clearTimeout(this._resizeTimeoutBuffer)
209
- this._resizeTimeoutBuffer = setTimeout(() => {
210
- this._resizeTimeoutBuffer = undefined
211
- this._canvasctrl.width = width
212
- this._canvasctrl.height = height
213
- this.sendMessage('canvas', { width, height })
214
- }, 100)
215
- } else {
216
- this._canvasctrl.width = width
217
- this._canvasctrl.height = height
218
- this.sendMessage('canvas', { width, height })
219
- this._resizeTimeoutBuffer = setTimeout(() => {
220
- this._resizeTimeoutBuffer = undefined
221
- }, 100)
222
- }
223
- }
224
- }
225
-
226
- _getVideoPosition () {
227
- const videoRatio = this._video.videoWidth / this._video.videoHeight
228
- const { offsetWidth, offsetHeight } = this._video
229
- const elementRatio = offsetWidth / offsetHeight
230
- let width = offsetWidth
231
- let height = offsetHeight
232
- if (elementRatio > videoRatio) {
233
- width = Math.floor(offsetHeight * videoRatio)
234
- } else {
235
- height = Math.floor(offsetWidth / videoRatio)
236
- }
237
-
238
- const x = (offsetWidth - width) / 2
239
- const y = (offsetHeight - height) / 2
240
-
241
- return { width, height, x, y }
242
- }
243
-
244
- _computeCanvasSize (width = 0, height = 0) {
245
- const scalefactor = this.prescaleFactor <= 0 ? 1.0 : this.prescaleFactor
246
-
247
- if (height <= 0 || width <= 0) {
248
- width = 0
249
- height = 0
250
- } else {
251
- const sgn = scalefactor < 1 ? -1 : 1
252
- let newH = height
253
- if (sgn * newH * scalefactor <= sgn * this.prescaleHeightLimit) {
254
- newH *= scalefactor
255
- } else if (sgn * newH < sgn * this.prescaleHeightLimit) {
256
- newH = this.prescaleHeightLimit
257
- }
258
-
259
- if (this.maxRenderHeight > 0 && newH > this.maxRenderHeight) newH = this.maxRenderHeight
260
-
261
- width *= newH / height
262
- height = newH
263
- }
264
-
265
- return { width, height }
266
- }
267
-
268
- _timeupdate ({ type }) {
269
- const eventmap = {
270
- seeking: true,
271
- waiting: true,
272
- playing: false
273
- }
274
- const playing = eventmap[type]
275
- if (playing != null) this._playstate = playing
276
- this.setCurrentTime(this._video.paused || this._playstate, this._video.currentTime + this.timeOffset)
277
- }
278
-
279
- /**
280
- * Change the video to use as target for event listeners.
281
- * @param {HTMLVideoElement} video
282
- */
283
- setVideo (video) {
284
- if (video instanceof HTMLVideoElement) {
285
- this._removeListeners()
286
- this._video = video
287
- if (this._onDemandRender) {
288
- this._video.requestVideoFrameCallback(this._handleRVFC.bind(this))
289
- } else {
290
- this._playstate = video.paused
291
-
292
- video.addEventListener('timeupdate', this._boundTimeUpdate, false)
293
- video.addEventListener('progress', this._boundTimeUpdate, false)
294
- video.addEventListener('waiting', this._boundTimeUpdate, false)
295
- video.addEventListener('seeking', this._boundTimeUpdate, false)
296
- video.addEventListener('playing', this._boundTimeUpdate, false)
297
- video.addEventListener('ratechange', this._boundSetRate, false)
298
- }
299
- if (video.videoWidth > 0) this.resize()
300
- video.addEventListener('resize', this._boundResize)
301
- // Support Element Resize Observer
302
- if (typeof ResizeObserver !== 'undefined') {
303
- if (!this._ro) this._ro = new ResizeObserver(() => this.resize())
304
- this._ro.observe(video)
305
- }
306
- } else {
307
- this._error('Video element invalid!')
308
- }
309
- }
310
-
311
- runBenchmark () {
312
- this.sendMessage('runBenchmark')
313
- }
314
-
315
- /**
316
- * Overwrites the current subtitle content.
317
- * @param {String} url URL to load subtitles from.
318
- */
319
- setTrackByUrl (url) {
320
- this.sendMessage('setTrackByUrl', { url })
321
- }
322
-
323
- /**
324
- * Overwrites the current subtitle content.
325
- * @param {String} content Content of the ASS file.
326
- */
327
- setTrack (content) {
328
- this.sendMessage('setTrack', { content })
329
- }
330
-
331
- /**
332
- * Free currently used subtitle track.
333
- */
334
- freeTrack () {
335
- this.sendMessage('freeTrack')
336
- }
337
-
338
- /**
339
- * Sets the playback state of the media.
340
- * @param {Boolean} isPaused Pause/Play subtitle playback.
341
- */
342
- setIsPaused (isPaused) {
343
- this.sendMessage('video', { isPaused })
344
- }
345
-
346
- /**
347
- * Sets the playback rate of the media [speed multiplier].
348
- * @param {Number} rate Playback rate.
349
- */
350
- setRate (rate) {
351
- this.sendMessage('video', { rate })
352
- }
353
-
354
- /**
355
- * Sets the current time, playback state and rate of the subtitles.
356
- * @param {Boolean} [isPaused] Pause/Play subtitle playback.
357
- * @param {Number} [currentTime] Time in seconds.
358
- * @param {Number} [rate] Playback rate.
359
- */
360
- setCurrentTime (isPaused, currentTime, rate) {
361
- this.sendMessage('video', { isPaused, currentTime, rate })
362
- }
363
-
364
- /**
365
- * @typedef {Object} ASS_Event
366
- * @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!
367
- * @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!
368
- * @property {String} Style Style name. If it is "Default", then your own *Default style will be subtituted.
369
- * @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.
370
- * @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.
371
- * @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.
372
- * @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.
373
- * @property {String} Effect Transition Effect. This is either empty, or contains information for one of the three transition effects implemented in SSA v4.x
374
- * @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.
375
- * @property {Number} ReadOrder Number in order of which to read this event.
376
- * @property {Number} Layer Z-index overlap in which to render this event.
377
- * @property {Number} _index (Internal) index of the event.
378
- */
379
-
380
- /**
381
- * Create a new ASS event directly.
382
- * @param {ASS_Event} event
383
- */
384
- createEvent (event) {
385
- this.sendMessage('createEvent', { event })
386
- }
387
-
388
- /**
389
- * Overwrite the data of the event with the specified index.
390
- * @param {ASS_Event} event
391
- * @param {Number} index
392
- */
393
- setEvent (event, index) {
394
- this.sendMessage('setEvent', { event, index })
395
- }
396
-
397
- /**
398
- * Remove the event with the specified index.
399
- * @param {Number} index
400
- */
401
- removeEvent (index) {
402
- this.sendMessage('removeEvent', { index })
403
- }
404
-
405
- /**
406
- * Get all ASS events.
407
- * @param {function(Error|null, ASS_Event)} callback Function to callback when worker returns the events.
408
- */
409
- getEvents (callback) {
410
- this._fetchFromWorker({
411
- target: 'getEvents'
412
- }, (err, { events }) => {
413
- callback(err, events)
414
- })
415
- }
416
-
417
- /**
418
- * @typedef {Object} ASS_Style
419
- * @property {String} Name The name of the Style. Case sensitive. Cannot include commas.
420
- * @property {String} FontName The fontname as used by Windows. Case-sensitive.
421
- * @property {Number} FontSize Font size.
422
- * @property {Number} PrimaryColour A long integer BGR (blue-green-red) value. ie. the byte order in the hexadecimal equivelent of this number is BBGGRR
423
- * @property {Number} SecondaryColour A long integer BGR (blue-green-red) value. ie. the byte order in the hexadecimal equivelent of this number is BBGGRR
424
- * @property {Number} OutlineColour A long integer BGR (blue-green-red) value. ie. the byte order in the hexadecimal equivelent of this number is BBGGRR
425
- * @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.
426
- * @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.
427
- * @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.
428
- * @property {Number} Underline -1 or 0
429
- * @property {Number} StrikeOut -1 or 0
430
- * @property {Number} ScaleX Modifies the width of the font. [percent]
431
- * @property {Number} ScaleY Modifies the height of the font. [percent]
432
- * @property {Number} Spacing Extra space between characters. [pixels]
433
- * @property {Number} Angle The origin of the rotation is defined by the alignment. Can be a floating point number. [degrees]
434
- * @property {Number} BorderStyle 1=Outline + drop shadow, 3=Opaque box
435
- * @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.
436
- * @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.
437
- * @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
438
- * @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.
439
- * @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.
440
- * @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.
441
- * @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.
442
- * @property {Number} treat_fontname_as_pattern
443
- * @property {Number} Blur
444
- * @property {Number} Justify
445
- */
446
-
447
- /**
448
- * Create a new ASS style directly.
449
- * @param {ASS_Style} event
450
- */
451
- createStyle (style) {
452
- this.sendMessage('createStyle', { style })
453
- }
454
-
455
- /**
456
- * Overwrite the data of the style with the specified index.
457
- * @param {ASS_Style} event
458
- * @param {Number} index
459
- */
460
- setStyle (event, index) {
461
- this.sendMessage('setStyle', { event, index })
462
- }
463
-
464
- /**
465
- * Remove the style with the specified index.
466
- * @param {Number} index
467
- */
468
- removeStyle (index) {
469
- this.sendMessage('removeStyle', { index })
470
- }
471
-
472
- /**
473
- * Get all ASS styles.
474
- * @param {function(Error|null, ASS_Style)} callback Function to callback when worker returns the styles.
475
- */
476
- getStyles (callback) {
477
- this._fetchFromWorker({
478
- target: 'getStyles'
479
- }, (err, { styles }) => {
480
- callback(err, styles)
481
- })
482
- }
483
-
484
- /**
485
- * Adds a font to the renderer.
486
- * @param {String|Uint8Array} font Font to add.
487
- */
488
- addFont (font) {
489
- this.sendMessage('addFont', { font })
490
- }
491
-
492
- _sendLocalFont (name) {
493
- try {
494
- queryLocalFonts().then(fontData => {
495
- const font = fontData?.find(obj => obj.fullName.toLowerCase() === name)
496
- if (font) {
497
- font.blob().then(blob => {
498
- blob.arrayBuffer().then(buffer => {
499
- this.addFont(new Uint8Array(buffer))
500
- })
501
- })
502
- }
503
- })
504
- } catch (e) {
505
- console.warn('Local fonts API:', e)
506
- }
507
- }
508
-
509
- _getLocalFont ({ font }) {
510
- try {
511
- // electron by default has all permissions enabled, and it doesn't have perm query
512
- // if this happens, just send it
513
- if (navigator?.permissions?.query) {
514
- navigator.permissions.query({ name: 'local-fonts' }).then(permission => {
515
- if (permission.state === 'granted') {
516
- this._sendLocalFont(font)
517
- }
518
- })
519
- } else {
520
- this._sendLocalFont(font)
521
- }
522
- } catch (e) {
523
- console.warn('Local fonts API:', e)
524
- }
525
- }
526
-
527
- _unbusy () {
528
- // play catchup, leads to more frames being painted, but also more jitter
529
- if (this._lastDemandTime) {
530
- this._demandRender(this._lastDemandTime)
531
- } else {
532
- this.busy = false
533
- }
534
- }
535
-
536
- _handleRVFC (now, { mediaTime }) {
537
- if (this._destroyed) return null
538
- if (this.busy) {
539
- this._lastDemandTime = mediaTime
540
- } else {
541
- this.busy = true
542
- this._demandRender(mediaTime)
543
- }
544
- this._video.requestVideoFrameCallback(this._handleRVFC.bind(this))
545
- }
546
-
547
- _demandRender (time) {
548
- this._lastDemandTime = null
549
- this.sendMessage('demand', { time: time + this.timeOffset })
550
- }
551
-
552
- _render ({ images, async, times }) {
553
- const drawStartTime = Date.now()
554
- this._ctx.clearRect(0, 0, this._canvasctrl.width, this._canvasctrl.height)
555
- for (const image of images) {
556
- if (image.image) {
557
- if (async) {
558
- this._ctx.drawImage(image.image, image.x, image.y)
559
- image.image.close()
560
- } else {
561
- this._bufferCanvas.width = image.w
562
- this._bufferCanvas.height = image.h
563
- this._bufferCtx.putImageData(new ImageData(this._fixAlpha(new Uint8ClampedArray(image.image)), image.w, image.h), 0, 0)
564
- this._ctx.drawImage(this._bufferCanvas, image.x, image.y)
565
- }
566
- }
567
- }
568
- if (this.debug) {
569
- times.drawTime = Date.now() - drawStartTime
570
- let total = 0
571
- for (const key in times) total += times[key]
572
- console.log('Bitmaps: ' + images.length + ' Total: ' + Math.round(total) + 'ms', times)
573
- }
574
- }
575
-
576
- _fixAlpha (uint8) {
577
- if (JASSUB._hasAlphaBug) {
578
- for (let j = 3; j < uint8.length; j += 4) {
579
- uint8[j] = uint8[j] > 1 ? uint8[j] : 1
580
- }
581
- }
582
- return uint8
583
- }
584
-
585
- _ready () {
586
- this.dispatchEvent(new CustomEvent('ready'))
587
- }
588
-
589
- /**
590
- * Send data and execute function in the worker.
591
- * @param {String} target Target function.
592
- * @param {Object} [data] Data for function.
593
- * @param {Transferable[]} [transferable] Array of transferables.
594
- */
595
- sendMessage (target, data = {}, transferable) {
596
- if (transferable) {
597
- this._worker.postMessage({
598
- target,
599
- transferable,
600
- ...data
601
- }, [...transferable])
602
- } else {
603
- this._worker.postMessage({
604
- target,
605
- ...data
606
- })
607
- }
608
- }
609
-
610
- _fetchFromWorker (workerOptions, callback) {
611
- try {
612
- const target = workerOptions.target
613
-
614
- const timeout = setTimeout(() => {
615
- reject(new Error('Error: Timeout while try to fetch ' + target))
616
- }, 5000)
617
-
618
- const resolve = ({ data }) => {
619
- if (data.target === target) {
620
- callback(null, data)
621
- this._worker.removeEventListener('message', resolve)
622
- this._worker.removeEventListener('error', reject)
623
- clearTimeout(timeout)
624
- }
625
- }
626
-
627
- const reject = event => {
628
- callback(event)
629
- this._worker.removeEventListener('message', resolve)
630
- this._worker.removeEventListener('error', reject)
631
- clearTimeout(timeout)
632
- }
633
-
634
- this._worker.addEventListener('message', resolve)
635
- this._worker.addEventListener('error', reject)
636
-
637
- this._worker.postMessage(workerOptions)
638
- } catch (error) {
639
- this._error(error)
640
- }
641
- }
642
-
643
- _console ({ content, command }) {
644
- console[command].apply(console, JSON.parse(content))
645
- }
646
-
647
- _onmessage ({ data }) {
648
- if (this['_' + data.target]) this['_' + data.target](data)
649
- }
650
-
651
- _error (err) {
652
- this.dispatchEvent(err instanceof ErrorEvent ? err : new ErrorEvent('error', { cause: err instanceof Error ? err.cause : err }))
653
- if (!(err instanceof Error)) {
654
- if (err instanceof ErrorEvent) {
655
- err = err.error
656
- } else {
657
- err = new Error('error', { cause: err })
658
- }
659
- }
660
- console.error(err)
661
- }
662
-
663
- _removeListeners () {
664
- if (this._video) {
665
- if (this._ro) this._ro.unobserve(this._video)
666
- this._video.removeEventListener('timeupdate', this._boundTimeUpdate)
667
- this._video.removeEventListener('progress', this._boundTimeUpdate)
668
- this._video.removeEventListener('waiting', this._boundTimeUpdate)
669
- this._video.removeEventListener('seeking', this._boundTimeUpdate)
670
- this._video.removeEventListener('playing', this._boundTimeUpdate)
671
- this._video.removeEventListener('ratechange', this._boundSetRate)
672
- this._video.removeEventListener('resize', this._boundResize)
673
- }
674
- }
675
-
676
- /**
677
- * Destroy the object, worker, listeners and all data.
678
- * @param {String} [err] Error to throw when destroying.
679
- */
680
- destroy (err) {
681
- if (err) this._error(err)
682
- if (this._video && this._canvasParent) this._video.parentNode.removeChild(this._canvasParent)
683
- this._destroyed = true
684
- this._removeListeners()
685
- this.sendMessage('destroy')
686
- this._worker.terminate()
687
- }
688
- }