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