@kmamal/sdl 1.0.0-4 → 1.0.0-8

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 (84) hide show
  1. package/CHANGELOG.md +12 -6
  2. package/binding.gyp +3 -0
  3. package/package.json +6 -13
  4. package/scripts/util/common.js +2 -2
  5. package/src/javascript/audio/audio-playback-stream.js +9 -10
  6. package/src/javascript/audio/audio-recording-stream.js +9 -8
  7. package/src/javascript/audio/audio-stream.js +100 -44
  8. package/src/javascript/audio/conversion.js +41 -0
  9. package/src/javascript/audio/devices.js +11 -0
  10. package/src/javascript/audio/events.js +65 -0
  11. package/src/javascript/audio/format-helpers.js +8 -4
  12. package/src/javascript/audio/index.js +25 -20
  13. package/src/javascript/audio/prevent-exit.js +12 -9
  14. package/src/javascript/audio/validate.js +9 -0
  15. package/src/javascript/cleanup.js +9 -6
  16. package/src/javascript/clipboard/index.js +8 -3
  17. package/src/javascript/device-instance.js +61 -0
  18. package/src/javascript/events/events-via-poll.js +33 -27
  19. package/src/javascript/events/index.js +76 -482
  20. package/src/javascript/events/try.js +22 -0
  21. package/src/javascript/gamepad/{device.js → devices.js} +4 -5
  22. package/src/javascript/gamepad/events.js +66 -0
  23. package/src/javascript/gamepad/gamepad-instance.js +12 -160
  24. package/src/javascript/gamepad/index.js +15 -16
  25. package/src/javascript/globals.js +10 -1
  26. package/src/javascript/index.js +2 -5
  27. package/src/javascript/joystick/devices.js +43 -0
  28. package/src/javascript/joystick/events.js +129 -0
  29. package/src/javascript/joystick/index.js +9 -18
  30. package/src/javascript/joystick/joystick-device-instance.js +175 -0
  31. package/src/javascript/joystick/joystick-instance.js +12 -158
  32. package/src/javascript/keyboard/index.js +20 -10
  33. package/src/javascript/keyboard/key-mapping.js +46 -27
  34. package/src/javascript/mouse/index.js +36 -29
  35. package/src/javascript/sensor/events.js +21 -0
  36. package/src/javascript/sensor/index.js +13 -2
  37. package/src/javascript/sensor/sensor-instance.js +7 -47
  38. package/src/javascript/subsystems.js +56 -0
  39. package/src/javascript/touch/index.js +9 -4
  40. package/src/javascript/validate.js +114 -0
  41. package/src/javascript/video/conversion.js +63 -0
  42. package/src/javascript/video/events.js +179 -0
  43. package/src/javascript/video/format-helpers.js +10 -8
  44. package/src/javascript/video/index.js +28 -14
  45. package/src/javascript/video/validate.js +45 -0
  46. package/src/javascript/video/window.js +144 -161
  47. package/src/native/audio.cpp +457 -151
  48. package/src/native/audio.h +12 -6
  49. package/src/native/clipboard.cpp +8 -37
  50. package/src/native/enums.cpp +2 -0
  51. package/src/native/events.cpp +416 -354
  52. package/src/native/events.h +67 -65
  53. package/src/native/gamepad.cpp +86 -103
  54. package/src/native/gamepad.h +7 -8
  55. package/src/native/global.cpp +190 -85
  56. package/src/native/global.h +48 -2
  57. package/src/native/joystick.cpp +180 -274
  58. package/src/native/joystick.h +12 -6
  59. package/src/native/keyboard.cpp +60 -22
  60. package/src/native/keyboard.h +2 -1
  61. package/src/native/module.cpp +20 -3
  62. package/src/native/mouse.cpp +27 -58
  63. package/src/native/packed.cpp +106 -0
  64. package/src/native/packed.h +91 -0
  65. package/src/native/power.cpp +7 -1
  66. package/src/native/power.h +2 -2
  67. package/src/native/sensor.cpp +61 -69
  68. package/src/native/sensor.h +3 -3
  69. package/src/native/testing.cpp +131 -0
  70. package/src/native/testing.h +16 -0
  71. package/src/native/threads.cpp +300 -0
  72. package/src/native/threads.h +36 -0
  73. package/src/native/touch.cpp +32 -43
  74. package/src/native/touch.h +2 -1
  75. package/src/native/video.cpp +145 -95
  76. package/src/native/video.h +6 -3
  77. package/src/native/window.cpp +155 -218
  78. package/src/native/window.h +21 -20
  79. package/src/types/index.d.ts +141 -69
  80. package/src/javascript/audio/device.js +0 -37
  81. package/src/javascript/joystick/device.js +0 -13
  82. package/src/javascript/joystick/shared.js +0 -90
  83. package/src/javascript/worker.js +0 -88
  84. package/src/types/worker.d.ts +0 -71
package/CHANGELOG.md CHANGED
@@ -7,18 +7,21 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
- ## [v1.0.0] - 2026-10-01
11
-
12
- The library now builds against SDL3 (3.4.x) instead of SDL2. This release contains breaking changes, see the [migration guide](https://github.com/kmamal/node-sdl/tree/master/docs/migrating-to-sdl3.md) for a walkthrough.
10
+ ## [v1.0.0] - 2026-11-08
13
11
 
14
12
  ### Changed
15
13
 
16
- - Exceptions thrown in event listeners are re-emitted as an `'error'` event on the window or instance, following the usual `EventEmitter` semantics: with no `'error'` listener they surface as an uncaught exception. They no longer stop event delivery or crash the process.
14
+ - The library now builds against SDL3 (3.4.x) instead of SDL2. This introduces many breaking changes, see the [migration guide](https://github.com/kmamal/node-sdl/tree/master/docs/migrating-to-sdl3.md) for a walkthrough.
15
+ - All SDL subsystems are now initialized lazily, on first use. The `sdl.info.initialized` flags are gone and instead every submodule now has an `isAvailable()` function that tries to initialize the subsystem and returns `true` or `false`. Functions, properties, and event listeners that need an SDL subsystem throw if that subsystem has failed to initialize.
16
+ - `sdl.info.drivers.video` and `sdl.info.drivers.audio` moved to `sdl.video.drivers` and `sdl.audio.drivers`.
17
+ - `@kmamal/sdl` can now be imported from worker threads and works exactly as in the main thread with the exception of the video subsystem (`sdl.video`, `sdl.keyboard`, `sdl.mouse`, `sdl.touch`, and `sdl.clipboard`) which can only be used on the main thread. `@kmamal/sdl/helpers` is no longer needed and has been removed.
18
+ - Exceptions thrown in event listeners are re-emitted as an `'error'` event, following the usual `EventEmitter` semantics: with no `'error'` listener they surface as an uncaught exception. They no longer stop event delivery or crash the process.
17
19
  - Attaching a listener to a destroyed window or a closed instance or stream now throws, instead of silently never firing.
18
20
  - Audio and video formats are reported using the platform-independent enums. The platform-dependent ones are only used as input.
19
21
  - Character keys are reported as the unshifted character (`'ü'` instead of `'Ü'`), so `getKey(getScancode('ü'))` round-trips.
22
+ - Display device events now only include the device object itself. Read the changed props from the object.
23
+ - `sdl.keyboard.getState()` returns a `Uint8Array` of `0`/`1` values instead of an array of booleans.
20
24
  - steamHandle is now reported as a BigInt.
21
- - `@kmamal/sdl/helpers` is now `@kmamal/sdl/helpers`, and includes a lot of extra stuff.
22
25
 
23
26
  ### Added
24
27
 
@@ -29,10 +32,12 @@ The library now builds against SDL3 (3.4.x) instead of SDL2. This release contai
29
32
  - Relative mouse mode for FPS-style camera controls.
30
33
  - `mouseMove` and `ballMotion` events report relative movement through `dx` and `dy`.
31
34
  - Window event `'fingerCancel'`, fired when the system cancels a touch.
35
+ - Windows emit `'enterFullscreen'` and `'leaveFullscreen'` events when they enter or leave fullscreen mode.
32
36
  - Audio device objects report the `format`, `channels`, `frequency`, and `buffered` the device is running with while streams are open on them.
33
37
  - Gamepad buttons `misc1` and `touchpad` are now reported instead of arriving with `button: null`.
34
38
  - Pixel-format helpers similar to audio format helpers.
35
39
  - More scancodes and keys
40
+ - Sensor `'update'` events carry the reading (`x`, `y`, `z`) and the sensor's `timestamp`, so readings queued between polls are no longer lost.
36
41
 
37
42
  ### Fixed
38
43
 
@@ -50,6 +55,7 @@ Windows:
50
55
  - `setResizable()` and `setBorderless()` enforce the same mutual exclusivity as `createWindow()`.
51
56
  - `window.destroy()` no longer crashes when called from a `beforeClose` listener, or from a `move` or `resize` listener while the window is being dragged.
52
57
  - Removing all of a window's listeners no longer breaks event polling, lets the process exit while the window is open, or turns `destroy()` into a no-op.
58
+ - `window.render()` interprets `dstRect` in window coordinates, the same units as `width`/`height` and mouse events. On high-DPI displays it was previously in physical pixels, so a rectangle built from the window size covered only part of the window.
53
59
  - `window.render()` throws instead of silently presenting stale contents when updating the texture fails, and no longer corrupts memory or leaks after a failed render or renderer switch.
54
60
  - Windows recover from a lost graphics device instead of failing every `render()` from then on.
55
61
  - `window.render()` validates image `stride` and buffer sizes, preventing out-of-bounds reads, including for planar and packed YUV formats with odd dimensions.
@@ -98,7 +104,7 @@ Sensors:
98
104
 
99
105
  Audio:
100
106
 
101
- - `putData()` and `getData()` accept empty buffers as no-ops, and reject a `bytes` count that isn't a whole number of sample frames with a validation error.
107
+ - `putData()` and `getData()` accept empty buffers as no-ops. `putData()` rejects a `bytes` count that isn't a whole number of sample frames with a validation error.
102
108
  - `buffered` values larger than `32768` are rejected instead of silently truncated, and the buffer size the driver actually uses is reported on the stream's device.
103
109
  - `playbackStream.queued` no longer reports negative values for queues over 2 GiB.
104
110
  - `stream.playing` is `false` once the stream is closed.
package/binding.gyp CHANGED
@@ -19,6 +19,9 @@
19
19
  'src/native/audio.cpp',
20
20
  'src/native/clipboard.cpp',
21
21
  'src/native/power.cpp',
22
+ 'src/native/threads.cpp',
23
+ 'src/native/packed.cpp',
24
+ 'src/native/testing.cpp',
22
25
  ],
23
26
  'dependencies': [
24
27
  "<!(node -p \"require('node-addon-api').targets\"):node_addon_api_except",
package/package.json CHANGED
@@ -1,5 +1,5 @@
1
1
  {
2
- "version": "1.0.0-4",
2
+ "version": "1.0.0-8",
3
3
  "name": "@kmamal/sdl",
4
4
  "description": "SDL bindings for Node.js",
5
5
  "keywords": [
@@ -41,7 +41,7 @@
41
41
  "url": "git+ssh://git@github.com/kmamal/node-sdl.git"
42
42
  },
43
43
  "engines": {
44
- "node": ">=22"
44
+ "node": ">=22.16.0"
45
45
  },
46
46
  "main": "./src/javascript/index.js",
47
47
  "types": "./src/types/index.d.ts",
@@ -49,15 +49,12 @@
49
49
  ".": {
50
50
  "types": "./src/types/index.d.ts",
51
51
  "default": "./src/javascript/index.js"
52
- },
53
- "./worker": {
54
- "types": "./src/types/worker.d.ts",
55
- "default": "./src/javascript/worker.js"
56
52
  }
57
53
  },
58
54
  "gypfile": true,
59
55
  "scripts": {
60
56
  "test": "npx @kmamal/testing",
57
+ "test:stress": "npx @kmamal/testing 'tests/stress/*.stress.mjs'",
61
58
  "install": "cd scripts && node install.mjs",
62
59
  "download-release": "cd scripts && node download-release.mjs",
63
60
  "download-sdl": "cd scripts && node download-sdl.mjs",
@@ -67,9 +64,8 @@
67
64
  "clean": "cd scripts && node clean.mjs"
68
65
  },
69
66
  "devDependencies": {
70
- "@kmamal/evdev": "0.0.8",
71
67
  "@kmamal/testing": "0.0.34",
72
- "@types/node": "26.6.4",
68
+ "@types/node": "26.6.6",
73
69
  "node-addon-api": "8.9.2",
74
70
  "node-gyp": "13.1.0"
75
71
  },
@@ -77,13 +73,10 @@
77
73
  "sdl": {
78
74
  "owner": "kmamal",
79
75
  "repo": "build-sdl",
80
- "version": "3.4.14"
76
+ "version": "3.4.18"
81
77
  }
82
78
  },
83
- "allowScripts": {
84
- "@kmamal/evdev": true
85
- },
86
79
  "dependencies": {
87
- "modern-tar": "0.8.5"
80
+ "modern-tar": "0.8.6"
88
81
  }
89
82
  }
@@ -1,5 +1,5 @@
1
- const Fs = require('fs')
2
- const Path = require('path')
1
+ const Fs = require('node:fs')
2
+ const Path = require('node:path')
3
3
 
4
4
  const dir = {}
5
5
  dir.root = Path.join(__dirname, '../..')
@@ -1,6 +1,8 @@
1
1
  const Globals = require('../globals')
2
2
  const Bindings = require('../bindings')
3
3
  const { AudioStream } = require('./audio-stream')
4
+ const { validateBytes } = require('./validate')
5
+ const { validateBuffer } = require('../validate')
4
6
  const { resetTimeout } = require('./prevent-exit')
5
7
 
6
8
  class AudioPlaybackStream extends AudioStream {
@@ -10,21 +12,18 @@ class AudioPlaybackStream extends AudioStream {
10
12
 
11
13
  get queued () {
12
14
  Globals.events.poll()
13
- if (this._closed) { throw Object.assign(new Error("stream is closed"), { id: this._id }) }
15
+ this._assertOpen()
14
16
 
15
17
  return Bindings.audio_getQueued(this._id)
16
18
  }
17
19
 
18
- putData (buffer, bytes = null) {
19
- if (this._closed) { throw Object.assign(new Error("stream is closed"), { id: this._id }) }
20
+ putData (buffer, _bytes) {
21
+ this._assertOpen()
20
22
 
21
- if (!(buffer instanceof Buffer)) { throw Object.assign(new Error("buffer must be a Buffer"), { buffer }) }
22
- bytes ??= buffer.length
23
- if (!Number.isInteger(bytes)) { throw Object.assign(new Error("bytes must be an integer"), { bytes }) }
24
- if (bytes < 0 || bytes > 2 ** 31 - 1) { throw Object.assign(new Error("bytes must be a non-negative 32-bit integer"), { bytes }) }
25
- if (buffer.length < bytes) { throw Object.assign(new Error("buffer is smaller than expected"), { buffer, bytes }) }
26
- const frameSize = this._channels * this._bytesPerSample
27
- if (bytes % frameSize !== 0) { throw Object.assign(new Error(`bytes must be a multiple of ${frameSize}`), { bytes }) }
23
+ validateBuffer('buffer', buffer)
24
+ const bytes = _bytes === undefined ? buffer.length : _bytes
25
+ validateBytes(buffer, bytes)
26
+ if (bytes % this._frameSize !== 0) { throw Object.assign(new Error(`bytes must be a multiple of ${this._frameSize}`), { bytes }) }
28
27
 
29
28
  if (bytes === 0) { return }
30
29
 
@@ -1,6 +1,8 @@
1
1
  const Globals = require('../globals')
2
2
  const Bindings = require('../bindings')
3
3
  const { AudioStream } = require('./audio-stream')
4
+ const { validateBytes } = require('./validate')
5
+ const { validateBuffer } = require('../validate')
4
6
 
5
7
  class AudioRecordingStream extends AudioStream {
6
8
  constructor (device, options) {
@@ -9,19 +11,18 @@ class AudioRecordingStream extends AudioStream {
9
11
 
10
12
  get available () {
11
13
  Globals.events.poll()
12
- if (this._closed) { throw Object.assign(new Error("stream is closed"), { id: this._id }) }
14
+ this._assertOpen()
13
15
 
14
16
  return Bindings.audio_getAvailable(this._id)
15
17
  }
16
18
 
17
- getData (buffer, bytes = null) {
18
- if (this._closed) { throw Object.assign(new Error("stream is closed"), { id: this._id }) }
19
+ getData (buffer, _bytes) {
20
+ this._assertOpen()
19
21
 
20
- if (!(buffer instanceof Buffer)) { throw Object.assign(new Error("buffer must be a Buffer"), { buffer }) }
21
- bytes ??= buffer.length
22
- if (!Number.isInteger(bytes)) { throw Object.assign(new Error("bytes must be an integer"), { bytes }) }
23
- if (bytes < 0 || bytes > 2 ** 31 - 1) { throw Object.assign(new Error("bytes must be a non-negative 32-bit integer"), { bytes }) }
24
- if (buffer.length < bytes) { throw Object.assign(new Error("buffer is smaller than expected"), { buffer, bytes }) }
22
+ validateBuffer('buffer', buffer)
23
+ const bytes = _bytes === undefined ? buffer.length : _bytes
24
+ validateBytes(buffer, bytes)
25
+ // Unlike putData(), a partial frame isn't rejected: SDL rounds the read down to whole frames and the return value reports what was read.
25
26
 
26
27
  if (bytes === 0) { return 0 }
27
28
 
@@ -2,60 +2,96 @@ const Globals = require('../globals')
2
2
  const Bindings = require('../bindings')
3
3
  const Enums = require('../enums')
4
4
  const { EventsViaPoll } = require('../events/events-via-poll')
5
- const { AudioFormatHelpers } = require('./format-helpers')
6
- const { update: updateDevice } = require('./device')
7
-
8
- const validEvents = [ 'close' ]
5
+ const { tryEmit } = require('../events/try')
6
+ const { getFormatHelpers } = require('./format-helpers')
7
+ const {
8
+ validateBoolean,
9
+ validateObject,
10
+ validateBuffer,
11
+ validateNonNegativeFloat,
12
+ validateNumberRange,
13
+ validateIntegerRange,
14
+ validatePositiveInt32,
15
+ } = require('../validate')
16
+
17
+ const notifyEvents = { playback: 'drain', recording: 'readable' }
9
18
 
10
19
  class AudioStream extends EventsViaPoll {
11
20
  constructor (recording, device, options) {
12
- super(validEvents)
21
+ const notifyEvent = notifyEvents[recording ? 'recording' : 'playback']
22
+ super([ 'close', notifyEvent ])
13
23
 
14
- if (typeof options !== 'object' || options === null) { throw Object.assign(new Error("options must be an object"), { options }) }
24
+ validateObject('options', options)
15
25
 
16
26
  const {
17
27
  channels = 1,
18
28
  frequency = 48000,
19
29
  format = 'f32',
20
30
  buffered = 4096,
31
+ gain = 1,
32
+ frequencyRatio = 1,
21
33
  } = options
22
34
 
23
- if (!Number.isInteger(channels)) { throw Object.assign(new Error("channels must be an integer"), { channels }) }
24
- if (channels < 1 || channels > 8) { throw Object.assign(new Error("channels must be between 1 and 8"), { channels }) }
25
- if (!Number.isInteger(frequency)) { throw Object.assign(new Error("frequency must be an integer"), { frequency }) }
26
- if (frequency <= 0 || frequency > 2 ** 31 - 1) { throw Object.assign(new Error("frequency must be a positive 32-bit integer"), { frequency }) }
27
- if (typeof format !== 'string') { throw Object.assign(new Error("format must be a string"), { format }) }
28
- if (!Number.isInteger(buffered)) { throw Object.assign(new Error("buffered must be an integer"), { buffered }) }
29
- if (buffered <= 0) { throw Object.assign(new Error("buffered must be positive"), { buffered }) }
30
- if (buffered > 2 ** 15) { throw Object.assign(new Error("buffered must be at most 32768"), { buffered }) }
31
- if (buffered !== 2 ** (32 - Math.clz32(buffered) - 1)) { throw Object.assign(new Error("buffered must be a power of 2"), { buffered }) }
35
+ validateIntegerRange('channels', channels, 1, 8)
36
+ validatePositiveInt32('frequency', frequency)
37
+ const helper = getFormatHelpers(format)
38
+ validatePositiveInt32('buffered', buffered)
39
+ validateNonNegativeFloat('gain', gain)
40
+ validateNumberRange('frequencyRatio', frequencyRatio, 0.01, 100)
32
41
 
33
42
  const _format = Enums.audioFormat[format]
34
- if (_format === undefined) { throw Object.assign(new Error("invalid format"), { format }) }
35
43
 
36
- const id = Bindings.audio_open(device.id, recording, frequency, _format, channels, buffered)
44
+ const notify = (underruns, missing, available) => {
45
+ if (this._closed) { return }
46
+ const event = recording
47
+ ? { type: notifyEvent, available }
48
+ : { type: notifyEvent, underruns, missing }
49
+ Globals.events.withoutPolling(() => { tryEmit(this, notifyEvent, event) })
50
+ }
51
+
52
+ const id = Bindings.audio_open(device.id, recording, frequency, _format, channels, buffered, notify, device)
53
+ try {
54
+ if (gain !== 1) { Bindings.audio_setGain(id, gain) }
55
+ if (frequencyRatio !== 1) { Bindings.audio_setFrequencyRatio(id, frequencyRatio) }
56
+ }
57
+ catch (error) {
58
+ try { Bindings.audio_close(id, device) }
59
+ catch { }
60
+ throw error
61
+ }
37
62
 
38
63
  this._id = id
39
64
  this._recording = recording
40
- const helper = AudioFormatHelpers[format]
65
+ this._frameSize = channels * helper.bytesPerSample
41
66
 
42
67
  this._device = device
43
68
  this._channels = channels
44
- this._format = helper.name
45
69
  this._frequency = frequency
46
70
 
47
71
  this._playing = false
48
72
  this._closed = false
73
+ this._gain = gain
74
+ this._frequencyRatio = frequencyRatio
49
75
 
50
- this._bytesPerSample = helper.bytesPerSample
51
- this._minSampleValue = helper.minSampleValue
52
- this._maxSampleValue = helper.maxSampleValue
53
- this._zeroSampleValue = helper.zeroSampleValue
54
- this._reader = helper.reader
55
- this._writer = helper.writer
76
+ this._helper = helper
56
77
 
57
78
  Globals.audioStreams.set(this._id, this)
58
- updateDevice(this._device)
79
+
80
+ const notifyListeners = () => this.listenerCount(notifyEvent) + this.listenerCount('*')
81
+ this._addInternalListener('newListener', (type) => {
82
+ if ((type !== notifyEvent && type !== '*') || notifyListeners() !== 0) { return }
83
+ Bindings.audio_setNotify(this._id, true)
84
+ })
85
+ this._addInternalListener('removeListener', (type) => {
86
+ if ((type !== notifyEvent && type !== '*') || notifyListeners() !== 0 || this._closed) { return }
87
+ Bindings.audio_setNotify(this._id, false)
88
+ })
89
+ }
90
+
91
+ _makeClosedError () { return Object.assign(new Error("stream is closed"), { id: this._id }) }
92
+
93
+ _assertOpen () {
94
+ if (this._closed) { throw this._makeClosedError() }
59
95
  }
60
96
 
61
97
  get id () { return this._id }
@@ -64,27 +100,49 @@ class AudioStream extends EventsViaPoll {
64
100
  get channels () { return this._channels }
65
101
  get frequency () { return this._frequency }
66
102
 
67
- get format () { return this._format }
68
- get bytesPerSample () { return this._bytesPerSample }
69
- get minSampleValue () { return this._minSampleValue }
70
- get maxSampleValue () { return this._maxSampleValue }
71
- get zeroSampleValue () { return this._zeroSampleValue }
103
+ get format () { return this._helper.name }
104
+ get bytesPerSample () { return this._helper.bytesPerSample }
105
+ get minSampleValue () { return this._helper.minSampleValue }
106
+ get maxSampleValue () { return this._helper.maxSampleValue }
107
+ get zeroSampleValue () { return this._helper.zeroSampleValue }
72
108
 
73
109
  readSample (buffer, offset) {
74
- if (!(buffer instanceof Buffer)) { throw Object.assign(new Error("buffer must be a Buffer"), { buffer }) }
75
- return this._reader.call(buffer, offset)
110
+ validateBuffer('buffer', buffer)
111
+ return this._helper.reader.call(buffer, offset)
76
112
  }
77
113
 
78
114
  writeSample (buffer, value, offset) {
79
- if (!(buffer instanceof Buffer)) { throw Object.assign(new Error("buffer must be a Buffer"), { buffer }) }
80
- return this._writer.call(buffer, value, offset)
115
+ validateBuffer('buffer', buffer)
116
+ return this._helper.writer.call(buffer, value, offset)
117
+ }
118
+
119
+ get gain () { return this._gain }
120
+ setGain (gain) {
121
+ this._assertOpen()
122
+
123
+ validateNonNegativeFloat('gain', gain)
124
+
125
+ Bindings.audio_setGain(this._id, gain)
126
+
127
+ this._gain = gain
128
+ }
129
+
130
+ get frequencyRatio () { return this._frequencyRatio }
131
+ setFrequencyRatio (frequencyRatio) {
132
+ this._assertOpen()
133
+
134
+ validateNumberRange('frequencyRatio', frequencyRatio, 0.01, 100)
135
+
136
+ Bindings.audio_setFrequencyRatio(this._id, frequencyRatio)
137
+
138
+ this._frequencyRatio = frequencyRatio
81
139
  }
82
140
 
83
141
  get playing () { return this._playing }
84
142
  play (play = true) {
85
- if (this._closed) { throw Object.assign(new Error("stream is closed"), { id: this._id }) }
143
+ this._assertOpen()
86
144
 
87
- if (typeof play !== 'boolean') { throw Object.assign(new Error("play must be a boolean"), { play }) }
145
+ validateBoolean('play', play)
88
146
 
89
147
  Bindings.audio_play(this._id, play)
90
148
 
@@ -96,14 +154,14 @@ class AudioStream extends EventsViaPoll {
96
154
  }
97
155
 
98
156
  clear () {
99
- if (this._closed) { throw Object.assign(new Error("stream is closed"), { id: this._id }) }
157
+ this._assertOpen()
100
158
 
101
159
  Bindings.audio_clear(this._id)
102
160
  }
103
161
 
104
162
  get closed () { return this._closed }
105
163
  close () {
106
- if (this._closed) { throw Object.assign(new Error("stream is closed"), { id: this._id }) }
164
+ this._assertOpen()
107
165
 
108
166
  this._closed = true
109
167
  this._playing = false
@@ -111,13 +169,11 @@ class AudioStream extends EventsViaPoll {
111
169
  Globals.audioStreams.delete(this._id)
112
170
 
113
171
  // This call could throw if the device is gone
114
- try { Bindings.audio_close(this._id) }
115
- catch (_) { }
116
-
117
- updateDevice(this._device)
172
+ try { Bindings.audio_close(this._id, this._device) }
173
+ catch { }
118
174
 
119
175
  // We might be inside an event listener
120
- this._retire(() => Object.assign(new Error("stream is closed"), { id: this._id }))
176
+ this._retire(() => this._makeClosedError())
121
177
 
122
178
  Globals.events.withoutPolling(() => {
123
179
  try { this.emit('close', { type: 'close' }) }
@@ -0,0 +1,41 @@
1
+ const Bindings = require('../bindings')
2
+ const Enums = require('../enums')
3
+ const { getFormatHelpers } = require('./format-helpers')
4
+ const { INT32_MAX, validateIntegerRange, validatePositiveInt32, validateObject, validateBuffer } = require('../validate')
5
+
6
+ const checkSpec = (spec, name) => {
7
+ validateObject(name, spec)
8
+ const { format = 'f32', channels = 1, frequency = 48000 } = spec
9
+ const helpers = getFormatHelpers(format, `${name}.format`)
10
+ validateIntegerRange(`${name}.channels`, channels, 1, 8)
11
+ validatePositiveInt32(`${name}.frequency`, frequency)
12
+ return { format: Enums.audioFormat[format], channels, frequency, frameSize: channels * helpers.bytesPerSample }
13
+ }
14
+
15
+ const checkSource = (src, srcData) => {
16
+ if (srcData.length % src.frameSize !== 0) { throw Object.assign(new Error(`srcData length must be a multiple of ${src.frameSize}`), { length: srcData.length }) }
17
+ if (srcData.length > INT32_MAX) { throw Object.assign(new Error("srcData must be smaller than 2 GiB"), { length: srcData.length }) }
18
+ }
19
+
20
+ const convert = (srcSpec, srcData, dstSpec, dstData) => {
21
+ const src = checkSpec(srcSpec, 'srcSpec')
22
+ validateBuffer('srcData', srcData)
23
+ const dst = checkSpec(dstSpec, 'dstSpec')
24
+ checkSource(src, srcData)
25
+
26
+ const dstSize = Math.ceil(srcData.length / src.frameSize * dst.frequency / src.frequency) * dst.frameSize
27
+ if (dstSize > INT32_MAX) { throw Object.assign(new Error("converted data must be smaller than 2 GiB"), { size: dstSize }) }
28
+
29
+ if (dstData === undefined) {
30
+ if (srcData.length === 0) { return Buffer.alloc(0) }
31
+ const buffer = Buffer.alloc(dstSize)
32
+ const written = Bindings.audio_convert(src.format, src.channels, src.frequency, srcData, srcData.length, dst.format, dst.channels, dst.frequency, buffer)
33
+ return buffer.subarray(0, written)
34
+ }
35
+
36
+ validateBuffer('dstData', dstData)
37
+ if (srcData.length === 0) { return 0 }
38
+ return Bindings.audio_convert(src.format, src.channels, src.frequency, srcData, srcData.length, dst.format, dst.channels, dst.frequency, dstData)
39
+ }
40
+
41
+ module.exports = { convert }
@@ -0,0 +1,11 @@
1
+ const Globals = require('../globals')
2
+ const Bindings = require('../bindings')
3
+
4
+ const refreshDevices = () => {
5
+ Globals.audioDevices.playback = Bindings.audio_getDevices(false)
6
+ Globals.audioDevices.recording = Bindings.audio_getDevices(true)
7
+ }
8
+
9
+ module.exports = {
10
+ refreshDevices,
11
+ }
@@ -0,0 +1,65 @@
1
+ const Globals = require('../globals')
2
+ const { audio: audioModule } = require('.')
3
+ const { tryEmit, tryCall } = require('../events/try')
4
+
5
+ const handleEvent = (event) => {
6
+ // Thread might not have initialized this subsystem
7
+ if (!Globals.initialized.audio) { return }
8
+
9
+ const { type, audioDeviceType, defaultDevice } = event
10
+ delete event.audioDeviceType
11
+ delete event.defaultDevice
12
+
13
+ const list = Globals.audioDevices[audioDeviceType]
14
+ const emitter = audioModule[audioDeviceType]
15
+
16
+ Object.assign(list[0], defaultDevice)
17
+
18
+ switch (type) {
19
+ case 'deviceAdd': {
20
+ const { device } = event
21
+ delete event.device
22
+
23
+ if (list.some((a) => a.id === device.id)) { return }
24
+ list.push(device)
25
+ event.device = device
26
+ } break
27
+
28
+ case 'deviceRemove': {
29
+ const { deviceId } = event
30
+ delete event.deviceId
31
+
32
+ const logical = Globals.audioStreams.get(deviceId)
33
+ if (logical) {
34
+ tryCall(() => { logical.close() })
35
+ return
36
+ }
37
+
38
+ const index = list.findIndex((a) => a.id === deviceId)
39
+ if (index === -1) { return }
40
+ const device = list[index]
41
+ list.splice(index, 1)
42
+
43
+ for (const stream of [ ...Globals.audioStreams.values() ]) {
44
+ if (stream.device === device) {
45
+ tryCall(() => { stream.close() })
46
+ }
47
+ }
48
+
49
+ event.device = device
50
+ } break
51
+
52
+ case 'deviceFormatChange': {
53
+ const { deviceId, format } = event
54
+ const device = Globals.audioStreams.get(deviceId)?.device
55
+ ?? list.find((a) => a.id === deviceId)
56
+ if (device) { Object.assign(device, format) }
57
+ } return
58
+
59
+ // No default
60
+ }
61
+
62
+ tryEmit(emitter, type, event)
63
+ }
64
+
65
+ module.exports = { handleEvent }
@@ -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
  }