@kmamal/sdl 1.0.0-5 → 1.0.0-9

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 (90) hide show
  1. package/CHANGELOG.md +12 -6
  2. package/README.md +2 -2
  3. package/binding.gyp +21 -4
  4. package/package.json +5 -12
  5. package/scripts/build.mjs +3 -1
  6. package/scripts/install.mjs +2 -0
  7. package/scripts/util/common.js +3 -2
  8. package/src/javascript/audio/audio-playback-stream.js +9 -10
  9. package/src/javascript/audio/audio-recording-stream.js +9 -8
  10. package/src/javascript/audio/audio-stream.js +101 -44
  11. package/src/javascript/audio/conversion.js +41 -0
  12. package/src/javascript/audio/devices.js +11 -0
  13. package/src/javascript/audio/events.js +65 -0
  14. package/src/javascript/audio/format-helpers.js +8 -4
  15. package/src/javascript/audio/index.js +25 -20
  16. package/src/javascript/audio/prevent-exit.js +13 -10
  17. package/src/javascript/audio/validate.js +9 -0
  18. package/src/javascript/cleanup.js +9 -6
  19. package/src/javascript/clipboard/index.js +8 -3
  20. package/src/javascript/device-instance.js +61 -0
  21. package/src/javascript/events/events-via-poll.js +32 -28
  22. package/src/javascript/events/index.js +85 -479
  23. package/src/javascript/events/try.js +25 -0
  24. package/src/javascript/gamepad/{device.js → devices.js} +4 -5
  25. package/src/javascript/gamepad/events.js +66 -0
  26. package/src/javascript/gamepad/gamepad-instance.js +12 -160
  27. package/src/javascript/gamepad/index.js +15 -16
  28. package/src/javascript/globals.js +10 -1
  29. package/src/javascript/index.js +2 -5
  30. package/src/javascript/joystick/devices.js +43 -0
  31. package/src/javascript/joystick/events.js +129 -0
  32. package/src/javascript/joystick/index.js +9 -18
  33. package/src/javascript/joystick/joystick-device-instance.js +176 -0
  34. package/src/javascript/joystick/joystick-instance.js +12 -158
  35. package/src/javascript/keyboard/index.js +20 -10
  36. package/src/javascript/keyboard/key-mapping.js +46 -27
  37. package/src/javascript/mouse/index.js +36 -29
  38. package/src/javascript/sensor/events.js +21 -0
  39. package/src/javascript/sensor/index.js +13 -2
  40. package/src/javascript/sensor/sensor-instance.js +7 -47
  41. package/src/javascript/subsystems.js +56 -0
  42. package/src/javascript/touch/index.js +9 -4
  43. package/src/javascript/validate.js +119 -0
  44. package/src/javascript/video/conversion.js +63 -0
  45. package/src/javascript/video/events.js +179 -0
  46. package/src/javascript/video/format-helpers.js +10 -8
  47. package/src/javascript/video/index.js +28 -14
  48. package/src/javascript/video/validate.js +45 -0
  49. package/src/javascript/video/window.js +196 -167
  50. package/src/native/audio.cpp +457 -153
  51. package/src/native/audio.h +25 -19
  52. package/src/native/clipboard.cpp +8 -37
  53. package/src/native/clipboard.h +2 -2
  54. package/src/native/enums.cpp +16 -1
  55. package/src/native/enums.h +1 -1
  56. package/src/native/events.cpp +351 -357
  57. package/src/native/events.h +70 -68
  58. package/src/native/gamepad.cpp +147 -103
  59. package/src/native/gamepad.h +10 -11
  60. package/src/native/global.cpp +183 -340
  61. package/src/native/global.h +51 -5
  62. package/src/native/joystick.cpp +204 -275
  63. package/src/native/joystick.h +21 -15
  64. package/src/native/keyboard.cpp +63 -25
  65. package/src/native/keyboard.h +5 -4
  66. package/src/native/module.cpp +23 -3
  67. package/src/native/mouse.cpp +28 -59
  68. package/src/native/mouse.h +9 -9
  69. package/src/native/packed.cpp +99 -0
  70. package/src/native/packed.h +86 -0
  71. package/src/native/power.cpp +13 -1
  72. package/src/native/power.h +3 -3
  73. package/src/native/sensor.cpp +78 -69
  74. package/src/native/sensor.h +7 -7
  75. package/src/native/testing.cpp +148 -0
  76. package/src/native/testing.h +17 -0
  77. package/src/native/threads.cpp +301 -0
  78. package/src/native/threads.h +36 -0
  79. package/src/native/touch.cpp +38 -44
  80. package/src/native/touch.h +3 -2
  81. package/src/native/video.cpp +211 -98
  82. package/src/native/video.h +7 -4
  83. package/src/native/window.cpp +201 -219
  84. package/src/native/window.h +24 -20
  85. package/src/types/index.d.ts +157 -70
  86. package/src/javascript/audio/device.js +0 -37
  87. package/src/javascript/joystick/device.js +0 -13
  88. package/src/javascript/joystick/shared.js +0 -90
  89. package/src/javascript/worker.js +0 -88
  90. package/src/types/worker.d.ts +0 -71
@@ -1,4 +1,5 @@
1
1
  const Os = require('node:os')
2
+ const { validateString } = require('../validate')
2
3
 
3
4
  const signedLimits = (bits) => ({
4
5
  bytesPerSample: bits / 8,
@@ -79,11 +80,14 @@ else {
79
80
  AudioFormatHelpers.f32 = AudioFormatHelpers.f32be
80
81
  }
81
82
 
82
- const getFormatHelpers = (format) => {
83
- if (typeof format !== 'string') { throw Object.assign(new Error("format must be a string"), { format }) }
83
+ const getFormatHelpers = (format, name = 'format') => {
84
+ validateString(name, format)
84
85
  const helpers = AudioFormatHelpers[format]
85
- if (helpers === undefined) { throw Object.assign(new Error("invalid format"), { format }) }
86
+ if (helpers === undefined) { throw Object.assign(new Error(`invalid ${name}`), { format }) }
86
87
  return helpers
87
88
  }
88
89
 
89
- module.exports = { AudioFormatHelpers, getFormatHelpers }
90
+ module.exports = {
91
+ AudioFormatHelpers,
92
+ getFormatHelpers,
93
+ }
@@ -1,44 +1,47 @@
1
1
  const Globals = require('../globals')
2
+ const { assertInitialized, isAvailable } = require('../subsystems')
2
3
  const Bindings = require('../bindings')
3
4
  const { EventsViaPoll } = require('../events/events-via-poll')
5
+ const { lookupDevice } = require('../device-instance')
4
6
  const { AudioPlaybackStream } = require('./audio-playback-stream')
5
7
  const { AudioRecordingStream } = require('./audio-recording-stream')
6
8
  const { getFormatHelpers } = require('./format-helpers')
7
- const {
8
- make: makeDevice,
9
- makeDefault: makeDefaultDevice,
10
- } = require('./device')
11
-
12
-
13
- Globals.audioDevices.playback = [ makeDefaultDevice() ]
14
- Globals.audioDevices.recording = [ makeDefaultDevice() ]
15
- if (Globals.info.initialized.audio) {
16
- Globals.audioDevices.playback.push(...Bindings.audio_getDevices(false).map(makeDevice))
17
- Globals.audioDevices.recording.push(...Bindings.audio_getDevices(true).map(makeDevice))
18
- }
9
+ const { convert } = require('./conversion')
10
+ const { validateBuffer } = require('../validate')
19
11
 
20
12
 
21
13
  const validEvents = [ 'deviceAdd', 'deviceRemove' ]
22
14
 
23
15
  const makeModule = (type, Stream) => new class extends EventsViaPoll {
24
- constructor () { super(validEvents) }
16
+ constructor () { super(validEvents, () => { assertInitialized('audio') }) }
25
17
 
26
18
  get devices () {
19
+ assertInitialized('audio')
27
20
  Globals.events.poll()
28
21
  return [ ...Globals.audioDevices[type] ]
29
22
  }
30
23
 
31
- openDevice (device = null, options = {}) {
32
- Globals.events.poll()
33
- const list = Globals.audioDevices[type]
34
- if (device === null) { device = list[0] }
35
- else if (!list.includes(device)) { throw Object.assign(new Error(`device must be from sdl.audio.${type}.devices`), { device }) }
24
+ openDevice (requested = null, options = {}) {
25
+ assertInitialized('audio')
26
+
27
+ if (requested === null) {
28
+ Globals.events.poll()
29
+ return new Stream(Globals.audioDevices[type][0], options)
30
+ }
36
31
 
32
+ const device = lookupDevice(requested, `audio.${type}`, () => Globals.audioDevices[type])
37
33
  return new Stream(device, options)
38
34
  }
39
35
  }()
40
36
 
41
37
  const audio = {
38
+ isAvailable () { return isAvailable('audio') },
39
+
40
+ get drivers () {
41
+ assertInitialized('audio')
42
+ return Bindings.audio_getDrivers()
43
+ },
44
+
42
45
  playback: makeModule('playback', AudioPlaybackStream),
43
46
  recording: makeModule('recording', AudioRecordingStream),
44
47
 
@@ -47,13 +50,15 @@ const audio = {
47
50
  maxSampleValue (format) { return getFormatHelpers(format).maxSampleValue },
48
51
  zeroSampleValue (format) { return getFormatHelpers(format).zeroSampleValue },
49
52
 
53
+ convert,
54
+
50
55
  readSample (format, buffer, offset) {
51
- if (!(buffer instanceof Buffer)) { throw Object.assign(new Error("buffer must be a Buffer"), { buffer }) }
56
+ validateBuffer('buffer', buffer)
52
57
  return getFormatHelpers(format).reader.call(buffer, offset)
53
58
  },
54
59
 
55
60
  writeSample (format, buffer, value, offset) {
56
- if (!(buffer instanceof Buffer)) { throw Object.assign(new Error("buffer must be a Buffer"), { buffer }) }
61
+ validateBuffer('buffer', buffer)
57
62
  return getFormatHelpers(format).writer.call(buffer, value, offset)
58
63
  },
59
64
  }
@@ -1,5 +1,6 @@
1
1
  const Globals = require('../globals')
2
2
  const Bindings = require('../bindings')
3
+ const { INT32_MAX } = require('../validate')
3
4
 
4
5
  let timeout
5
6
 
@@ -12,6 +13,7 @@ const resetTimeout = () => {
12
13
 
13
14
  process.on('beforeExit', (code) => {
14
15
  if (code !== 0) { return }
16
+ if (Globals.audioStreams.size === 0) { return }
15
17
 
16
18
  let duration = 0
17
19
 
@@ -21,23 +23,24 @@ process.on('beforeExit', (code) => {
21
23
  if (!stream.playing) { continue }
22
24
 
23
25
  let queued = null
24
- let device = null
25
26
  try {
27
+ Bindings.audio_flush(stream.id)
26
28
  queued = Bindings.audio_getQueued(stream.id)
27
- device = Bindings.audio_getDeviceFormat(stream.id)
28
29
  }
29
- catch (_) { }
30
- if (!queued || !device) { continue }
31
-
32
- const { channels, frequency, bytesPerSample } = stream
33
- const bytesPerSecond = channels * frequency * bytesPerSample
34
- duration = Math.max(duration, queued / bytesPerSecond + device.buffered / device.frequency)
30
+ catch { }
31
+ // Skipping empty queues misses the device buffer's tail, so if something else kept the loop alive while the queue drained, up to one device buffer gets cut off at exit. Accepted.
32
+ if (!queued) { continue }
33
+
34
+ const { device, channels, frequency, bytesPerSample, frequencyRatio } = stream
35
+ const bytesPerSecond = channels * frequency * bytesPerSample * frequencyRatio
36
+ const tail = device.frequency ? device.buffered / device.frequency : 0
37
+ duration = Math.max(duration, queued / bytesPerSecond + tail)
35
38
  }
36
39
 
37
40
  if (duration) {
38
- // Keeps Node.js alive while audio is playing
41
+ // Keeps Node.js alive while audio is playing; don't unref it
39
42
  resetTimeout()
40
- timeout = setTimeout(() => { timeout = null }, Math.min(duration * 1e3, 2 ** 31 - 1))
43
+ timeout = setTimeout(() => { timeout = null }, Math.min(duration * 1e3, INT32_MAX))
41
44
  }
42
45
  })
43
46
 
@@ -0,0 +1,9 @@
1
+ const { validateNonNegativeInt32 } = require('../validate')
2
+
3
+ const validateBytes = (buffer, bytes) => {
4
+ validateNonNegativeInt32('bytes', bytes)
5
+ // Attaching the whole buffer is fine: Node's inspect only prints its first 50 bytes.
6
+ if (buffer.length < bytes) { throw Object.assign(new Error("buffer is smaller than expected"), { buffer, bytes }) }
7
+ }
8
+
9
+ module.exports = { validateBytes }
@@ -2,10 +2,13 @@ const Bindings = require('./bindings')
2
2
  const Globals = require('./globals')
3
3
 
4
4
  process.on('exit', (code) => {
5
- if (code !== 0) { return }
6
-
7
5
  Globals.events.stopPolling()
8
6
 
7
+ if (code !== 0) {
8
+ Bindings.global_cleanup()
9
+ return
10
+ }
11
+
9
12
  const errors = []
10
13
 
11
14
  for (const window of Globals.windows.all.values()) {
@@ -18,22 +21,22 @@ process.on('exit', (code) => {
18
21
  catch (error) { errors.push(error) }
19
22
  }
20
23
 
21
- for (const joystick of Globals.joystickInstances.all.values()) {
24
+ for (const joystick of Globals.joystickInstances.all) {
22
25
  try { joystick.close() }
23
26
  catch (error) { errors.push(error) }
24
27
  }
25
28
 
26
- for (const gamepad of Globals.gamepadInstances.all.values()) {
29
+ for (const gamepad of Globals.gamepadInstances.all) {
27
30
  try { gamepad.close() }
28
31
  catch (error) { errors.push(error) }
29
32
  }
30
33
 
31
- for (const sensor of Globals.sensorInstances.all.values()) {
34
+ for (const sensor of Globals.sensorInstances.all) {
32
35
  try { sensor.close() }
33
36
  catch (error) { errors.push(error) }
34
37
  }
35
38
 
36
39
  Bindings.global_cleanup()
37
40
 
38
- if (errors.length) { throw new AggregateError(errors, "errors occurred during process exit cleanup") }
41
+ if (errors.length) { throw new AggregateError(errors, "errors occurred during exit cleanup") }
39
42
  })
@@ -1,20 +1,25 @@
1
1
  const Globals = require('../globals')
2
+ const { assertInitialized, isAvailable } = require('../subsystems')
2
3
  const Bindings = require('../bindings')
3
4
  const { EventsViaPoll } = require('../events/events-via-poll')
5
+ const { validateString } = require('../validate')
4
6
 
5
7
  const validEvents = [ 'update' ]
6
8
 
7
9
  const clipboard = new class extends EventsViaPoll {
8
- constructor () { super(validEvents) }
10
+ constructor () { super(validEvents, () => { assertInitialized('video') }) }
11
+
12
+ isAvailable () { return isAvailable('video') }
9
13
 
10
14
  get text () {
15
+ assertInitialized('video')
11
16
  Globals.events.poll()
12
17
  return Bindings.clipboard_getText()
13
18
  }
14
19
 
15
20
  setText (text) {
16
- if (typeof text !== 'string') { throw Object.assign(new Error("text must be a string"), { text }) }
17
-
21
+ assertInitialized('video')
22
+ validateString('text', text)
18
23
  Bindings.clipboard_setText(text)
19
24
  }
20
25
  }()
@@ -0,0 +1,61 @@
1
+ const Globals = require('./globals')
2
+ const { EventsViaPoll } = require('./events/events-via-poll')
3
+ const { validateNotClosed, validateObject } = require('./validate')
4
+
5
+ const lookupDevice = (requested, name, getDevices) => {
6
+ validateObject('device', requested)
7
+
8
+ Globals.events.poll()
9
+
10
+ const device = getDevices().find(({ id }) => id === requested.id)
11
+ if (!device) { throw Object.assign(new Error(`device must be from sdl.${name}.devices`), { device: requested }) }
12
+ return device
13
+ }
14
+
15
+ class DeviceInstance extends EventsViaPoll {
16
+ constructor (validEvents, device, instances, closeBinding) {
17
+ super(validEvents)
18
+
19
+ this._device = device
20
+ this._instances = instances
21
+ this._closeBinding = closeBinding
22
+
23
+ this._closed = false
24
+
25
+ instances.all.add(this)
26
+ const collection = instances.byId.get(device.id) ?? new Set()
27
+ instances.byId.set(device.id, collection)
28
+ collection.add(this)
29
+ }
30
+
31
+ get device () { return this._device }
32
+
33
+ _beforeCloseBinding () {}
34
+
35
+ get closed () { return this._closed }
36
+ close () {
37
+ validateNotClosed(this)
38
+
39
+ this._closed = true
40
+
41
+ this._instances.all.delete(this)
42
+ const collection = this._instances.byId.get(this._device.id)
43
+ collection.delete(this)
44
+ if (collection.size === 0) { this._instances.byId.delete(this._device.id) }
45
+ this._beforeCloseBinding()
46
+
47
+ // This call could throw if the device is gone
48
+ try { this._closeBinding(this._device.id) }
49
+ catch {}
50
+
51
+ // We might be inside an event listener
52
+ this._retire(() => Object.assign(new Error("instance is closed"), { id: this._device.id }))
53
+
54
+ Globals.events.withoutPolling(() => {
55
+ try { this.emit('close', { type: 'close' }) }
56
+ catch (error) { this.emit('error', error) }
57
+ })
58
+ }
59
+ }
60
+
61
+ module.exports = { DeviceInstance, lookupDevice }
@@ -1,62 +1,66 @@
1
1
  const Globals = require('../globals')
2
2
  const { EventEmitter } = require('node:events')
3
3
 
4
- let _ID = 0
5
- const activeEmitters = new Set()
6
-
7
4
  const commonEvents = [ 'newListener', 'removeListener', 'error', '*' ]
5
+ const metaEvents = [ 'newListener', 'removeListener' ]
6
+ const undemandingEvents = [ ...metaEvents, 'error' ]
8
7
 
9
8
  class EventsViaPoll extends EventEmitter {
10
- constructor (validEvents) {
9
+ constructor (validEvents, assertReady = null) {
11
10
  super()
12
11
 
13
12
  this._validEvents = validEvents
14
-
15
- const id = _ID++
16
- let count = 0
13
+ this._internalListeners = new Set()
17
14
 
18
15
  // NOTE: this needs to be first, otherwise it will emit for 'newListener'
19
- this.on('removeListener', (type) => {
20
- if (type === 'newListener' || type === 'removeListener') { return }
21
-
22
- count--
23
- if (count !== 0) { return }
16
+ this._addInternalListener('removeListener', (type) => {
17
+ if (undemandingEvents.includes(type)) { return }
24
18
 
25
- activeEmitters.delete(id)
26
- if (activeEmitters.size !== 0) { return }
27
-
28
- Globals.events.switchToPollingSlow()
19
+ Globals.events.unref()
29
20
  })
30
21
 
31
- this.on('newListener', (type) => {
22
+ this._addInternalListener('newListener', (type) => {
32
23
  if (this._makeRetiredError) { throw this._makeRetiredError() }
33
24
 
34
25
  if (!commonEvents.includes(type) && !validEvents.includes(type)) {
35
26
  throw Object.assign(new Error("invalid event"), { type })
36
27
  }
37
28
 
38
- if (type === 'newListener' || type === 'removeListener') { return }
39
-
40
- count++
41
- if (count !== 1) { return }
29
+ if (undemandingEvents.includes(type)) { return }
42
30
 
43
- activeEmitters.add(id)
44
- if (activeEmitters.size !== 1) { return }
31
+ if (assertReady) { assertReady() }
45
32
 
46
- Globals.events.switchToPollingFast()
33
+ Globals.events.ref()
47
34
  })
48
35
  }
49
36
 
37
+ _addInternalListener (type, listener) {
38
+ this._internalListeners.add(listener)
39
+ this.on(type, listener)
40
+ }
41
+
50
42
  _retire (makeError) {
51
43
  this._makeRetiredError = makeError
52
44
  process.nextTick(() => { this.removeAllListeners() })
53
45
  }
54
46
 
55
47
  removeAllListeners (type) {
56
- const types = type !== undefined ? [ type ] : this.eventNames()
57
- for (const eventType of types) {
58
- if (eventType === 'newListener' || eventType === 'removeListener') { continue }
59
- super.removeAllListeners(eventType)
48
+ if (type === undefined) {
49
+ const types = this.eventNames().filter((name) => name !== 'removeListener')
50
+ for (const eventType of [ ...types, 'removeListener' ]) {
51
+ this.removeAllListeners(eventType)
52
+ }
53
+ return this
54
+ }
55
+
56
+ if (!metaEvents.includes(type)) {
57
+ super.removeAllListeners(type)
58
+ return this
59
+ }
60
+
61
+ for (const listener of this.listeners(type)) {
62
+ if (this._internalListeners.has(listener)) { continue }
63
+ this.removeListener(type, listener)
60
64
  }
61
65
  return this
62
66
  }