jassub 1.7.13 → 1.7.15

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.
Files changed (172) hide show
  1. package/dist/jassub-worker.js +6 -6
  2. package/package.json +4 -2
  3. package/dist/js/jassub-worker-modern.js +0 -128
  4. package/dist/js/jassub-worker-modern.wasm +0 -0
  5. package/dist/js/jassub-worker.js +0 -128
  6. package/dist/js/jassub-worker.wasm +0 -0
  7. package/dist/js/jassub-worker.wasm.js +0 -84
  8. package/dist/js/jassub.js +0 -832
  9. package/dist/libraries/bin/brotli.js +0 -1
  10. package/dist/libraries/include/ass/ass.h +0 -812
  11. package/dist/libraries/include/ass/ass_types.h +0 -292
  12. package/dist/libraries/include/brotli/decode.h +0 -344
  13. package/dist/libraries/include/brotli/encode.h +0 -448
  14. package/dist/libraries/include/brotli/port.h +0 -288
  15. package/dist/libraries/include/brotli/types.h +0 -83
  16. package/dist/libraries/include/expat.h +0 -1064
  17. package/dist/libraries/include/expat_config.h +0 -115
  18. package/dist/libraries/include/expat_external.h +0 -165
  19. package/dist/libraries/include/fontconfig/fcfreetype.h +0 -59
  20. package/dist/libraries/include/fontconfig/fcprivate.h +0 -134
  21. package/dist/libraries/include/fontconfig/fontconfig.h +0 -1154
  22. package/dist/libraries/include/freetype2/freetype/config/ftconfig.h +0 -63
  23. package/dist/libraries/include/freetype2/freetype/config/ftheader.h +0 -824
  24. package/dist/libraries/include/freetype2/freetype/config/ftmodule.h +0 -20
  25. package/dist/libraries/include/freetype2/freetype/config/ftoption.h +0 -1011
  26. package/dist/libraries/include/freetype2/freetype/config/ftstdlib.h +0 -175
  27. package/dist/libraries/include/freetype2/freetype/config/integer-types.h +0 -245
  28. package/dist/libraries/include/freetype2/freetype/config/mac-support.h +0 -49
  29. package/dist/libraries/include/freetype2/freetype/config/public-macros.h +0 -120
  30. package/dist/libraries/include/freetype2/freetype/freetype.h +0 -4833
  31. package/dist/libraries/include/freetype2/freetype/ftadvanc.h +0 -188
  32. package/dist/libraries/include/freetype2/freetype/ftbbox.h +0 -101
  33. package/dist/libraries/include/freetype2/freetype/ftbdf.h +0 -212
  34. package/dist/libraries/include/freetype2/freetype/ftbitmap.h +0 -329
  35. package/dist/libraries/include/freetype2/freetype/ftbzip2.h +0 -102
  36. package/dist/libraries/include/freetype2/freetype/ftcache.h +0 -1087
  37. package/dist/libraries/include/freetype2/freetype/ftchapters.h +0 -147
  38. package/dist/libraries/include/freetype2/freetype/ftcid.h +0 -167
  39. package/dist/libraries/include/freetype2/freetype/ftcolor.h +0 -1609
  40. package/dist/libraries/include/freetype2/freetype/ftdriver.h +0 -1193
  41. package/dist/libraries/include/freetype2/freetype/fterrdef.h +0 -279
  42. package/dist/libraries/include/freetype2/freetype/fterrors.h +0 -296
  43. package/dist/libraries/include/freetype2/freetype/ftfntfmt.h +0 -93
  44. package/dist/libraries/include/freetype2/freetype/ftgasp.h +0 -143
  45. package/dist/libraries/include/freetype2/freetype/ftglyph.h +0 -664
  46. package/dist/libraries/include/freetype2/freetype/ftgxval.h +0 -354
  47. package/dist/libraries/include/freetype2/freetype/ftgzip.h +0 -151
  48. package/dist/libraries/include/freetype2/freetype/ftimage.h +0 -1276
  49. package/dist/libraries/include/freetype2/freetype/ftincrem.h +0 -348
  50. package/dist/libraries/include/freetype2/freetype/ftlcdfil.h +0 -323
  51. package/dist/libraries/include/freetype2/freetype/ftlist.h +0 -296
  52. package/dist/libraries/include/freetype2/freetype/ftlogging.h +0 -184
  53. package/dist/libraries/include/freetype2/freetype/ftlzw.h +0 -100
  54. package/dist/libraries/include/freetype2/freetype/ftmac.h +0 -289
  55. package/dist/libraries/include/freetype2/freetype/ftmm.h +0 -752
  56. package/dist/libraries/include/freetype2/freetype/ftmodapi.h +0 -806
  57. package/dist/libraries/include/freetype2/freetype/ftmoderr.h +0 -204
  58. package/dist/libraries/include/freetype2/freetype/ftotval.h +0 -206
  59. package/dist/libraries/include/freetype2/freetype/ftoutln.h +0 -586
  60. package/dist/libraries/include/freetype2/freetype/ftparams.h +0 -203
  61. package/dist/libraries/include/freetype2/freetype/ftpfr.h +0 -179
  62. package/dist/libraries/include/freetype2/freetype/ftrender.h +0 -244
  63. package/dist/libraries/include/freetype2/freetype/ftsizes.h +0 -159
  64. package/dist/libraries/include/freetype2/freetype/ftsnames.h +0 -272
  65. package/dist/libraries/include/freetype2/freetype/ftstroke.h +0 -773
  66. package/dist/libraries/include/freetype2/freetype/ftsynth.h +0 -83
  67. package/dist/libraries/include/freetype2/freetype/ftsystem.h +0 -352
  68. package/dist/libraries/include/freetype2/freetype/fttrigon.h +0 -350
  69. package/dist/libraries/include/freetype2/freetype/fttypes.h +0 -615
  70. package/dist/libraries/include/freetype2/freetype/ftwinfnt.h +0 -276
  71. package/dist/libraries/include/freetype2/freetype/t1tables.h +0 -773
  72. package/dist/libraries/include/freetype2/freetype/ttnameid.h +0 -1235
  73. package/dist/libraries/include/freetype2/freetype/tttables.h +0 -855
  74. package/dist/libraries/include/freetype2/freetype/tttags.h +0 -123
  75. package/dist/libraries/include/freetype2/ft2build.h +0 -42
  76. package/dist/libraries/include/fribidi/fribidi-arabic.h +0 -81
  77. package/dist/libraries/include/fribidi/fribidi-begindecls.h +0 -3
  78. package/dist/libraries/include/fribidi/fribidi-bidi-types-list.h +0 -96
  79. package/dist/libraries/include/fribidi/fribidi-bidi-types.h +0 -405
  80. package/dist/libraries/include/fribidi/fribidi-bidi.h +0 -142
  81. package/dist/libraries/include/fribidi/fribidi-brackets.h +0 -89
  82. package/dist/libraries/include/fribidi/fribidi-char-sets-list.h +0 -54
  83. package/dist/libraries/include/fribidi/fribidi-char-sets.h +0 -106
  84. package/dist/libraries/include/fribidi/fribidi-common.h +0 -158
  85. package/dist/libraries/include/fribidi/fribidi-config.h +0 -23
  86. package/dist/libraries/include/fribidi/fribidi-deprecated.h +0 -175
  87. package/dist/libraries/include/fribidi/fribidi-enddecls.h +0 -3
  88. package/dist/libraries/include/fribidi/fribidi-flags.h +0 -72
  89. package/dist/libraries/include/fribidi/fribidi-joining-types-list.h +0 -44
  90. package/dist/libraries/include/fribidi/fribidi-joining-types.h +0 -249
  91. package/dist/libraries/include/fribidi/fribidi-joining.h +0 -74
  92. package/dist/libraries/include/fribidi/fribidi-mirroring.h +0 -86
  93. package/dist/libraries/include/fribidi/fribidi-shape.h +0 -71
  94. package/dist/libraries/include/fribidi/fribidi-types.h +0 -79
  95. package/dist/libraries/include/fribidi/fribidi-unicode-version.h +0 -10
  96. package/dist/libraries/include/fribidi/fribidi-unicode.h +0 -105
  97. package/dist/libraries/include/fribidi/fribidi.h +0 -129
  98. package/dist/libraries/include/harfbuzz/hb-aat-layout.h +0 -795
  99. package/dist/libraries/include/harfbuzz/hb-aat.h +0 -38
  100. package/dist/libraries/include/harfbuzz/hb-blob.h +0 -160
  101. package/dist/libraries/include/harfbuzz/hb-buffer.h +0 -799
  102. package/dist/libraries/include/harfbuzz/hb-common.h +0 -902
  103. package/dist/libraries/include/harfbuzz/hb-cplusplus.hh +0 -221
  104. package/dist/libraries/include/harfbuzz/hb-deprecated.h +0 -251
  105. package/dist/libraries/include/harfbuzz/hb-draw.h +0 -325
  106. package/dist/libraries/include/harfbuzz/hb-face.h +0 -181
  107. package/dist/libraries/include/harfbuzz/hb-font.h +0 -1108
  108. package/dist/libraries/include/harfbuzz/hb-ft.h +0 -145
  109. package/dist/libraries/include/harfbuzz/hb-map.h +0 -124
  110. package/dist/libraries/include/harfbuzz/hb-ot-color.h +0 -146
  111. package/dist/libraries/include/harfbuzz/hb-ot-deprecated.h +0 -141
  112. package/dist/libraries/include/harfbuzz/hb-ot-font.h +0 -45
  113. package/dist/libraries/include/harfbuzz/hb-ot-layout.h +0 -503
  114. package/dist/libraries/include/harfbuzz/hb-ot-math.h +0 -333
  115. package/dist/libraries/include/harfbuzz/hb-ot-meta.h +0 -72
  116. package/dist/libraries/include/harfbuzz/hb-ot-metrics.h +0 -129
  117. package/dist/libraries/include/harfbuzz/hb-ot-name.h +0 -158
  118. package/dist/libraries/include/harfbuzz/hb-ot-shape.h +0 -53
  119. package/dist/libraries/include/harfbuzz/hb-ot-var.h +0 -191
  120. package/dist/libraries/include/harfbuzz/hb-ot.h +0 -49
  121. package/dist/libraries/include/harfbuzz/hb-set.h +0 -200
  122. package/dist/libraries/include/harfbuzz/hb-shape-plan.h +0 -122
  123. package/dist/libraries/include/harfbuzz/hb-shape.h +0 -62
  124. package/dist/libraries/include/harfbuzz/hb-style.h +0 -81
  125. package/dist/libraries/include/harfbuzz/hb-subset-repacker.h +0 -81
  126. package/dist/libraries/include/harfbuzz/hb-subset.h +0 -234
  127. package/dist/libraries/include/harfbuzz/hb-unicode.h +0 -643
  128. package/dist/libraries/include/harfbuzz/hb-version.h +0 -95
  129. package/dist/libraries/include/harfbuzz/hb.h +0 -50
  130. package/dist/libraries/lib/cmake/expat-2.4.7/expat-config-version.cmake +0 -70
  131. package/dist/libraries/lib/cmake/expat-2.4.7/expat-config.cmake +0 -99
  132. package/dist/libraries/lib/cmake/expat-2.4.7/expat-noconfig.cmake +0 -19
  133. package/dist/libraries/lib/cmake/expat-2.4.7/expat.cmake +0 -99
  134. package/dist/libraries/lib/libass.a +0 -0
  135. package/dist/libraries/lib/libass.la +0 -41
  136. package/dist/libraries/lib/libbrotlicommon.a +0 -0
  137. package/dist/libraries/lib/libbrotlidec.a +0 -0
  138. package/dist/libraries/lib/libbrotlienc.a +0 -0
  139. package/dist/libraries/lib/libexpat.a +0 -0
  140. package/dist/libraries/lib/libfontconfig.a +0 -0
  141. package/dist/libraries/lib/libfontconfig.la +0 -41
  142. package/dist/libraries/lib/libfreetype.a +0 -0
  143. package/dist/libraries/lib/libfreetype.la +0 -41
  144. package/dist/libraries/lib/libfribidi.a +0 -0
  145. package/dist/libraries/lib/libfribidi.la +0 -41
  146. package/dist/libraries/lib/libharfbuzz-subset.a +0 -0
  147. package/dist/libraries/lib/libharfbuzz-subset.la +0 -41
  148. package/dist/libraries/lib/libharfbuzz.a +0 -0
  149. package/dist/libraries/lib/libharfbuzz.la +0 -41
  150. package/dist/libraries/lib/pkgconfig/expat.pc +0 -11
  151. package/dist/libraries/lib/pkgconfig/fontconfig.pc +0 -18
  152. package/dist/libraries/lib/pkgconfig/freetype2.pc +0 -14
  153. package/dist/libraries/lib/pkgconfig/fribidi.pc +0 -13
  154. package/dist/libraries/lib/pkgconfig/harfbuzz-subset.pc +0 -12
  155. package/dist/libraries/lib/pkgconfig/harfbuzz.pc +0 -13
  156. package/dist/libraries/lib/pkgconfig/libass.pc +0 -13
  157. package/dist/libraries/lib/pkgconfig/libbrotlicommon.pc +0 -11
  158. package/dist/libraries/lib/pkgconfig/libbrotlidec.pc +0 -12
  159. package/dist/libraries/lib/pkgconfig/libbrotlienc.pc +0 -12
  160. package/dist/libraries/share/aclocal/freetype2.m4 +0 -194
  161. package/dist/libraries/share/doc/expat/AUTHORS +0 -10
  162. package/dist/libraries/share/doc/expat/changelog +0 -1161
  163. package/dist/license/all +0 -951
  164. package/dist/license/all.tmp +0 -307
  165. package/dist/license/brotli +0 -12
  166. package/dist/license/expat +0 -71
  167. package/dist/license/fontconfig +0 -46
  168. package/dist/license/freetype +0 -92
  169. package/dist/license/fribidi +0 -15
  170. package/dist/license/harfbuzz +0 -32
  171. package/dist/license/jassub +0 -0
  172. package/dist/license/libass +0 -28
package/dist/js/jassub.js DELETED
@@ -1,832 +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 async _test () {
171
- // check if ran previously
172
- if (JASSUB._hasBitmapBug !== null) return null
173
-
174
- try {
175
- 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))
176
- } catch (e) {
177
- JASSUB._supportsSIMD = false
178
- }
179
-
180
- const canvas1 = document.createElement('canvas')
181
- const ctx1 = canvas1.getContext('2d', { willReadFrequently: true })
182
- if (!ctx1) throw new Error('Canvas rendering not supported')
183
- // test ImageData constructor
184
- if (typeof ImageData.prototype.constructor === 'function') {
185
- try {
186
- // try actually calling ImageData, as on some browsers it's reported
187
- // as existing but calling it errors out as "TypeError: Illegal constructor"
188
- // eslint-disable-next-line no-new
189
- new ImageData(new Uint8ClampedArray([0, 0, 0, 0]), 1, 1)
190
- } catch (e) {
191
- console.log('Detected that ImageData is not constructable despite browser saying so')
192
-
193
- // @ts-ignore
194
- self.ImageData = function (data, width, height) {
195
- const imageData = ctx1.createImageData(width, height)
196
- if (data) imageData.data.set(data)
197
- return imageData
198
- }
199
- }
200
- }
201
-
202
- // Test for alpha bug, where e.g. WebKit can render a transparent pixel
203
- // (with alpha == 0) as non-black which then leads to visual artifacts.
204
- const canvas2 = document.createElement('canvas')
205
- const ctx2 = canvas2.getContext('2d', { willReadFrequently: true })
206
- if (!ctx2) throw new Error('Canvas rendering not supported')
207
-
208
- canvas1.width = canvas2.width = 1
209
- canvas1.height = canvas2.height = 1
210
- ctx1.clearRect(0, 0, 1, 1)
211
- ctx2.clearRect(0, 0, 1, 1)
212
- const prePut = ctx2.getImageData(0, 0, 1, 1).data
213
- ctx1.putImageData(new ImageData(new Uint8ClampedArray([0, 255, 0, 0]), 1, 1), 0, 0)
214
- ctx2.drawImage(canvas1, 0, 0)
215
- const postPut = ctx2.getImageData(0, 0, 1, 1).data
216
- JASSUB._hasAlphaBug = prePut[1] !== postPut[1]
217
- if (JASSUB._hasAlphaBug) console.log('Detected a browser having issue with transparent pixels, applying workaround')
218
-
219
- if (typeof createImageBitmap !== 'undefined') {
220
- const subarray = new Uint8ClampedArray([255, 0, 255, 0, 255]).subarray(1, 5)
221
- ctx2.drawImage(await createImageBitmap(new ImageData(subarray, 1)), 0, 0)
222
- const { data } = ctx2.getImageData(0, 0, 1, 1)
223
- JASSUB._hasBitmapBug = false
224
- for (const [i, number] of data.entries()) {
225
- // realistically at most this will be a diff of 4, but just to be safe
226
- if (Math.abs(subarray[i] - number) > 15) {
227
- JASSUB._hasBitmapBug = true
228
- console.log('Detected a browser having issue with partial bitmaps, applying workaround')
229
- break
230
- }
231
- }
232
- } else {
233
- JASSUB._hasBitmapBug = false
234
- }
235
-
236
- canvas1.remove()
237
- canvas2.remove()
238
- }
239
-
240
- /**
241
- * Resize the canvas to given parameters. Auto-generated if values are ommited.
242
- * @param {Number} [width=0]
243
- * @param {Number} [height=0]
244
- * @param {Number} [top=0]
245
- * @param {Number} [left=0]
246
- * @param {Boolean} [force=false]
247
- */
248
- resize (width = 0, height = 0, top = 0, left = 0, force = this._video?.paused) {
249
- if ((!width || !height) && this._video) {
250
- const videoSize = this._getVideoPosition()
251
- let renderSize = null
252
- // support anamorphic video
253
- if (this._videoWidth) {
254
- const widthRatio = this._video.videoWidth / this._videoWidth
255
- const heightRatio = this._video.videoHeight / this._videoHeight
256
- renderSize = this._computeCanvasSize((videoSize.width || 0) / widthRatio, (videoSize.height || 0) / heightRatio)
257
- } else {
258
- renderSize = this._computeCanvasSize(videoSize.width || 0, videoSize.height || 0)
259
- }
260
- width = renderSize.width
261
- height = renderSize.height
262
- if (this._canvasParent) {
263
- top = videoSize.y - (this._canvasParent.getBoundingClientRect().top - this._video.getBoundingClientRect().top)
264
- left = videoSize.x
265
- }
266
- this._canvas.style.width = videoSize.width + 'px'
267
- this._canvas.style.height = videoSize.height + 'px'
268
- }
269
-
270
- this._canvas.style.top = top + 'px'
271
- this._canvas.style.left = left + 'px'
272
- if (force && this.busy === false) {
273
- this.busy = true
274
- } else {
275
- force = false
276
- }
277
- this.sendMessage('canvas', { width, height, force })
278
- }
279
-
280
- _getVideoPosition (width = this._video.videoWidth, height = this._video.videoHeight) {
281
- const videoRatio = width / height
282
- const { offsetWidth, offsetHeight } = this._video
283
- const elementRatio = offsetWidth / offsetHeight
284
- width = offsetWidth
285
- height = offsetHeight
286
- if (elementRatio > videoRatio) {
287
- width = Math.floor(offsetHeight * videoRatio)
288
- } else {
289
- height = Math.floor(offsetWidth / videoRatio)
290
- }
291
-
292
- const x = (offsetWidth - width) / 2
293
- const y = (offsetHeight - height) / 2
294
-
295
- return { width, height, x, y }
296
- }
297
-
298
- _computeCanvasSize (width = 0, height = 0) {
299
- const scalefactor = this.prescaleFactor <= 0 ? 1.0 : this.prescaleFactor
300
- const ratio = self.devicePixelRatio || 1
301
-
302
- width = width * ratio
303
- height = height * ratio
304
- if (height <= 0 || width <= 0) {
305
- width = 0
306
- height = 0
307
- } else {
308
- const sgn = scalefactor < 1 ? -1 : 1
309
- let newH = height * ratio
310
- if (sgn * newH * scalefactor <= sgn * this.prescaleHeightLimit) {
311
- newH *= scalefactor
312
- } else if (sgn * newH < sgn * this.prescaleHeightLimit) {
313
- newH = this.prescaleHeightLimit
314
- }
315
-
316
- if (this.maxRenderHeight > 0 && newH > this.maxRenderHeight) newH = this.maxRenderHeight
317
-
318
- width *= newH / height
319
- height = newH
320
- }
321
-
322
- return { width, height }
323
- }
324
-
325
- _timeupdate ({ type }) {
326
- const eventmap = {
327
- seeking: true,
328
- waiting: true,
329
- playing: false
330
- }
331
- const playing = eventmap[type]
332
- if (playing != null) this._playstate = playing
333
- this.setCurrentTime(this._video.paused || this._playstate, this._video.currentTime + this.timeOffset)
334
- }
335
-
336
- /**
337
- * Change the video to use as target for event listeners.
338
- * @param {HTMLVideoElement} video
339
- */
340
- setVideo (video) {
341
- if (video instanceof HTMLVideoElement) {
342
- this._removeListeners()
343
- this._video = video
344
- if (this._onDemandRender) {
345
- this._video.requestVideoFrameCallback(this._handleRVFC.bind(this))
346
- } else {
347
- this._playstate = video.paused
348
-
349
- video.addEventListener('timeupdate', this._boundTimeUpdate, false)
350
- video.addEventListener('progress', this._boundTimeUpdate, false)
351
- video.addEventListener('waiting', this._boundTimeUpdate, false)
352
- video.addEventListener('seeking', this._boundTimeUpdate, false)
353
- video.addEventListener('playing', this._boundTimeUpdate, false)
354
- video.addEventListener('ratechange', this._boundSetRate, false)
355
- video.addEventListener('resize', this._boundResize, false)
356
- }
357
- // everything else is unreliable for this, loadedmetadata and loadeddata included.
358
- if ('VideoFrame' in window) {
359
- video.addEventListener('loadedmetadata', this._boundUpdateColorSpace, false)
360
- if (video.readyState > 2) this._updateColorSpace()
361
- }
362
- if (video.videoWidth > 0) this.resize()
363
- // Support Element Resize Observer
364
- if (typeof ResizeObserver !== 'undefined') {
365
- if (!this._ro) this._ro = new ResizeObserver(() => this.resize())
366
- this._ro.observe(video)
367
- }
368
- } else {
369
- this._error('Video element invalid!')
370
- }
371
- }
372
-
373
- runBenchmark () {
374
- this.sendMessage('runBenchmark')
375
- }
376
-
377
- /**
378
- * Overwrites the current subtitle content.
379
- * @param {String} url URL to load subtitles from.
380
- */
381
- setTrackByUrl (url) {
382
- this.sendMessage('setTrackByUrl', { url })
383
- this._reAttachOffscreen()
384
- if (this._ctx) this._ctx.filter = 'none'
385
- }
386
-
387
- /**
388
- * Overwrites the current subtitle content.
389
- * @param {String} content Content of the ASS file.
390
- */
391
- setTrack (content) {
392
- this.sendMessage('setTrack', { content })
393
- this._reAttachOffscreen()
394
- if (this._ctx) this._ctx.filter = 'none'
395
- }
396
-
397
- /**
398
- * Free currently used subtitle track.
399
- */
400
- freeTrack () {
401
- this.sendMessage('freeTrack')
402
- }
403
-
404
- /**
405
- * Sets the playback state of the media.
406
- * @param {Boolean} isPaused Pause/Play subtitle playback.
407
- */
408
- setIsPaused (isPaused) {
409
- this.sendMessage('video', { isPaused })
410
- }
411
-
412
- /**
413
- * Sets the playback rate of the media [speed multiplier].
414
- * @param {Number} rate Playback rate.
415
- */
416
- setRate (rate) {
417
- this.sendMessage('video', { rate })
418
- }
419
-
420
- /**
421
- * Sets the current time, playback state and rate of the subtitles.
422
- * @param {Boolean} [isPaused] Pause/Play subtitle playback.
423
- * @param {Number} [currentTime] Time in seconds.
424
- * @param {Number} [rate] Playback rate.
425
- */
426
- setCurrentTime (isPaused, currentTime, rate) {
427
- this.sendMessage('video', { isPaused, currentTime, rate, colorSpace: this._videoColorSpace })
428
- }
429
-
430
- /**
431
- * @typedef {Object} ASS_Event
432
- * @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!
433
- * @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!
434
- * @property {String} Style Style name. If it is "Default", then your own *Default style will be subtituted.
435
- * @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.
436
- * @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.
437
- * @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.
438
- * @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.
439
- * @property {String} Effect Transition Effect. This is either empty, or contains information for one of the three transition effects implemented in SSA v4.x
440
- * @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.
441
- * @property {Number} ReadOrder Number in order of which to read this event.
442
- * @property {Number} Layer Z-index overlap in which to render this event.
443
- * @property {Number} _index (Internal) index of the event.
444
- */
445
-
446
- /**
447
- * Create a new ASS event directly.
448
- * @param {ASS_Event} event
449
- */
450
- createEvent (event) {
451
- this.sendMessage('createEvent', { event })
452
- }
453
-
454
- /**
455
- * Overwrite the data of the event with the specified index.
456
- * @param {ASS_Event} event
457
- * @param {Number} index
458
- */
459
- setEvent (event, index) {
460
- this.sendMessage('setEvent', { event, index })
461
- }
462
-
463
- /**
464
- * Remove the event with the specified index.
465
- * @param {Number} index
466
- */
467
- removeEvent (index) {
468
- this.sendMessage('removeEvent', { index })
469
- }
470
-
471
- /**
472
- * Get all ASS events.
473
- * @param {function(Error|null, ASS_Event): void} callback Function to callback when worker returns the events.
474
- */
475
- getEvents (callback) {
476
- this._fetchFromWorker({
477
- target: 'getEvents'
478
- }, (err, { events }) => {
479
- callback(err, events)
480
- })
481
- }
482
-
483
- /**
484
- * @typedef {Object} ASS_Style
485
- * @property {String} Name The name of the Style. Case sensitive. Cannot include commas.
486
- * @property {String} FontName The fontname as used by Windows. Case-sensitive.
487
- * @property {Number} FontSize Font size.
488
- * @property {Number} PrimaryColour A long integer BGR (blue-green-red) value. ie. the byte order in the hexadecimal equivelent of this number is BBGGRR
489
- * @property {Number} SecondaryColour A long integer BGR (blue-green-red) value. ie. the byte order in the hexadecimal equivelent of this number is BBGGRR
490
- * @property {Number} OutlineColour A long integer BGR (blue-green-red) value. ie. the byte order in the hexadecimal equivelent of this number is BBGGRR
491
- * @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.
492
- * @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.
493
- * @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.
494
- * @property {Number} Underline -1 or 0
495
- * @property {Number} StrikeOut -1 or 0
496
- * @property {Number} ScaleX Modifies the width of the font. [percent]
497
- * @property {Number} ScaleY Modifies the height of the font. [percent]
498
- * @property {Number} Spacing Extra space between characters. [pixels]
499
- * @property {Number} Angle The origin of the rotation is defined by the alignment. Can be a floating point number. [degrees]
500
- * @property {Number} BorderStyle 1=Outline + drop shadow, 3=Opaque box
501
- * @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.
502
- * @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.
503
- * @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
504
- * @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.
505
- * @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.
506
- * @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.
507
- * @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.
508
- * @property {Number} treat_fontname_as_pattern
509
- * @property {Number} Blur
510
- * @property {Number} Justify
511
- */
512
-
513
- /**
514
- * Create a new ASS style directly.
515
- * @param {ASS_Style} style
516
- */
517
- createStyle (style) {
518
- this.sendMessage('createStyle', { style })
519
- }
520
-
521
- /**
522
- * Overwrite the data of the style with the specified index.
523
- * @param {ASS_Style} style
524
- * @param {Number} index
525
- */
526
- setStyle (style, index) {
527
- this.sendMessage('setStyle', { style, index })
528
- }
529
-
530
- /**
531
- * Remove the style with the specified index.
532
- * @param {Number} index
533
- */
534
- removeStyle (index) {
535
- this.sendMessage('removeStyle', { index })
536
- }
537
-
538
- /**
539
- * Get all ASS styles.
540
- * @param {function(Error|null, ASS_Style): void} callback Function to callback when worker returns the styles.
541
- */
542
- getStyles (callback) {
543
- this._fetchFromWorker({
544
- target: 'getStyles'
545
- }, (err, { styles }) => {
546
- callback(err, styles)
547
- })
548
- }
549
-
550
- /**
551
- * Adds a font to the renderer.
552
- * @param {String|Uint8Array} font Font to add.
553
- */
554
- addFont (font) {
555
- this.sendMessage('addFont', { font })
556
- }
557
-
558
- _sendLocalFont (name) {
559
- try {
560
- // @ts-ignore
561
- queryLocalFonts().then(fontData => {
562
- const font = fontData?.find(obj => obj.fullName.toLowerCase() === name)
563
- if (font) {
564
- font.blob().then(blob => {
565
- blob.arrayBuffer().then(buffer => {
566
- this.addFont(new Uint8Array(buffer))
567
- })
568
- })
569
- }
570
- })
571
- } catch (e) {
572
- console.warn('Local fonts API:', e)
573
- }
574
- }
575
-
576
- _getLocalFont ({ font }) {
577
- try {
578
- // electron by default has all permissions enabled, and it doesn't have perm query
579
- // if this happens, just send it
580
- if (navigator?.permissions?.query) {
581
- // @ts-ignore
582
- navigator.permissions.query({ name: 'local-fonts' }).then(permission => {
583
- if (permission.state === 'granted') {
584
- this._sendLocalFont(font)
585
- }
586
- })
587
- } else {
588
- this._sendLocalFont(font)
589
- }
590
- } catch (e) {
591
- console.warn('Local fonts API:', e)
592
- }
593
- }
594
-
595
- _unbusy () {
596
- // play catchup, leads to more frames being painted, but also more jitter
597
- if (this._lastDemandTime) {
598
- this._demandRender(this._lastDemandTime)
599
- } else {
600
- this.busy = false
601
- }
602
- }
603
-
604
- _handleRVFC (now, { mediaTime, width, height }) {
605
- if (this._destroyed) return null
606
- if (this.busy) {
607
- this._lastDemandTime = { mediaTime, width, height }
608
- } else {
609
- this.busy = true
610
- this._demandRender({ mediaTime, width, height })
611
- }
612
- this._video.requestVideoFrameCallback(this._handleRVFC.bind(this))
613
- }
614
-
615
- _demandRender ({ mediaTime, width, height }) {
616
- this._lastDemandTime = null
617
- if (width !== this._videoWidth || height !== this._videoHeight) {
618
- this._videoWidth = width
619
- this._videoHeight = height
620
- this.resize()
621
- }
622
- this.sendMessage('demand', { time: mediaTime + this.timeOffset })
623
- }
624
-
625
- // if we're using offscreen render, we can't use ctx filters, so we can't use a transfered canvas
626
- _detachOffscreen () {
627
- if (!this._offscreenRender || this._ctx) return null
628
- this._canvas.remove()
629
- this._createCanvas()
630
- this._canvasctrl = this._canvas
631
- this._ctx = this._canvasctrl.getContext('2d')
632
- this.sendMessage('detachOffscreen')
633
- // force a render after resize
634
- this.busy = false
635
- this.resize(0, 0, 0, 0, true)
636
- }
637
-
638
- // if the video or track changed, we need to re-attach the offscreen canvas
639
- _reAttachOffscreen () {
640
- if (!this._offscreenRender || !this._ctx) return null
641
- this._canvas.remove()
642
- this._createCanvas()
643
- this._canvasctrl = this._canvas.transferControlToOffscreen()
644
- this._ctx = false
645
- this.sendMessage('offscreenCanvas', null, [this._canvasctrl])
646
- this.resize(0, 0, 0, 0, true)
647
- }
648
-
649
- _updateColorSpace () {
650
- this._video.requestVideoFrameCallback(() => {
651
- try {
652
- // eslint-disable-next-line no-undef
653
- const frame = new VideoFrame(this._video)
654
- this._videoColorSpace = webYCbCrMap[frame.colorSpace.matrix]
655
- frame.close()
656
- this.sendMessage('getColorSpace')
657
- } catch (e) {
658
- // sources can be tainted
659
- console.warn(e)
660
- }
661
- })
662
- }
663
-
664
- /**
665
- * Veryify the color spaces for subtitles and videos, then apply filters to correct the color of subtitles.
666
- * @param {Object} options
667
- * @param {String} options.subtitleColorSpace Subtitle color space. One of: BT601 BT709 SMPTE240M FCC
668
- * @param {String=} options.videoColorSpace Video color space. One of: BT601 BT709
669
- */
670
- _verifyColorSpace ({ subtitleColorSpace, videoColorSpace = this._videoColorSpace }) {
671
- if (!subtitleColorSpace || !videoColorSpace) return
672
- if (subtitleColorSpace === videoColorSpace) return
673
- this._detachOffscreen()
674
- 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")`
675
- }
676
-
677
- _render ({ images, asyncRender, times, width, height, colorSpace }) {
678
- this._unbusy()
679
- if (this.debug) times.IPCTime = Date.now() - times.JSRenderTime
680
- if (this._canvasctrl.width !== width || this._canvasctrl.height !== height) {
681
- this._canvasctrl.width = width
682
- this._canvasctrl.height = height
683
- this._verifyColorSpace({ subtitleColorSpace: colorSpace })
684
- }
685
- this._ctx.clearRect(0, 0, this._canvasctrl.width, this._canvasctrl.height)
686
- for (const image of images) {
687
- if (image.image) {
688
- if (asyncRender) {
689
- this._ctx.drawImage(image.image, image.x, image.y)
690
- image.image.close()
691
- } else {
692
- this._bufferCanvas.width = image.w
693
- this._bufferCanvas.height = image.h
694
- this._bufferCtx.putImageData(new ImageData(this._fixAlpha(new Uint8ClampedArray(image.image)), image.w, image.h), 0, 0)
695
- this._ctx.drawImage(this._bufferCanvas, image.x, image.y)
696
- }
697
- }
698
- }
699
- if (this.debug) {
700
- times.JSRenderTime = Date.now() - times.JSRenderTime - times.IPCTime
701
- let total = 0
702
- const count = times.bitmaps || images.length
703
- delete times.bitmaps
704
- for (const key in times) total += times[key]
705
- console.log('Bitmaps: ' + count + ' Total: ' + (total | 0) + 'ms', times)
706
- }
707
- }
708
-
709
- _fixAlpha (uint8) {
710
- if (JASSUB._hasAlphaBug) {
711
- for (let j = 3; j < uint8.length; j += 4) {
712
- uint8[j] = uint8[j] > 1 ? uint8[j] : 1
713
- }
714
- }
715
- return uint8
716
- }
717
-
718
- _ready () {
719
- this._init()
720
- this.dispatchEvent(new CustomEvent('ready'))
721
- }
722
-
723
- /**
724
- * Send data and execute function in the worker.
725
- * @param {String} target Target function.
726
- * @param {Object} [data] Data for function.
727
- * @param {Transferable[]} [transferable] Array of transferables.
728
- */
729
- async sendMessage (target, data = {}, transferable) {
730
- await this._loaded
731
- if (transferable) {
732
- this._worker.postMessage({
733
- target,
734
- transferable,
735
- ...data
736
- }, [...transferable])
737
- } else {
738
- this._worker.postMessage({
739
- target,
740
- ...data
741
- })
742
- }
743
- }
744
-
745
- _fetchFromWorker (workerOptions, callback) {
746
- try {
747
- const target = workerOptions.target
748
-
749
- const timeout = setTimeout(() => {
750
- reject(new Error('Error: Timeout while try to fetch ' + target))
751
- }, 5000)
752
-
753
- const resolve = ({ data }) => {
754
- if (data.target === target) {
755
- callback(null, data)
756
- this._worker.removeEventListener('message', resolve)
757
- this._worker.removeEventListener('error', reject)
758
- clearTimeout(timeout)
759
- }
760
- }
761
-
762
- const reject = event => {
763
- callback(event)
764
- this._worker.removeEventListener('message', resolve)
765
- this._worker.removeEventListener('error', reject)
766
- clearTimeout(timeout)
767
- }
768
-
769
- this._worker.addEventListener('message', resolve)
770
- this._worker.addEventListener('error', reject)
771
-
772
- this._worker.postMessage(workerOptions)
773
- } catch (error) {
774
- this._error(error)
775
- }
776
- }
777
-
778
- _console ({ content, command }) {
779
- console[command].apply(console, JSON.parse(content))
780
- }
781
-
782
- _onmessage ({ data }) {
783
- if (this['_' + data.target]) this['_' + data.target](data)
784
- }
785
-
786
- _error (err) {
787
- const error = err instanceof Error
788
- ? err // pass
789
- : err instanceof ErrorEvent
790
- ? err.error // ErrorEvent has error property which is an Error object
791
- : new Error(err) // construct Error
792
-
793
- const event = err instanceof Event
794
- ? new ErrorEvent(err.type, err) // clone event
795
- : new ErrorEvent('error', { error }) // construct Event
796
-
797
- this.dispatchEvent(event)
798
-
799
- console.error(error)
800
-
801
- return error
802
- }
803
-
804
- _removeListeners () {
805
- if (this._video) {
806
- if (this._ro) this._ro.unobserve(this._video)
807
- if (this._ctx) this._ctx.filter = 'none'
808
- this._video.removeEventListener('timeupdate', this._boundTimeUpdate)
809
- this._video.removeEventListener('progress', this._boundTimeUpdate)
810
- this._video.removeEventListener('waiting', this._boundTimeUpdate)
811
- this._video.removeEventListener('seeking', this._boundTimeUpdate)
812
- this._video.removeEventListener('playing', this._boundTimeUpdate)
813
- this._video.removeEventListener('ratechange', this._boundSetRate)
814
- this._video.removeEventListener('resize', this._boundResize)
815
- this._video.removeEventListener('loadedmetadata', this._boundUpdateColorSpace)
816
- }
817
- }
818
-
819
- /**
820
- * Destroy the object, worker, listeners and all data.
821
- * @param {String|Error} [err] Error to throw when destroying.
822
- */
823
- destroy (err) {
824
- if (err) err = this._error(err)
825
- if (this._video && this._canvasParent) this._video.parentNode?.removeChild(this._canvasParent)
826
- this._destroyed = true
827
- this._removeListeners()
828
- this.sendMessage('destroy')
829
- this._worker?.terminate()
830
- return err
831
- }
832
- }